blob: 62bcc32bb4ef653b83894c5377986e1c2bc2caac [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.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"
Reid Spencer5694b6e2007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000032#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000034#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000035#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000037#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetFrameInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetLowering.h"
42#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000043#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattnerda8abb02005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000057static cl::opt<bool>
58ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
59 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000060#else
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000061static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000062#endif
63
Jim Laskeyeb577ba2006-08-02 12:30:23 +000064//===---------------------------------------------------------------------===//
65///
66/// RegisterScheduler class - Track the registration of instruction schedulers.
67///
68//===---------------------------------------------------------------------===//
69MachinePassRegistry RegisterScheduler::Registry;
70
71//===---------------------------------------------------------------------===//
72///
73/// ISHeuristic command line option for instruction schedulers.
74///
75//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000076namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000077 cl::opt<RegisterScheduler::FunctionPassCtor, false,
78 RegisterPassParser<RegisterScheduler> >
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000079 ISHeuristic("pre-RA-sched",
Chris Lattner3700f902006-08-03 00:18:59 +000080 cl::init(&createDefaultScheduler),
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000081 cl::desc("Instruction schedulers available (before register allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000082
Jim Laskey9ff542f2006-08-01 18:29:48 +000083 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000084 defaultListDAGScheduler("default", " Best scheduler for the target",
85 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000086} // namespace
87
Chris Lattnerbf996f12007-04-30 17:29:31 +000088namespace { struct AsmOperandInfo; }
89
Chris Lattner864635a2006-02-22 22:37:12 +000090namespace {
91 /// RegsForValue - This struct represents the physical registers that a
92 /// particular value is assigned and the type information about the value.
93 /// This is needed because values can be promoted into larger registers and
94 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000095 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohmanb6f5b002007-06-28 23:29:44 +000096 /// Regs - This list holds the register (for legal and promoted values)
Chris Lattner864635a2006-02-22 22:37:12 +000097 /// or register set (for expanded values) that the value should be assigned
98 /// to.
99 std::vector<unsigned> Regs;
100
101 /// RegVT - The value type of each register.
102 ///
103 MVT::ValueType RegVT;
104
105 /// ValueVT - The value type of the LLVM value, which may be promoted from
106 /// RegVT or made from merging the two expanded parts.
107 MVT::ValueType ValueVT;
108
109 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
110
111 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
112 : RegVT(regvt), ValueVT(valuevt) {
113 Regs.push_back(Reg);
114 }
115 RegsForValue(const std::vector<unsigned> &regs,
116 MVT::ValueType regvt, MVT::ValueType valuevt)
117 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
118 }
119
120 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
121 /// this value and returns the result as a ValueVT value. This uses
122 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000123 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000124 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000125 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000126
127 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
128 /// specified value into the registers specified by this object. This uses
129 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000130 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000131 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000132 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000133
134 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
135 /// operand list. This adds the code marker and includes the number of
136 /// values added into it.
137 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000138 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000139 };
140}
Evan Cheng4ef10862006-01-23 07:01:07 +0000141
Chris Lattner1c08c712005-01-07 07:47:53 +0000142namespace llvm {
143 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000144 /// createDefaultScheduler - This creates an instruction scheduler appropriate
145 /// for the target.
146 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
147 SelectionDAG *DAG,
148 MachineBasicBlock *BB) {
149 TargetLowering &TLI = IS->getTargetLowering();
150
151 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
152 return createTDListDAGScheduler(IS, DAG, BB);
153 } else {
154 assert(TLI.getSchedulingPreference() ==
155 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
156 return createBURRListDAGScheduler(IS, DAG, BB);
157 }
158 }
159
160
161 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000162 /// FunctionLoweringInfo - This contains information that is global to a
163 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000164 class FunctionLoweringInfo {
165 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000166 TargetLowering &TLI;
167 Function &Fn;
168 MachineFunction &MF;
169 SSARegMap *RegMap;
170
171 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
172
173 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
174 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
175
176 /// ValueMap - Since we emit code for the function a basic block at a time,
177 /// we must remember which virtual registers hold the values for
178 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000179 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000180
181 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
182 /// the entry block. This allows the allocas to be efficiently referenced
183 /// anywhere in the function.
184 std::map<const AllocaInst*, int> StaticAllocaMap;
185
Duncan Sandsf4070822007-06-15 19:04:19 +0000186#ifndef NDEBUG
187 SmallSet<Instruction*, 8> CatchInfoLost;
188 SmallSet<Instruction*, 8> CatchInfoFound;
189#endif
190
Chris Lattner1c08c712005-01-07 07:47:53 +0000191 unsigned MakeReg(MVT::ValueType VT) {
192 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
193 }
Chris Lattner571e4342006-10-27 21:36:01 +0000194
195 /// isExportedInst - Return true if the specified value is an instruction
196 /// exported from its block.
197 bool isExportedInst(const Value *V) {
198 return ValueMap.count(V);
199 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000200
Chris Lattner3c384492006-03-16 19:51:18 +0000201 unsigned CreateRegForValue(const Value *V);
202
Chris Lattner1c08c712005-01-07 07:47:53 +0000203 unsigned InitializeRegForValue(const Value *V) {
204 unsigned &R = ValueMap[V];
205 assert(R == 0 && "Already initialized this value register!");
206 return R = CreateRegForValue(V);
207 }
208 };
209}
210
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000211/// isSelector - Return true if this instruction is a call to the
212/// eh.selector intrinsic.
213static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000214 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000215 return II->getIntrinsicID() == Intrinsic::eh_selector;
Duncan Sandsf4070822007-06-15 19:04:19 +0000216 return false;
217}
218
Chris Lattner1c08c712005-01-07 07:47:53 +0000219/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000220/// PHI nodes or outside of the basic block that defines it, or used by a
221/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000222static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
223 if (isa<PHINode>(I)) return true;
224 BasicBlock *BB = I->getParent();
225 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000226 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000227 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000228 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000229 return true;
230 return false;
231}
232
Chris Lattnerbf209482005-10-30 19:42:35 +0000233/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000234/// entry block, return true. This includes arguments used by switches, since
235/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000236static bool isOnlyUsedInEntryBlock(Argument *A) {
237 BasicBlock *Entry = A->getParent()->begin();
238 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000239 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000240 return false; // Use not in entry block.
241 return true;
242}
243
Chris Lattner1c08c712005-01-07 07:47:53 +0000244FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000245 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000246 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
247
Chris Lattnerbf209482005-10-30 19:42:35 +0000248 // Create a vreg for each argument register that is not dead and is used
249 // outside of the entry block for the function.
250 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
251 AI != E; ++AI)
252 if (!isOnlyUsedInEntryBlock(AI))
253 InitializeRegForValue(AI);
254
Chris Lattner1c08c712005-01-07 07:47:53 +0000255 // Initialize the mapping of values to registers. This is only set up for
256 // instruction values that are used outside of the block that defines
257 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000258 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000259 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
260 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000261 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000262 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000263 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000264 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000265 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000266 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000267
Reid Spencerb83eb642006-10-20 07:07:24 +0000268 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000269 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000270 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000271 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000272 }
273
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000274 for (; BB != EB; ++BB)
275 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000276 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
277 if (!isa<AllocaInst>(I) ||
278 !StaticAllocaMap.count(cast<AllocaInst>(I)))
279 InitializeRegForValue(I);
280
281 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
282 // also creates the initial PHI MachineInstrs, though none of the input
283 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000284 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000285 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
286 MBBMap[BB] = MBB;
287 MF.getBasicBlockList().push_back(MBB);
288
289 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
290 // appropriate.
291 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000292 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
293 if (PN->use_empty()) continue;
294
295 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000296 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000297 unsigned PHIReg = ValueMap[PN];
298 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000299 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000300 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000301 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000302 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000303 }
304}
305
Chris Lattner3c384492006-03-16 19:51:18 +0000306/// CreateRegForValue - Allocate the appropriate number of virtual registers of
307/// the correctly promoted or expanded types. Assign these registers
308/// consecutive vreg numbers and return the first assigned number.
309unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
310 MVT::ValueType VT = TLI.getValueType(V->getType());
311
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000312 unsigned NumRegisters = TLI.getNumRegisters(VT);
313 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
Bill Wendling95b39552007-04-24 21:13:23 +0000314
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000315 unsigned R = MakeReg(RegisterVT);
316 for (unsigned i = 1; i != NumRegisters; ++i)
317 MakeReg(RegisterVT);
318
Chris Lattner3c384492006-03-16 19:51:18 +0000319 return R;
320}
Chris Lattner1c08c712005-01-07 07:47:53 +0000321
322//===----------------------------------------------------------------------===//
323/// SelectionDAGLowering - This is the common target-independent lowering
324/// implementation that is parameterized by a TargetLowering object.
325/// Also, targets can overload any lowering method.
326///
327namespace llvm {
328class SelectionDAGLowering {
329 MachineBasicBlock *CurMBB;
330
Chris Lattner0da331f2007-02-04 01:31:47 +0000331 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000332
Chris Lattnerd3948112005-01-17 22:19:26 +0000333 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
334 /// them up and then emit token factor nodes when possible. This allows us to
335 /// get simple disambiguation between loads without worrying about alias
336 /// analysis.
337 std::vector<SDOperand> PendingLoads;
338
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000339 /// Case - A struct to record the Value for a switch case, and the
340 /// case's target basic block.
341 struct Case {
342 Constant* Low;
343 Constant* High;
344 MachineBasicBlock* BB;
345
346 Case() : Low(0), High(0), BB(0) { }
347 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
348 Low(low), High(high), BB(bb) { }
349 uint64_t size() const {
350 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
351 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
352 return (rHigh - rLow + 1ULL);
353 }
354 };
355
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000356 struct CaseBits {
357 uint64_t Mask;
358 MachineBasicBlock* BB;
359 unsigned Bits;
360
361 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
362 Mask(mask), BB(bb), Bits(bits) { }
363 };
364
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000365 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000366 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000367 typedef CaseVector::iterator CaseItr;
368 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000369
370 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
371 /// of conditional branches.
372 struct CaseRec {
373 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
374 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
375
376 /// CaseBB - The MBB in which to emit the compare and branch
377 MachineBasicBlock *CaseBB;
378 /// LT, GE - If nonzero, we know the current case value must be less-than or
379 /// greater-than-or-equal-to these Constants.
380 Constant *LT;
381 Constant *GE;
382 /// Range - A pair of iterators representing the range of case values to be
383 /// processed at this point in the binary search tree.
384 CaseRange Range;
385 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000386
387 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000388
389 /// The comparison function for sorting the switch case values in the vector.
390 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000391 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000392 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000393 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
394 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
395 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
396 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000397 }
398 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000399
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000400 struct CaseBitsCmp {
401 bool operator () (const CaseBits& C1, const CaseBits& C2) {
402 return C1.Bits > C2.Bits;
403 }
404 };
405
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000406 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000407
Chris Lattner1c08c712005-01-07 07:47:53 +0000408public:
409 // TLI - This is information that describes the available target features we
410 // need for lowering. This indicates when operations are unavailable,
411 // implemented with a libcall, etc.
412 TargetLowering &TLI;
413 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000414 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000415 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000416
Nate Begemanf15485a2006-03-27 01:32:24 +0000417 /// SwitchCases - Vector of CaseBlock structures used to communicate
418 /// SwitchInst code generation information.
419 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000420 /// JTCases - Vector of JumpTable structures used to communicate
421 /// SwitchInst code generation information.
422 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000423 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000424
Chris Lattner1c08c712005-01-07 07:47:53 +0000425 /// FuncInfo - Information about the function as a whole.
426 ///
427 FunctionLoweringInfo &FuncInfo;
428
429 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000430 AliasAnalysis &aa,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000431 FunctionLoweringInfo &funcinfo)
Dan Gohman5f43f922007-08-27 16:26:13 +0000432 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000433 FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000434 }
435
Chris Lattnera651cf62005-01-17 19:43:36 +0000436 /// getRoot - Return the current virtual root of the Selection DAG.
437 ///
438 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000439 if (PendingLoads.empty())
440 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000441
Chris Lattnerd3948112005-01-17 22:19:26 +0000442 if (PendingLoads.size() == 1) {
443 SDOperand Root = PendingLoads[0];
444 DAG.setRoot(Root);
445 PendingLoads.clear();
446 return Root;
447 }
448
449 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000450 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
451 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000452 PendingLoads.clear();
453 DAG.setRoot(Root);
454 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000455 }
456
Chris Lattner571e4342006-10-27 21:36:01 +0000457 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
458
Chris Lattner1c08c712005-01-07 07:47:53 +0000459 void visit(Instruction &I) { visit(I.getOpcode(), I); }
460
461 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000462 // Note: this doesn't use InstVisitor, because it has to work with
463 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000464 switch (Opcode) {
465 default: assert(0 && "Unknown instruction type encountered!");
466 abort();
467 // Build the switch statement using the Instruction.def file.
468#define HANDLE_INST(NUM, OPCODE, CLASS) \
469 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
470#include "llvm/Instruction.def"
471 }
472 }
473
474 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
475
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000476 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000477 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000478 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000479
480 SDOperand getIntPtrConstant(uint64_t Val) {
481 return DAG.getConstant(Val, TLI.getPointerTy());
482 }
483
Chris Lattner199862b2006-03-16 19:57:50 +0000484 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000485
Chris Lattner0da331f2007-02-04 01:31:47 +0000486 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000487 SDOperand &N = NodeMap[V];
488 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000489 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000490 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000491
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000492 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
493 std::set<unsigned> &OutputRegs,
494 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000495
Chris Lattner571e4342006-10-27 21:36:01 +0000496 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
497 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
498 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000499 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000500 void ExportFromCurrentBlock(Value *V);
Jim Laskey1da20a72007-02-23 21:45:01 +0000501 void LowerCallTo(Instruction &I,
502 const Type *CalledValueTy, unsigned CallingConv,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000503 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
504 MachineBasicBlock *LandingPad = NULL);
505
Chris Lattner1c08c712005-01-07 07:47:53 +0000506 // Terminator instructions.
507 void visitRet(ReturnInst &I);
508 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000509 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000510 void visitUnreachable(UnreachableInst &I) { /* noop */ }
511
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000512 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000513 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000514 CaseRecVector& WorkList,
515 Value* SV,
516 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000517 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000518 CaseRecVector& WorkList,
519 Value* SV,
520 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000521 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000522 CaseRecVector& WorkList,
523 Value* SV,
524 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000525 bool handleBitTestsSwitchCase(CaseRec& CR,
526 CaseRecVector& WorkList,
527 Value* SV,
528 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000529 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000530 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
531 void visitBitTestCase(MachineBasicBlock* NextMBB,
532 unsigned Reg,
533 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000534 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000535 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
536 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000537
Chris Lattner1c08c712005-01-07 07:47:53 +0000538 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000539 void visitInvoke(InvokeInst &I);
540 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000541
Dan Gohman7f321562007-06-25 16:23:39 +0000542 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000543 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000544 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000545 if (I.getType()->isFPOrFPVector())
546 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000547 else
Dan Gohman7f321562007-06-25 16:23:39 +0000548 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000549 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000550 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000551 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000552 if (I.getType()->isFPOrFPVector())
553 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000554 else
Dan Gohman7f321562007-06-25 16:23:39 +0000555 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000556 }
Dan Gohman7f321562007-06-25 16:23:39 +0000557 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
558 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
559 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
560 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
561 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
562 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
563 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
564 void visitOr (User &I) { visitBinary(I, ISD::OR); }
565 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000566 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000567 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
568 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000569 void visitICmp(User &I);
570 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000571 // Visit the conversion instructions
572 void visitTrunc(User &I);
573 void visitZExt(User &I);
574 void visitSExt(User &I);
575 void visitFPTrunc(User &I);
576 void visitFPExt(User &I);
577 void visitFPToUI(User &I);
578 void visitFPToSI(User &I);
579 void visitUIToFP(User &I);
580 void visitSIToFP(User &I);
581 void visitPtrToInt(User &I);
582 void visitIntToPtr(User &I);
583 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000584
Chris Lattner2bbd8102006-03-29 00:11:43 +0000585 void visitExtractElement(User &I);
586 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000587 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000588
Chris Lattner1c08c712005-01-07 07:47:53 +0000589 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000590 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000591
592 void visitMalloc(MallocInst &I);
593 void visitFree(FreeInst &I);
594 void visitAlloca(AllocaInst &I);
595 void visitLoad(LoadInst &I);
596 void visitStore(StoreInst &I);
597 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
598 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000599 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000600 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000601 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000602
Chris Lattner1c08c712005-01-07 07:47:53 +0000603 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000604 void visitVAArg(VAArgInst &I);
605 void visitVAEnd(CallInst &I);
606 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000607
Chris Lattner7041ee32005-01-11 05:56:49 +0000608 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000609
610 void visitUserOp1(Instruction &I) {
611 assert(0 && "UserOp1 should not exist at instruction selection time!");
612 abort();
613 }
614 void visitUserOp2(Instruction &I) {
615 assert(0 && "UserOp2 should not exist at instruction selection time!");
616 abort();
617 }
618};
619} // end namespace llvm
620
Dan Gohman6183f782007-07-05 20:12:34 +0000621
622/// getCopyFromParts - Create a value that contains the
623/// specified legal parts combined into the value they represent.
624static SDOperand getCopyFromParts(SelectionDAG &DAG,
625 const SDOperand *Parts,
626 unsigned NumParts,
627 MVT::ValueType PartVT,
628 MVT::ValueType ValueVT,
Dan Gohman6183f782007-07-05 20:12:34 +0000629 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
630 if (!MVT::isVector(ValueVT) || NumParts == 1) {
631 SDOperand Val = Parts[0];
632
633 // If the value was expanded, copy from the top part.
634 if (NumParts > 1) {
635 assert(NumParts == 2 &&
636 "Cannot expand to more than 2 elts yet!");
637 SDOperand Hi = Parts[1];
Dan Gohman532dc2e2007-07-09 20:59:04 +0000638 if (!DAG.getTargetLoweringInfo().isLittleEndian())
Dan Gohman6183f782007-07-05 20:12:34 +0000639 std::swap(Val, Hi);
640 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
641 }
642
643 // Otherwise, if the value was promoted or extended, truncate it to the
644 // appropriate type.
645 if (PartVT == ValueVT)
646 return Val;
647
648 if (MVT::isVector(PartVT)) {
649 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
650 return DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
651 }
652
653 if (MVT::isInteger(PartVT) &&
654 MVT::isInteger(ValueVT)) {
655 if (ValueVT < PartVT) {
656 // For a truncate, see if we have any information to
657 // indicate whether the truncated bits will always be
658 // zero or sign-extension.
659 if (AssertOp != ISD::DELETED_NODE)
660 Val = DAG.getNode(AssertOp, PartVT, Val,
661 DAG.getValueType(ValueVT));
662 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
663 } else {
664 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
665 }
666 }
667
668 if (MVT::isFloatingPoint(PartVT) &&
669 MVT::isFloatingPoint(ValueVT))
670 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
671
672 if (MVT::getSizeInBits(PartVT) ==
673 MVT::getSizeInBits(ValueVT))
674 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
675
676 assert(0 && "Unknown mismatch!");
677 }
678
679 // Handle a multi-element vector.
680 MVT::ValueType IntermediateVT, RegisterVT;
681 unsigned NumIntermediates;
682 unsigned NumRegs =
683 DAG.getTargetLoweringInfo()
684 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
685 RegisterVT);
686
687 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
688 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
689 assert(RegisterVT == Parts[0].getValueType() &&
690 "Part type doesn't match part!");
691
692 // Assemble the parts into intermediate operands.
693 SmallVector<SDOperand, 8> Ops(NumIntermediates);
694 if (NumIntermediates == NumParts) {
695 // If the register was not expanded, truncate or copy the value,
696 // as appropriate.
697 for (unsigned i = 0; i != NumParts; ++i)
698 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
Dan Gohman532dc2e2007-07-09 20:59:04 +0000699 PartVT, IntermediateVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000700 } else if (NumParts > 0) {
701 // If the intermediate type was expanded, build the intermediate operands
702 // from the parts.
Dan Gohmanbe444ed2007-07-30 19:09:17 +0000703 assert(NumParts % NumIntermediates == 0 &&
Dan Gohman6183f782007-07-05 20:12:34 +0000704 "Must expand into a divisible number of parts!");
Dan Gohmanbe444ed2007-07-30 19:09:17 +0000705 unsigned Factor = NumParts / NumIntermediates;
Dan Gohman6183f782007-07-05 20:12:34 +0000706 for (unsigned i = 0; i != NumIntermediates; ++i)
707 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
Dan Gohman532dc2e2007-07-09 20:59:04 +0000708 PartVT, IntermediateVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000709 }
710
711 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
712 // operands.
713 return DAG.getNode(MVT::isVector(IntermediateVT) ?
714 ISD::CONCAT_VECTORS :
715 ISD::BUILD_VECTOR,
Dan Gohmanbe444ed2007-07-30 19:09:17 +0000716 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000717}
718
719/// getCopyToParts - Create a series of nodes that contain the
720/// specified value split into legal parts.
721static void getCopyToParts(SelectionDAG &DAG,
722 SDOperand Val,
723 SDOperand *Parts,
724 unsigned NumParts,
Dan Gohman532dc2e2007-07-09 20:59:04 +0000725 MVT::ValueType PartVT) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000726 TargetLowering &TLI = DAG.getTargetLoweringInfo();
727 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohman6183f782007-07-05 20:12:34 +0000728 MVT::ValueType ValueVT = Val.getValueType();
729
730 if (!MVT::isVector(ValueVT) || NumParts == 1) {
731 // If the value was expanded, copy from the parts.
732 if (NumParts > 1) {
733 for (unsigned i = 0; i != NumParts; ++i)
734 Parts[i] = DAG.getNode(ISD::EXTRACT_ELEMENT, PartVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +0000735 DAG.getConstant(i, PtrVT));
Dan Gohman532dc2e2007-07-09 20:59:04 +0000736 if (!DAG.getTargetLoweringInfo().isLittleEndian())
Dan Gohman6183f782007-07-05 20:12:34 +0000737 std::reverse(Parts, Parts + NumParts);
738 return;
739 }
740
741 // If there is a single part and the types differ, this must be
742 // a promotion.
743 if (PartVT != ValueVT) {
744 if (MVT::isVector(PartVT)) {
745 assert(MVT::isVector(ValueVT) &&
746 "Not a vector-vector cast?");
747 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
748 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
749 if (PartVT < ValueVT)
750 Val = DAG.getNode(ISD::TRUNCATE, PartVT, Val);
751 else
752 Val = DAG.getNode(ISD::ANY_EXTEND, PartVT, Val);
753 } else if (MVT::isFloatingPoint(PartVT) &&
754 MVT::isFloatingPoint(ValueVT)) {
755 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
756 } else if (MVT::getSizeInBits(PartVT) ==
757 MVT::getSizeInBits(ValueVT)) {
758 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
759 } else {
760 assert(0 && "Unknown mismatch!");
761 }
762 }
763 Parts[0] = Val;
764 return;
765 }
766
767 // Handle a multi-element vector.
768 MVT::ValueType IntermediateVT, RegisterVT;
769 unsigned NumIntermediates;
770 unsigned NumRegs =
771 DAG.getTargetLoweringInfo()
772 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
773 RegisterVT);
774 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
775
776 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
777 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
778
779 // Split the vector into intermediate operands.
780 SmallVector<SDOperand, 8> Ops(NumIntermediates);
781 for (unsigned i = 0; i != NumIntermediates; ++i)
782 if (MVT::isVector(IntermediateVT))
783 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
784 IntermediateVT, Val,
785 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +0000786 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +0000787 else
788 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
789 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +0000790 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +0000791
792 // Split the intermediate operands into legal parts.
793 if (NumParts == NumIntermediates) {
794 // If the register was not expanded, promote or copy the value,
795 // as appropriate.
796 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +0000797 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000798 } else if (NumParts > 0) {
799 // If the intermediate type was expanded, split each the value into
800 // legal parts.
801 assert(NumParts % NumIntermediates == 0 &&
802 "Must expand into a divisible number of parts!");
803 unsigned Factor = NumParts / NumIntermediates;
804 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +0000805 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000806 }
807}
808
809
Chris Lattner199862b2006-03-16 19:57:50 +0000810SDOperand SelectionDAGLowering::getValue(const Value *V) {
811 SDOperand &N = NodeMap[V];
812 if (N.Val) return N;
813
814 const Type *VTy = V->getType();
815 MVT::ValueType VT = TLI.getValueType(VTy);
816 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
817 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
818 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +0000819 SDOperand N1 = NodeMap[V];
820 assert(N1.Val && "visit didn't populate the ValueMap!");
821 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +0000822 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
823 return N = DAG.getGlobalAddress(GV, VT);
824 } else if (isa<ConstantPointerNull>(C)) {
825 return N = DAG.getConstant(0, TLI.getPointerTy());
826 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000827 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +0000828 return N = DAG.getNode(ISD::UNDEF, VT);
829
Dan Gohman7f321562007-06-25 16:23:39 +0000830 // Create a BUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000831 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +0000832 unsigned NumElements = PTy->getNumElements();
833 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
834
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000835 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000836 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
837
838 // Create a VConstant node with generic Vector type.
Dan Gohman7f321562007-06-25 16:23:39 +0000839 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
840 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000841 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000842 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
843 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000844 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +0000845 unsigned NumElements = PTy->getNumElements();
846 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000847
848 // Now that we know the number and type of the elements, push a
849 // Constant or ConstantFP node onto the ops list for each element of
Dan Gohman07a96762007-07-16 14:29:03 +0000850 // the vector constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000851 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000852 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000853 for (unsigned i = 0; i != NumElements; ++i)
854 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000855 } else {
Dan Gohman07a96762007-07-16 14:29:03 +0000856 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Chris Lattner199862b2006-03-16 19:57:50 +0000857 SDOperand Op;
858 if (MVT::isFloatingPoint(PVT))
859 Op = DAG.getConstantFP(0, PVT);
860 else
861 Op = DAG.getConstant(0, PVT);
862 Ops.assign(NumElements, Op);
863 }
864
Dan Gohman7f321562007-06-25 16:23:39 +0000865 // Create a BUILD_VECTOR node.
866 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
867 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
Chris Lattner0da331f2007-02-04 01:31:47 +0000868 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000869 } else {
870 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000871 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000872 }
873 }
874
875 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
876 std::map<const AllocaInst*, int>::iterator SI =
877 FuncInfo.StaticAllocaMap.find(AI);
878 if (SI != FuncInfo.StaticAllocaMap.end())
879 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
880 }
881
Chris Lattner251db182007-02-25 18:40:32 +0000882 unsigned InReg = FuncInfo.ValueMap[V];
883 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +0000884
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000885 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
886 unsigned NumRegs = TLI.getNumRegisters(VT);
Chris Lattner70c2a612006-03-31 02:06:56 +0000887
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000888 std::vector<unsigned> Regs(NumRegs);
889 for (unsigned i = 0; i != NumRegs; ++i)
890 Regs[i] = InReg + i;
891
892 RegsForValue RFV(Regs, RegisterVT, VT);
893 SDOperand Chain = DAG.getEntryNode();
894
895 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +0000896}
897
898
Chris Lattner1c08c712005-01-07 07:47:53 +0000899void SelectionDAGLowering::visitRet(ReturnInst &I) {
900 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000901 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000902 return;
903 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000904 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000905 NewValues.push_back(getRoot());
906 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
907 SDOperand RetOp = getValue(I.getOperand(i));
908
909 // If this is an integer return value, we need to promote it ourselves to
Dan Gohman6183f782007-07-05 20:12:34 +0000910 // the full width of a register, since getCopyToParts and Legalize will use
911 // ANY_EXTEND rather than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000912 // FIXME: C calling convention requires the return type to be promoted to
913 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000914 if (MVT::isInteger(RetOp.getValueType()) &&
915 RetOp.getValueType() < MVT::i64) {
916 MVT::ValueType TmpVT;
917 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
918 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
919 else
920 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000921 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer5694b6e2007-04-09 06:17:21 +0000922 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencerbcca3402007-01-03 16:49:33 +0000923 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer18da0722007-04-11 02:44:20 +0000924 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000925 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer18da0722007-04-11 02:44:20 +0000926 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencer47857812006-12-31 05:55:36 +0000927 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000928 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Dan Gohman6183f782007-07-05 20:12:34 +0000929 NewValues.push_back(RetOp);
930 NewValues.push_back(DAG.getConstant(false, MVT::i32));
931 } else {
932 MVT::ValueType VT = RetOp.getValueType();
933 unsigned NumParts = TLI.getNumRegisters(VT);
934 MVT::ValueType PartVT = TLI.getRegisterType(VT);
935 SmallVector<SDOperand, 4> Parts(NumParts);
Dan Gohman532dc2e2007-07-09 20:59:04 +0000936 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000937 for (unsigned i = 0; i < NumParts; ++i) {
938 NewValues.push_back(Parts[i]);
939 NewValues.push_back(DAG.getConstant(false, MVT::i32));
940 }
Nate Begemanee625572006-01-27 21:09:22 +0000941 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000942 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000943 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
944 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000945}
946
Chris Lattner571e4342006-10-27 21:36:01 +0000947/// ExportFromCurrentBlock - If this condition isn't known to be exported from
948/// the current basic block, add it to ValueMap now so that we'll get a
949/// CopyTo/FromReg.
950void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
951 // No need to export constants.
952 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
953
954 // Already exported?
955 if (FuncInfo.isExportedInst(V)) return;
956
957 unsigned Reg = FuncInfo.InitializeRegForValue(V);
958 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
959}
960
Chris Lattner8c494ab2006-10-27 23:50:33 +0000961bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
962 const BasicBlock *FromBB) {
963 // The operands of the setcc have to be in this block. We don't know
964 // how to export them from some other block.
965 if (Instruction *VI = dyn_cast<Instruction>(V)) {
966 // Can export from current BB.
967 if (VI->getParent() == FromBB)
968 return true;
969
970 // Is already exported, noop.
971 return FuncInfo.isExportedInst(V);
972 }
973
974 // If this is an argument, we can export it if the BB is the entry block or
975 // if it is already exported.
976 if (isa<Argument>(V)) {
977 if (FromBB == &FromBB->getParent()->getEntryBlock())
978 return true;
979
980 // Otherwise, can only export this if it is already exported.
981 return FuncInfo.isExportedInst(V);
982 }
983
984 // Otherwise, constants can always be exported.
985 return true;
986}
987
Chris Lattner6a586c82006-10-29 21:01:20 +0000988static bool InBlock(const Value *V, const BasicBlock *BB) {
989 if (const Instruction *I = dyn_cast<Instruction>(V))
990 return I->getParent() == BB;
991 return true;
992}
993
Chris Lattner571e4342006-10-27 21:36:01 +0000994/// FindMergedConditions - If Cond is an expression like
995void SelectionDAGLowering::FindMergedConditions(Value *Cond,
996 MachineBasicBlock *TBB,
997 MachineBasicBlock *FBB,
998 MachineBasicBlock *CurBB,
999 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001000 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001001 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001002
Reid Spencere4d87aa2006-12-23 06:05:41 +00001003 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1004 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001005 BOp->getParent() != CurBB->getBasicBlock() ||
1006 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1007 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001008 const BasicBlock *BB = CurBB->getBasicBlock();
1009
Reid Spencere4d87aa2006-12-23 06:05:41 +00001010 // If the leaf of the tree is a comparison, merge the condition into
1011 // the caseblock.
1012 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1013 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001014 // how to export them from some other block. If this is the first block
1015 // of the sequence, no exporting is needed.
1016 (CurBB == CurMBB ||
1017 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1018 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001019 BOp = cast<Instruction>(Cond);
1020 ISD::CondCode Condition;
1021 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1022 switch (IC->getPredicate()) {
1023 default: assert(0 && "Unknown icmp predicate opcode!");
1024 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1025 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1026 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1027 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1028 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1029 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1030 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1031 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1032 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1033 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1034 }
1035 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1036 ISD::CondCode FPC, FOC;
1037 switch (FC->getPredicate()) {
1038 default: assert(0 && "Unknown fcmp predicate opcode!");
1039 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1040 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1041 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1042 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1043 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1044 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1045 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1046 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1047 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1048 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1049 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1050 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1051 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1052 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1053 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1054 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1055 }
1056 if (FiniteOnlyFPMath())
1057 Condition = FOC;
1058 else
1059 Condition = FPC;
1060 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001061 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001062 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001063 }
1064
Chris Lattner571e4342006-10-27 21:36:01 +00001065 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001066 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001067 SwitchCases.push_back(CB);
1068 return;
1069 }
1070
1071 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001072 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001073 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001074 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001075 return;
1076 }
1077
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001078
1079 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001080 MachineFunction::iterator BBI = CurBB;
1081 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1082 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1083
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001084 if (Opc == Instruction::Or) {
1085 // Codegen X | Y as:
1086 // jmp_if_X TBB
1087 // jmp TmpBB
1088 // TmpBB:
1089 // jmp_if_Y TBB
1090 // jmp FBB
1091 //
Chris Lattner571e4342006-10-27 21:36:01 +00001092
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001093 // Emit the LHS condition.
1094 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1095
1096 // Emit the RHS condition into TmpBB.
1097 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1098 } else {
1099 assert(Opc == Instruction::And && "Unknown merge op!");
1100 // Codegen X & Y as:
1101 // jmp_if_X TmpBB
1102 // jmp FBB
1103 // TmpBB:
1104 // jmp_if_Y TBB
1105 // jmp FBB
1106 //
1107 // This requires creation of TmpBB after CurBB.
1108
1109 // Emit the LHS condition.
1110 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1111
1112 // Emit the RHS condition into TmpBB.
1113 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1114 }
Chris Lattner571e4342006-10-27 21:36:01 +00001115}
1116
Chris Lattnerdf19f272006-10-31 22:37:42 +00001117/// If the set of cases should be emitted as a series of branches, return true.
1118/// If we should emit this as a bunch of and/or'd together conditions, return
1119/// false.
1120static bool
1121ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1122 if (Cases.size() != 2) return true;
1123
Chris Lattner0ccb5002006-10-31 23:06:00 +00001124 // If this is two comparisons of the same values or'd or and'd together, they
1125 // will get folded into a single comparison, so don't emit two blocks.
1126 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1127 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1128 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1129 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1130 return false;
1131 }
1132
Chris Lattnerdf19f272006-10-31 22:37:42 +00001133 return true;
1134}
1135
Chris Lattner1c08c712005-01-07 07:47:53 +00001136void SelectionDAGLowering::visitBr(BranchInst &I) {
1137 // Update machine-CFG edges.
1138 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001139
1140 // Figure out which block is immediately after the current one.
1141 MachineBasicBlock *NextBlock = 0;
1142 MachineFunction::iterator BBI = CurMBB;
1143 if (++BBI != CurMBB->getParent()->end())
1144 NextBlock = BBI;
1145
1146 if (I.isUnconditional()) {
1147 // If this is not a fall-through branch, emit the branch.
1148 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +00001149 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001150 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001151
Chris Lattner57ab6592006-10-24 17:57:59 +00001152 // Update machine-CFG edges.
1153 CurMBB->addSuccessor(Succ0MBB);
1154
1155 return;
1156 }
1157
1158 // If this condition is one of the special cases we handle, do special stuff
1159 // now.
1160 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001161 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001162
1163 // If this is a series of conditions that are or'd or and'd together, emit
1164 // this as a sequence of branches instead of setcc's with and/or operations.
1165 // For example, instead of something like:
1166 // cmp A, B
1167 // C = seteq
1168 // cmp D, E
1169 // F = setle
1170 // or C, F
1171 // jnz foo
1172 // Emit:
1173 // cmp A, B
1174 // je foo
1175 // cmp D, E
1176 // jle foo
1177 //
1178 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1179 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001180 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001181 BOp->getOpcode() == Instruction::Or)) {
1182 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001183 // If the compares in later blocks need to use values not currently
1184 // exported from this block, export them now. This block should always
1185 // be the first entry.
1186 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1187
Chris Lattnerdf19f272006-10-31 22:37:42 +00001188 // Allow some cases to be rejected.
1189 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001190 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1191 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1192 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1193 }
1194
1195 // Emit the branch for this block.
1196 visitSwitchCase(SwitchCases[0]);
1197 SwitchCases.erase(SwitchCases.begin());
1198 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001199 }
1200
Chris Lattner0ccb5002006-10-31 23:06:00 +00001201 // Okay, we decided not to do this, remove any inserted MBB's and clear
1202 // SwitchCases.
1203 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1204 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1205
Chris Lattnerdf19f272006-10-31 22:37:42 +00001206 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001207 }
1208 }
Chris Lattner24525952006-10-24 18:07:37 +00001209
1210 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001211 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001212 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001213 // Use visitSwitchCase to actually insert the fast branch sequence for this
1214 // cond branch.
1215 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001216}
1217
Nate Begemanf15485a2006-03-27 01:32:24 +00001218/// visitSwitchCase - Emits the necessary code to represent a single node in
1219/// the binary search tree resulting from lowering a switch instruction.
1220void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001221 SDOperand Cond;
1222 SDOperand CondLHS = getValue(CB.CmpLHS);
1223
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001224 // Build the setcc now.
1225 if (CB.CmpMHS == NULL) {
1226 // Fold "(X == true)" to X and "(X == false)" to !X to
1227 // handle common cases produced by branch lowering.
1228 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1229 Cond = CondLHS;
1230 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1231 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1232 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1233 } else
1234 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1235 } else {
1236 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001237
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001238 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1239 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1240
1241 SDOperand CmpOp = getValue(CB.CmpMHS);
1242 MVT::ValueType VT = CmpOp.getValueType();
1243
1244 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1245 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1246 } else {
1247 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1248 Cond = DAG.getSetCC(MVT::i1, SUB,
1249 DAG.getConstant(High-Low, VT), ISD::SETULE);
1250 }
1251
1252 }
1253
Nate Begemanf15485a2006-03-27 01:32:24 +00001254 // Set NextBlock to be the MBB immediately after the current one, if any.
1255 // This is used to avoid emitting unnecessary branches to the next block.
1256 MachineBasicBlock *NextBlock = 0;
1257 MachineFunction::iterator BBI = CurMBB;
1258 if (++BBI != CurMBB->getParent()->end())
1259 NextBlock = BBI;
1260
1261 // If the lhs block is the next block, invert the condition so that we can
1262 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001263 if (CB.TrueBB == NextBlock) {
1264 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001265 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1266 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1267 }
1268 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001269 DAG.getBasicBlock(CB.TrueBB));
1270 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001271 DAG.setRoot(BrCond);
1272 else
1273 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001274 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001275 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001276 CurMBB->addSuccessor(CB.TrueBB);
1277 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001278}
1279
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001280/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001281void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001282 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001283 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001284 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001285 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1286 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1287 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1288 Table, Index));
1289 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001290}
1291
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001292/// visitJumpTableHeader - This function emits necessary code to produce index
1293/// in the JumpTable from switch case.
1294void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1295 SelectionDAGISel::JumpTableHeader &JTH) {
1296 // Subtract the lowest switch case value from the value being switched on
1297 // and conditional branch to default mbb if the result is greater than the
1298 // difference between smallest and largest cases.
1299 SDOperand SwitchOp = getValue(JTH.SValue);
1300 MVT::ValueType VT = SwitchOp.getValueType();
1301 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1302 DAG.getConstant(JTH.First, VT));
1303
1304 // The SDNode we just created, which holds the value being switched on
1305 // minus the the smallest case value, needs to be copied to a virtual
1306 // register so it can be used as an index into the jump table in a
1307 // subsequent basic block. This value may be smaller or larger than the
1308 // target's pointer type, and therefore require extension or truncating.
Dan Gohman7f321562007-06-25 16:23:39 +00001309 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001310 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1311 else
1312 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1313
1314 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1315 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1316 JT.Reg = JumpTableReg;
1317
1318 // Emit the range check for the jump table, and branch to the default
1319 // block for the switch statement if the value being switched on exceeds
1320 // the largest case in the switch.
1321 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1322 DAG.getConstant(JTH.Last-JTH.First,VT),
1323 ISD::SETUGT);
1324
1325 // Set NextBlock to be the MBB immediately after the current one, if any.
1326 // This is used to avoid emitting unnecessary branches to the next block.
1327 MachineBasicBlock *NextBlock = 0;
1328 MachineFunction::iterator BBI = CurMBB;
1329 if (++BBI != CurMBB->getParent()->end())
1330 NextBlock = BBI;
1331
1332 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1333 DAG.getBasicBlock(JT.Default));
1334
1335 if (JT.MBB == NextBlock)
1336 DAG.setRoot(BrCond);
1337 else
1338 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001339 DAG.getBasicBlock(JT.MBB)));
1340
1341 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001342}
1343
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001344/// visitBitTestHeader - This function emits necessary code to produce value
1345/// suitable for "bit tests"
1346void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1347 // Subtract the minimum value
1348 SDOperand SwitchOp = getValue(B.SValue);
1349 MVT::ValueType VT = SwitchOp.getValueType();
1350 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1351 DAG.getConstant(B.First, VT));
1352
1353 // Check range
1354 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1355 DAG.getConstant(B.Range, VT),
1356 ISD::SETUGT);
1357
1358 SDOperand ShiftOp;
Dan Gohman7f321562007-06-25 16:23:39 +00001359 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001360 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1361 else
1362 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1363
1364 // Make desired shift
1365 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1366 DAG.getConstant(1, TLI.getPointerTy()),
1367 ShiftOp);
1368
1369 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1370 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1371 B.Reg = SwitchReg;
1372
1373 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1374 DAG.getBasicBlock(B.Default));
1375
1376 // Set NextBlock to be the MBB immediately after the current one, if any.
1377 // This is used to avoid emitting unnecessary branches to the next block.
1378 MachineBasicBlock *NextBlock = 0;
1379 MachineFunction::iterator BBI = CurMBB;
1380 if (++BBI != CurMBB->getParent()->end())
1381 NextBlock = BBI;
1382
1383 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1384 if (MBB == NextBlock)
1385 DAG.setRoot(BrRange);
1386 else
1387 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1388 DAG.getBasicBlock(MBB)));
1389
1390 CurMBB->addSuccessor(B.Default);
1391 CurMBB->addSuccessor(MBB);
1392
1393 return;
1394}
1395
1396/// visitBitTestCase - this function produces one "bit test"
1397void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1398 unsigned Reg,
1399 SelectionDAGISel::BitTestCase &B) {
1400 // Emit bit tests and jumps
1401 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1402
1403 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1404 SwitchVal,
1405 DAG.getConstant(B.Mask,
1406 TLI.getPointerTy()));
1407 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1408 DAG.getConstant(0, TLI.getPointerTy()),
1409 ISD::SETNE);
1410 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1411 AndCmp, DAG.getBasicBlock(B.TargetBB));
1412
1413 // Set NextBlock to be the MBB immediately after the current one, if any.
1414 // This is used to avoid emitting unnecessary branches to the next block.
1415 MachineBasicBlock *NextBlock = 0;
1416 MachineFunction::iterator BBI = CurMBB;
1417 if (++BBI != CurMBB->getParent()->end())
1418 NextBlock = BBI;
1419
1420 if (NextMBB == NextBlock)
1421 DAG.setRoot(BrAnd);
1422 else
1423 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1424 DAG.getBasicBlock(NextMBB)));
1425
1426 CurMBB->addSuccessor(B.TargetBB);
1427 CurMBB->addSuccessor(NextMBB);
1428
1429 return;
1430}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001431
Jim Laskeyb180aa12007-02-21 22:53:45 +00001432void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1433 // Retrieve successors.
1434 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001435 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001436
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001437 LowerCallTo(I, I.getCalledValue()->getType(),
1438 I.getCallingConv(),
1439 false,
1440 getValue(I.getOperand(0)),
1441 3, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001442
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001443 // If the value of the invoke is used outside of its defining block, make it
1444 // available as a virtual register.
1445 if (!I.use_empty()) {
1446 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1447 if (VMI != FuncInfo.ValueMap.end())
1448 DAG.setRoot(CopyValueToVirtualRegister(&I, VMI->second));
Jim Laskey183f47f2007-02-25 21:43:59 +00001449 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001450
1451 // Drop into normal successor.
1452 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1453 DAG.getBasicBlock(Return)));
1454
1455 // Update successor info
1456 CurMBB->addSuccessor(Return);
1457 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001458}
1459
1460void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1461}
1462
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001463/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001464/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001465bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001466 CaseRecVector& WorkList,
1467 Value* SV,
1468 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001469 Case& BackCase = *(CR.Range.second-1);
1470
1471 // Size is the number of Cases represented by this range.
1472 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001473 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001474 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001475
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001476 // Get the MachineFunction which holds the current MBB. This is used when
1477 // inserting any additional MBBs necessary to represent the switch.
1478 MachineFunction *CurMF = CurMBB->getParent();
1479
1480 // Figure out which block is immediately after the current one.
1481 MachineBasicBlock *NextBlock = 0;
1482 MachineFunction::iterator BBI = CR.CaseBB;
1483
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001484 if (++BBI != CurMBB->getParent()->end())
1485 NextBlock = BBI;
1486
1487 // TODO: If any two of the cases has the same destination, and if one value
1488 // is the same as the other, but has one bit unset that the other has set,
1489 // use bit manipulation to do two compares at once. For example:
1490 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1491
1492 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001493 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001494 // The last case block won't fall through into 'NextBlock' if we emit the
1495 // branches in this order. See if rearranging a case value would help.
1496 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001497 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001498 std::swap(*I, BackCase);
1499 break;
1500 }
1501 }
1502 }
1503
1504 // Create a CaseBlock record representing a conditional branch to
1505 // the Case's target mbb if the value being switched on SV is equal
1506 // to C.
1507 MachineBasicBlock *CurBlock = CR.CaseBB;
1508 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1509 MachineBasicBlock *FallThrough;
1510 if (I != E-1) {
1511 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1512 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1513 } else {
1514 // If the last case doesn't match, go to the default block.
1515 FallThrough = Default;
1516 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001517
1518 Value *RHS, *LHS, *MHS;
1519 ISD::CondCode CC;
1520 if (I->High == I->Low) {
1521 // This is just small small case range :) containing exactly 1 case
1522 CC = ISD::SETEQ;
1523 LHS = SV; RHS = I->High; MHS = NULL;
1524 } else {
1525 CC = ISD::SETLE;
1526 LHS = I->Low; MHS = SV; RHS = I->High;
1527 }
1528 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1529 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001530
1531 // If emitting the first comparison, just call visitSwitchCase to emit the
1532 // code into the current block. Otherwise, push the CaseBlock onto the
1533 // vector to be later processed by SDISel, and insert the node's MBB
1534 // before the next MBB.
1535 if (CurBlock == CurMBB)
1536 visitSwitchCase(CB);
1537 else
1538 SwitchCases.push_back(CB);
1539
1540 CurBlock = FallThrough;
1541 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001542
1543 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001544}
1545
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001546static inline bool areJTsAllowed(const TargetLowering &TLI) {
1547 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1548 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1549}
1550
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001551/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001552bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001553 CaseRecVector& WorkList,
1554 Value* SV,
1555 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001556 Case& FrontCase = *CR.Range.first;
1557 Case& BackCase = *(CR.Range.second-1);
1558
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001559 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1560 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1561
1562 uint64_t TSize = 0;
1563 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1564 I!=E; ++I)
1565 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001566
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001567 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001568 return false;
1569
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001570 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1571 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001572 return false;
1573
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001574 DOUT << "Lowering jump table\n"
1575 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001576 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001577
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001578 // Get the MachineFunction which holds the current MBB. This is used when
1579 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001580 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001581
1582 // Figure out which block is immediately after the current one.
1583 MachineBasicBlock *NextBlock = 0;
1584 MachineFunction::iterator BBI = CR.CaseBB;
1585
1586 if (++BBI != CurMBB->getParent()->end())
1587 NextBlock = BBI;
1588
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001589 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1590
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001591 // Create a new basic block to hold the code for loading the address
1592 // of the jump table, and jumping to it. Update successor information;
1593 // we will either branch to the default case for the switch, or the jump
1594 // table.
1595 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1596 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1597 CR.CaseBB->addSuccessor(Default);
1598 CR.CaseBB->addSuccessor(JumpTableBB);
1599
1600 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001601 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001602 // a case statement, push the case's BB onto the vector, otherwise, push
1603 // the default BB.
1604 std::vector<MachineBasicBlock*> DestBBs;
1605 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001606 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1607 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1608 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1609
1610 if ((Low <= TEI) && (TEI <= High)) {
1611 DestBBs.push_back(I->BB);
1612 if (TEI==High)
1613 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001614 } else {
1615 DestBBs.push_back(Default);
1616 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001617 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001618
1619 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001620 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001621 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1622 E = DestBBs.end(); I != E; ++I) {
1623 if (!SuccsHandled[(*I)->getNumber()]) {
1624 SuccsHandled[(*I)->getNumber()] = true;
1625 JumpTableBB->addSuccessor(*I);
1626 }
1627 }
1628
1629 // Create a jump table index for this jump table, or return an existing
1630 // one.
1631 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1632
1633 // Set the jump table information so that we can codegen it as a second
1634 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001635 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001636 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1637 (CR.CaseBB == CurMBB));
1638 if (CR.CaseBB == CurMBB)
1639 visitJumpTableHeader(JT, JTH);
1640
1641 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001642
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001643 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001644}
1645
1646/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1647/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001648bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001649 CaseRecVector& WorkList,
1650 Value* SV,
1651 MachineBasicBlock* Default) {
1652 // Get the MachineFunction which holds the current MBB. This is used when
1653 // inserting any additional MBBs necessary to represent the switch.
1654 MachineFunction *CurMF = CurMBB->getParent();
1655
1656 // Figure out which block is immediately after the current one.
1657 MachineBasicBlock *NextBlock = 0;
1658 MachineFunction::iterator BBI = CR.CaseBB;
1659
1660 if (++BBI != CurMBB->getParent()->end())
1661 NextBlock = BBI;
1662
1663 Case& FrontCase = *CR.Range.first;
1664 Case& BackCase = *(CR.Range.second-1);
1665 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1666
1667 // Size is the number of Cases represented by this range.
1668 unsigned Size = CR.Range.second - CR.Range.first;
1669
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001670 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1671 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001672 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001673 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001674
1675 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1676 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001677 uint64_t TSize = 0;
1678 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1679 I!=E; ++I)
1680 TSize += I->size();
1681
1682 uint64_t LSize = FrontCase.size();
1683 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001684 DOUT << "Selecting best pivot: \n"
1685 << "First: " << First << ", Last: " << Last <<"\n"
1686 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001687 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001688 J!=E; ++I, ++J) {
1689 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1690 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001691 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001692 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1693 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001694 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001695 // Should always split in some non-trivial place
1696 DOUT <<"=>Step\n"
1697 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1698 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1699 << "Metric: " << Metric << "\n";
1700 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001701 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001702 FMetric = Metric;
1703 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001704 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001705
1706 LSize += J->size();
1707 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001708 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001709 if (areJTsAllowed(TLI)) {
1710 // If our case is dense we *really* should handle it earlier!
1711 assert((FMetric > 0) && "Should handle dense range earlier!");
1712 } else {
1713 Pivot = CR.Range.first + Size/2;
1714 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001715
1716 CaseRange LHSR(CR.Range.first, Pivot);
1717 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001718 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001719 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1720
1721 // We know that we branch to the LHS if the Value being switched on is
1722 // less than the Pivot value, C. We use this to optimize our binary
1723 // tree a bit, by recognizing that if SV is greater than or equal to the
1724 // LHS's Case Value, and that Case Value is exactly one less than the
1725 // Pivot's Value, then we can branch directly to the LHS's Target,
1726 // rather than creating a leaf node for it.
1727 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001728 LHSR.first->High == CR.GE &&
1729 cast<ConstantInt>(C)->getSExtValue() ==
1730 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1731 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001732 } else {
1733 TrueBB = new MachineBasicBlock(LLVMBB);
1734 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1735 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1736 }
1737
1738 // Similar to the optimization above, if the Value being switched on is
1739 // known to be less than the Constant CR.LT, and the current Case Value
1740 // is CR.LT - 1, then we can branch directly to the target block for
1741 // the current Case Value, rather than emitting a RHS leaf node for it.
1742 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001743 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1744 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1745 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001746 } else {
1747 FalseBB = new MachineBasicBlock(LLVMBB);
1748 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1749 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1750 }
1751
1752 // Create a CaseBlock record representing a conditional branch to
1753 // the LHS node if the value being switched on SV is less than C.
1754 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001755 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1756 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001757
1758 if (CR.CaseBB == CurMBB)
1759 visitSwitchCase(CB);
1760 else
1761 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001762
1763 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001764}
1765
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001766/// handleBitTestsSwitchCase - if current case range has few destination and
1767/// range span less, than machine word bitwidth, encode case range into series
1768/// of masks and emit bit tests with these masks.
1769bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1770 CaseRecVector& WorkList,
1771 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00001772 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00001773 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001774
1775 Case& FrontCase = *CR.Range.first;
1776 Case& BackCase = *(CR.Range.second-1);
1777
1778 // Get the MachineFunction which holds the current MBB. This is used when
1779 // inserting any additional MBBs necessary to represent the switch.
1780 MachineFunction *CurMF = CurMBB->getParent();
1781
1782 unsigned numCmps = 0;
1783 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1784 I!=E; ++I) {
1785 // Single case counts one, case range - two.
1786 if (I->Low == I->High)
1787 numCmps +=1;
1788 else
1789 numCmps +=2;
1790 }
1791
1792 // Count unique destinations
1793 SmallSet<MachineBasicBlock*, 4> Dests;
1794 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1795 Dests.insert(I->BB);
1796 if (Dests.size() > 3)
1797 // Don't bother the code below, if there are too much unique destinations
1798 return false;
1799 }
1800 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1801 << "Total number of comparisons: " << numCmps << "\n";
1802
1803 // Compute span of values.
1804 Constant* minValue = FrontCase.Low;
1805 Constant* maxValue = BackCase.High;
1806 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1807 cast<ConstantInt>(minValue)->getSExtValue();
1808 DOUT << "Compare range: " << range << "\n"
1809 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1810 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1811
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00001812 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001813 (!(Dests.size() == 1 && numCmps >= 3) &&
1814 !(Dests.size() == 2 && numCmps >= 5) &&
1815 !(Dests.size() >= 3 && numCmps >= 6)))
1816 return false;
1817
1818 DOUT << "Emitting bit tests\n";
1819 int64_t lowBound = 0;
1820
1821 // Optimize the case where all the case values fit in a
1822 // word without having to subtract minValue. In this case,
1823 // we can optimize away the subtraction.
1824 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001825 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001826 range = cast<ConstantInt>(maxValue)->getSExtValue();
1827 } else {
1828 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1829 }
1830
1831 CaseBitsVector CasesBits;
1832 unsigned i, count = 0;
1833
1834 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1835 MachineBasicBlock* Dest = I->BB;
1836 for (i = 0; i < count; ++i)
1837 if (Dest == CasesBits[i].BB)
1838 break;
1839
1840 if (i == count) {
1841 assert((count < 3) && "Too much destinations to test!");
1842 CasesBits.push_back(CaseBits(0, Dest, 0));
1843 count++;
1844 }
1845
1846 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1847 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1848
1849 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00001850 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001851 CasesBits[i].Bits++;
1852 }
1853
1854 }
1855 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1856
1857 SelectionDAGISel::BitTestInfo BTC;
1858
1859 // Figure out which block is immediately after the current one.
1860 MachineFunction::iterator BBI = CR.CaseBB;
1861 ++BBI;
1862
1863 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1864
1865 DOUT << "Cases:\n";
1866 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1867 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1868 << ", BB: " << CasesBits[i].BB << "\n";
1869
1870 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1871 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1872 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1873 CaseBB,
1874 CasesBits[i].BB));
1875 }
1876
1877 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00001878 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001879 CR.CaseBB, Default, BTC);
1880
1881 if (CR.CaseBB == CurMBB)
1882 visitBitTestHeader(BTB);
1883
1884 BitTestCases.push_back(BTB);
1885
1886 return true;
1887}
1888
1889
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001890// Clusterify - Transform simple list of Cases into list of CaseRange's
1891unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1892 const SwitchInst& SI) {
1893 unsigned numCmps = 0;
1894
1895 // Start with "simple" cases
1896 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1897 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1898 Cases.push_back(Case(SI.getSuccessorValue(i),
1899 SI.getSuccessorValue(i),
1900 SMBB));
1901 }
1902 sort(Cases.begin(), Cases.end(), CaseCmp());
1903
1904 // Merge case into clusters
1905 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00001906 // Must recompute end() each iteration because it may be
1907 // invalidated by erase if we hold on to it
David Greenecfacc8f2007-06-29 02:49:11 +00001908 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001909 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1910 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1911 MachineBasicBlock* nextBB = J->BB;
1912 MachineBasicBlock* currentBB = I->BB;
1913
1914 // If the two neighboring cases go to the same destination, merge them
1915 // into a single case.
1916 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1917 I->High = J->High;
1918 J = Cases.erase(J);
1919 } else {
1920 I = J++;
1921 }
1922 }
1923
1924 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1925 if (I->Low != I->High)
1926 // A range counts double, since it requires two compares.
1927 ++numCmps;
1928 }
1929
1930 return numCmps;
1931}
1932
1933void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001934 // Figure out which block is immediately after the current one.
1935 MachineBasicBlock *NextBlock = 0;
1936 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001937
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001938 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001939
Nate Begemanf15485a2006-03-27 01:32:24 +00001940 // If there is only the default destination, branch to it if it is not the
1941 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001942 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001943 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001944
Nate Begemanf15485a2006-03-27 01:32:24 +00001945 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001946 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001947 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001948 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001949
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001950 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001951 return;
1952 }
1953
1954 // If there are any non-default case statements, create a vector of Cases
1955 // representing each one, and sort the vector so that we can efficiently
1956 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001957 CaseVector Cases;
1958 unsigned numCmps = Clusterify(Cases, SI);
1959 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1960 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001961
Nate Begemanf15485a2006-03-27 01:32:24 +00001962 // Get the Value to be switched on and default basic blocks, which will be
1963 // inserted into CaseBlock records, representing basic blocks in the binary
1964 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001965 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001966
Nate Begemanf15485a2006-03-27 01:32:24 +00001967 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001968 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001969 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1970
1971 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00001972 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001973 CaseRec CR = WorkList.back();
1974 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001975
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001976 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1977 continue;
1978
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001979 // If the range has few cases (two or less) emit a series of specific
1980 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001981 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1982 continue;
1983
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001984 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001985 // target supports indirect branches, then emit a jump table rather than
1986 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001987 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1988 continue;
1989
1990 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1991 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1992 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001993 }
1994}
1995
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001996
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001997void SelectionDAGLowering::visitSub(User &I) {
1998 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001999 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002000 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002001 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2002 const VectorType *DestTy = cast<VectorType>(I.getType());
2003 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002004 if (ElTy->isFloatingPoint()) {
2005 unsigned VL = DestTy->getNumElements();
2006 std::vector<Constant*> NZ(VL, ConstantFP::get(ElTy, -0.0));
2007 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2008 if (CV == CNZ) {
2009 SDOperand Op2 = getValue(I.getOperand(1));
2010 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2011 return;
2012 }
Dan Gohman7f321562007-06-25 16:23:39 +00002013 }
2014 }
2015 }
2016 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002017 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2018 if (CFP->isExactlyValue(-0.0)) {
2019 SDOperand Op2 = getValue(I.getOperand(1));
2020 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2021 return;
2022 }
Dan Gohman7f321562007-06-25 16:23:39 +00002023 }
2024
2025 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002026}
2027
Dan Gohman7f321562007-06-25 16:23:39 +00002028void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002029 SDOperand Op1 = getValue(I.getOperand(0));
2030 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002031
2032 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002033}
2034
Nate Begemane21ea612005-11-18 07:42:56 +00002035void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2036 SDOperand Op1 = getValue(I.getOperand(0));
2037 SDOperand Op2 = getValue(I.getOperand(1));
2038
Dan Gohman7f321562007-06-25 16:23:39 +00002039 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2040 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002041 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2042 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2043 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002044
Chris Lattner1c08c712005-01-07 07:47:53 +00002045 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2046}
2047
Reid Spencer45fb3f32006-11-20 01:22:35 +00002048void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002049 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2050 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2051 predicate = IC->getPredicate();
2052 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2053 predicate = ICmpInst::Predicate(IC->getPredicate());
2054 SDOperand Op1 = getValue(I.getOperand(0));
2055 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002056 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002057 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002058 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2059 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2060 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2061 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2062 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2063 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2064 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2065 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2066 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2067 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2068 default:
2069 assert(!"Invalid ICmp predicate value");
2070 Opcode = ISD::SETEQ;
2071 break;
2072 }
2073 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2074}
2075
2076void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002077 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2078 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2079 predicate = FC->getPredicate();
2080 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2081 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002082 SDOperand Op1 = getValue(I.getOperand(0));
2083 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002084 ISD::CondCode Condition, FOC, FPC;
2085 switch (predicate) {
2086 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2087 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2088 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2089 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2090 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2091 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2092 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2093 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2094 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2095 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2096 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2097 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2098 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2099 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2100 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2101 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2102 default:
2103 assert(!"Invalid FCmp predicate value");
2104 FOC = FPC = ISD::SETFALSE;
2105 break;
2106 }
2107 if (FiniteOnlyFPMath())
2108 Condition = FOC;
2109 else
2110 Condition = FPC;
2111 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002112}
2113
2114void SelectionDAGLowering::visitSelect(User &I) {
2115 SDOperand Cond = getValue(I.getOperand(0));
2116 SDOperand TrueVal = getValue(I.getOperand(1));
2117 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002118 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2119 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002120}
2121
Reid Spencer3da59db2006-11-27 01:05:10 +00002122
2123void SelectionDAGLowering::visitTrunc(User &I) {
2124 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2125 SDOperand N = getValue(I.getOperand(0));
2126 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2127 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2128}
2129
2130void SelectionDAGLowering::visitZExt(User &I) {
2131 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2132 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2133 SDOperand N = getValue(I.getOperand(0));
2134 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2135 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2136}
2137
2138void SelectionDAGLowering::visitSExt(User &I) {
2139 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2140 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2141 SDOperand N = getValue(I.getOperand(0));
2142 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2143 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2144}
2145
2146void SelectionDAGLowering::visitFPTrunc(User &I) {
2147 // FPTrunc is never a no-op cast, no need to check
2148 SDOperand N = getValue(I.getOperand(0));
2149 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2150 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2151}
2152
2153void SelectionDAGLowering::visitFPExt(User &I){
2154 // FPTrunc is never a no-op cast, no need to check
2155 SDOperand N = getValue(I.getOperand(0));
2156 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2157 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2158}
2159
2160void SelectionDAGLowering::visitFPToUI(User &I) {
2161 // FPToUI is never a no-op cast, no need to check
2162 SDOperand N = getValue(I.getOperand(0));
2163 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2164 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2165}
2166
2167void SelectionDAGLowering::visitFPToSI(User &I) {
2168 // FPToSI is never a no-op cast, no need to check
2169 SDOperand N = getValue(I.getOperand(0));
2170 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2171 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2172}
2173
2174void SelectionDAGLowering::visitUIToFP(User &I) {
2175 // UIToFP is never a no-op cast, no need to check
2176 SDOperand N = getValue(I.getOperand(0));
2177 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2178 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2179}
2180
2181void SelectionDAGLowering::visitSIToFP(User &I){
2182 // UIToFP is never a no-op cast, no need to check
2183 SDOperand N = getValue(I.getOperand(0));
2184 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2185 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2186}
2187
2188void SelectionDAGLowering::visitPtrToInt(User &I) {
2189 // What to do depends on the size of the integer and the size of the pointer.
2190 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002191 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002192 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002193 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002194 SDOperand Result;
2195 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2196 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2197 else
2198 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2199 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2200 setValue(&I, Result);
2201}
Chris Lattner1c08c712005-01-07 07:47:53 +00002202
Reid Spencer3da59db2006-11-27 01:05:10 +00002203void SelectionDAGLowering::visitIntToPtr(User &I) {
2204 // What to do depends on the size of the integer and the size of the pointer.
2205 // We can either truncate, zero extend, or no-op, accordingly.
2206 SDOperand N = getValue(I.getOperand(0));
2207 MVT::ValueType SrcVT = N.getValueType();
2208 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2209 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2210 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2211 else
2212 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2213 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2214}
2215
2216void SelectionDAGLowering::visitBitCast(User &I) {
2217 SDOperand N = getValue(I.getOperand(0));
2218 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002219
2220 // BitCast assures us that source and destination are the same size so this
2221 // is either a BIT_CONVERT or a no-op.
2222 if (DestVT != N.getValueType())
2223 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2224 else
2225 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002226}
2227
Chris Lattner2bbd8102006-03-29 00:11:43 +00002228void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002229 SDOperand InVec = getValue(I.getOperand(0));
2230 SDOperand InVal = getValue(I.getOperand(1));
2231 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2232 getValue(I.getOperand(2)));
2233
Dan Gohman7f321562007-06-25 16:23:39 +00002234 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2235 TLI.getValueType(I.getType()),
2236 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002237}
2238
Chris Lattner2bbd8102006-03-29 00:11:43 +00002239void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002240 SDOperand InVec = getValue(I.getOperand(0));
2241 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2242 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002243 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002244 TLI.getValueType(I.getType()), InVec, InIdx));
2245}
Chris Lattnerc7029802006-03-18 01:44:44 +00002246
Chris Lattner3e104b12006-04-08 04:15:24 +00002247void SelectionDAGLowering::visitShuffleVector(User &I) {
2248 SDOperand V1 = getValue(I.getOperand(0));
2249 SDOperand V2 = getValue(I.getOperand(1));
2250 SDOperand Mask = getValue(I.getOperand(2));
2251
Dan Gohman7f321562007-06-25 16:23:39 +00002252 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2253 TLI.getValueType(I.getType()),
2254 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002255}
2256
2257
Chris Lattner1c08c712005-01-07 07:47:53 +00002258void SelectionDAGLowering::visitGetElementPtr(User &I) {
2259 SDOperand N = getValue(I.getOperand(0));
2260 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002261
2262 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2263 OI != E; ++OI) {
2264 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002265 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002266 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002267 if (Field) {
2268 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002269 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002270 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00002271 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002272 }
2273 Ty = StTy->getElementType(Field);
2274 } else {
2275 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002276
Chris Lattner7c0104b2005-11-09 04:45:33 +00002277 // If this is a constant subscript, handle it quickly.
2278 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002279 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002280 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00002281 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00002282 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2283 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002284 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002285
2286 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00002287 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002288 SDOperand IdxN = getValue(Idx);
2289
2290 // If the index is smaller or larger than intptr_t, truncate or extend
2291 // it.
2292 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002293 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002294 } else if (IdxN.getValueType() > N.getValueType())
2295 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2296
2297 // If this is a multiply by a power of two, turn it into a shl
2298 // immediately. This is a very common case.
2299 if (isPowerOf2_64(ElementSize)) {
2300 unsigned Amt = Log2_64(ElementSize);
2301 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002302 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002303 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2304 continue;
2305 }
2306
2307 SDOperand Scale = getIntPtrConstant(ElementSize);
2308 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2309 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002310 }
2311 }
2312 setValue(&I, N);
2313}
2314
2315void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2316 // If this is a fixed sized alloca in the entry block of the function,
2317 // allocate it statically on the stack.
2318 if (FuncInfo.StaticAllocaMap.count(&I))
2319 return; // getValue will auto-populate this.
2320
2321 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00002322 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002323 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002324 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002325 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002326
2327 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002328 MVT::ValueType IntPtr = TLI.getPointerTy();
2329 if (IntPtr < AllocSize.getValueType())
2330 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2331 else if (IntPtr > AllocSize.getValueType())
2332 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002333
Chris Lattner68cd65e2005-01-22 23:04:37 +00002334 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00002335 getIntPtrConstant(TySize));
2336
Evan Cheng45157792007-08-16 23:46:29 +00002337 // Handle alignment. If the requested alignment is less than or equal to
2338 // the stack alignment, ignore it. If the size is greater than or equal to
2339 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002340 unsigned StackAlign =
2341 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002342 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002343 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002344
2345 // Round the size of the allocation up to the stack alignment size
2346 // by add SA-1 to the size.
2347 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2348 getIntPtrConstant(StackAlign-1));
2349 // Mask out the low bits for alignment purposes.
2350 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2351 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002352
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002353 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002354 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2355 MVT::Other);
2356 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002357 setValue(&I, DSA);
2358 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002359
2360 // Inform the Frame Information that we have just allocated a variable-sized
2361 // object.
2362 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2363}
2364
Chris Lattner1c08c712005-01-07 07:47:53 +00002365void SelectionDAGLowering::visitLoad(LoadInst &I) {
2366 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002367
Chris Lattnerd3948112005-01-17 22:19:26 +00002368 SDOperand Root;
2369 if (I.isVolatile())
2370 Root = getRoot();
2371 else {
2372 // Do not serialize non-volatile loads against each other.
2373 Root = DAG.getRoot();
2374 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002375
Evan Cheng466685d2006-10-09 20:57:25 +00002376 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002377 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002378}
2379
2380SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002381 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002382 bool isVolatile,
2383 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002384 SDOperand L =
2385 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2386 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002387
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002388 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002389 DAG.setRoot(L.getValue(1));
2390 else
2391 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002392
2393 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002394}
2395
2396
2397void SelectionDAGLowering::visitStore(StoreInst &I) {
2398 Value *SrcV = I.getOperand(0);
2399 SDOperand Src = getValue(SrcV);
2400 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002401 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002402 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002403}
2404
Chris Lattner0eade312006-03-24 02:22:33 +00002405/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2406/// access memory and has no other side effects at all.
2407static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2408#define GET_NO_MEMORY_INTRINSICS
2409#include "llvm/Intrinsics.gen"
2410#undef GET_NO_MEMORY_INTRINSICS
2411 return false;
2412}
2413
Chris Lattnere58a7802006-04-02 03:41:14 +00002414// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2415// have any side-effects or if it only reads memory.
2416static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2417#define GET_SIDE_EFFECT_INFO
2418#include "llvm/Intrinsics.gen"
2419#undef GET_SIDE_EFFECT_INFO
2420 return false;
2421}
2422
Chris Lattner0eade312006-03-24 02:22:33 +00002423/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2424/// node.
2425void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2426 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00002427 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00002428 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00002429
2430 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002431 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002432 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2433 if (OnlyLoad) {
2434 // We don't need to serialize loads against other loads.
2435 Ops.push_back(DAG.getRoot());
2436 } else {
2437 Ops.push_back(getRoot());
2438 }
2439 }
Chris Lattner0eade312006-03-24 02:22:33 +00002440
2441 // Add the intrinsic ID as an integer operand.
2442 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2443
2444 // Add all operands of the call to the operand list.
2445 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2446 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002447 assert(TLI.isTypeLegal(Op.getValueType()) &&
2448 "Intrinsic uses a non-legal type?");
2449 Ops.push_back(Op);
2450 }
2451
2452 std::vector<MVT::ValueType> VTs;
2453 if (I.getType() != Type::VoidTy) {
2454 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00002455 if (MVT::isVector(VT)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002456 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002457 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2458
2459 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2460 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2461 }
2462
2463 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2464 VTs.push_back(VT);
2465 }
2466 if (HasChain)
2467 VTs.push_back(MVT::Other);
2468
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002469 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2470
Chris Lattner0eade312006-03-24 02:22:33 +00002471 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002472 SDOperand Result;
2473 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002474 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2475 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002476 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002477 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2478 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002479 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002480 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2481 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002482
Chris Lattnere58a7802006-04-02 03:41:14 +00002483 if (HasChain) {
2484 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2485 if (OnlyLoad)
2486 PendingLoads.push_back(Chain);
2487 else
2488 DAG.setRoot(Chain);
2489 }
Chris Lattner0eade312006-03-24 02:22:33 +00002490 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002491 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohman7f321562007-06-25 16:23:39 +00002492 MVT::ValueType VT = TLI.getValueType(PTy);
2493 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002494 }
2495 setValue(&I, Result);
2496 }
2497}
2498
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002499/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002500static GlobalVariable *ExtractTypeInfo (Value *V) {
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002501 V = IntrinsicInst::StripPointerCasts(V);
2502 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002503 assert (GV || isa<ConstantPointerNull>(V) &&
2504 "TypeInfo must be a global variable or NULL");
2505 return GV;
2506}
2507
Duncan Sandsf4070822007-06-15 19:04:19 +00002508/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002509/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002510static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2511 MachineBasicBlock *MBB) {
2512 // Inform the MachineModuleInfo of the personality for this landing pad.
2513 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2514 assert(CE->getOpcode() == Instruction::BitCast &&
2515 isa<Function>(CE->getOperand(0)) &&
2516 "Personality should be a function");
2517 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2518
2519 // Gather all the type infos for this landing pad and pass them along to
2520 // MachineModuleInfo.
2521 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002522 unsigned N = I.getNumOperands();
2523
2524 for (unsigned i = N - 1; i > 2; --i) {
2525 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2526 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002527 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002528 assert (FirstCatch <= N && "Invalid filter length");
2529
2530 if (FirstCatch < N) {
2531 TyInfo.reserve(N - FirstCatch);
2532 for (unsigned j = FirstCatch; j < N; ++j)
2533 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2534 MMI->addCatchTypeInfo(MBB, TyInfo);
2535 TyInfo.clear();
2536 }
2537
Duncan Sands6590b042007-08-27 15:47:50 +00002538 if (!FilterLength) {
2539 // Cleanup.
2540 MMI->addCleanup(MBB);
2541 } else {
2542 // Filter.
2543 TyInfo.reserve(FilterLength - 1);
2544 for (unsigned j = i + 1; j < FirstCatch; ++j)
2545 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2546 MMI->addFilterTypeInfo(MBB, TyInfo);
2547 TyInfo.clear();
2548 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002549
2550 N = i;
2551 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002552 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002553
2554 if (N > 3) {
2555 TyInfo.reserve(N - 3);
2556 for (unsigned j = 3; j < N; ++j)
2557 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002558 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002559 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002560}
2561
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002562/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2563/// we want to emit this as a call to a named external function, return the name
2564/// otherwise lower it and return null.
2565const char *
2566SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2567 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002568 default:
2569 // By default, turn this into a target intrinsic node.
2570 visitTargetIntrinsic(I, Intrinsic);
2571 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002572 case Intrinsic::vastart: visitVAStart(I); return 0;
2573 case Intrinsic::vaend: visitVAEnd(I); return 0;
2574 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002575 case Intrinsic::returnaddress:
2576 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2577 getValue(I.getOperand(1))));
2578 return 0;
2579 case Intrinsic::frameaddress:
2580 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2581 getValue(I.getOperand(1))));
2582 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002583 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002584 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002585 break;
2586 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002587 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002588 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002589 case Intrinsic::memcpy_i32:
2590 case Intrinsic::memcpy_i64:
2591 visitMemIntrinsic(I, ISD::MEMCPY);
2592 return 0;
2593 case Intrinsic::memset_i32:
2594 case Intrinsic::memset_i64:
2595 visitMemIntrinsic(I, ISD::MEMSET);
2596 return 0;
2597 case Intrinsic::memmove_i32:
2598 case Intrinsic::memmove_i64:
2599 visitMemIntrinsic(I, ISD::MEMMOVE);
2600 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002601
Chris Lattner86cb6432005-12-13 17:40:33 +00002602 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002603 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002604 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002605 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002606 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002607
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002608 Ops[0] = getRoot();
2609 Ops[1] = getValue(SPI.getLineValue());
2610 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002611
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002612 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002613 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002614 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2615
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002616 Ops[3] = DAG.getString(CompileUnit->getFileName());
2617 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002618
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002619 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002620 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002621
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002622 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002623 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002624 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002625 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002626 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002627 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2628 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002629 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002630 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002631 }
2632
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002633 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002634 }
2635 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002636 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002637 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002638 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2639 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002640 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002641 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002642 }
2643
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002644 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002645 }
2646 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002647 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002648 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002649 if (MMI && FSI.getSubprogram() &&
2650 MMI->Verify(FSI.getSubprogram())) {
2651 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002652 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002653 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002654 }
2655
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002656 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002657 }
2658 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002659 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002660 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002661 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002662 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002663 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002664 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002665 }
2666
2667 return 0;
2668 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002669
Jim Laskeyb180aa12007-02-21 22:53:45 +00002670 case Intrinsic::eh_exception: {
Evan Chenge47c3332007-06-27 18:45:32 +00002671 if (ExceptionHandling) {
Duncan Sands90291952007-07-06 09:18:59 +00002672 if (!CurMBB->isLandingPad()) {
2673 // FIXME: Mark exception register as live in. Hack for PR1508.
2674 unsigned Reg = TLI.getExceptionAddressRegister();
2675 if (Reg) CurMBB->addLiveIn(Reg);
2676 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002677 // Insert the EXCEPTIONADDR instruction.
2678 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2679 SDOperand Ops[1];
2680 Ops[0] = DAG.getRoot();
2681 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2682 setValue(&I, Op);
2683 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002684 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002685 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey735b6f82007-02-22 15:38:06 +00002686 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002687 return 0;
2688 }
2689
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002690 case Intrinsic::eh_selector:{
Jim Laskeyb180aa12007-02-21 22:53:45 +00002691 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeyb180aa12007-02-21 22:53:45 +00002692
Duncan Sandsf4070822007-06-15 19:04:19 +00002693 if (ExceptionHandling && MMI) {
2694 if (CurMBB->isLandingPad())
2695 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00002696 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00002697#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00002698 FuncInfo.CatchInfoLost.insert(&I);
2699#endif
Duncan Sands90291952007-07-06 09:18:59 +00002700 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2701 unsigned Reg = TLI.getExceptionSelectorRegister();
2702 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00002703 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002704
2705 // Insert the EHSELECTION instruction.
Evan Chenga34d3952007-09-04 20:39:26 +00002706 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002707 SDOperand Ops[2];
2708 Ops[0] = getValue(I.getOperand(1));
2709 Ops[1] = getRoot();
2710 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2711 setValue(&I, Op);
2712 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002713 } else {
Anton Korobeynikov6ad82562007-05-02 22:15:48 +00002714 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey735b6f82007-02-22 15:38:06 +00002715 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002716
2717 return 0;
2718 }
2719
2720 case Intrinsic::eh_typeid_for: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002721 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeyb180aa12007-02-21 22:53:45 +00002722
Jim Laskey735b6f82007-02-22 15:38:06 +00002723 if (MMI) {
2724 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002725 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00002726
Jim Laskey735b6f82007-02-22 15:38:06 +00002727 unsigned TypeID = MMI->getTypeIDFor(GV);
2728 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskey7a1de982007-02-24 09:45:44 +00002729 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00002730 // Return something different to eh_selector.
2731 setValue(&I, DAG.getConstant(1, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002732 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002733
2734 return 0;
2735 }
2736
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002737 case Intrinsic::eh_return: {
2738 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2739
2740 if (MMI && ExceptionHandling) {
2741 MMI->setCallsEHReturn(true);
2742 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2743 MVT::Other,
2744 getRoot(),
2745 getValue(I.getOperand(1)),
2746 getValue(I.getOperand(2))));
2747 } else {
2748 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2749 }
2750
2751 return 0;
2752 }
2753
2754 case Intrinsic::eh_unwind_init: {
2755 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2756 MMI->setCallsUnwindInit(true);
2757 }
2758
2759 return 0;
2760 }
2761
2762 case Intrinsic::eh_dwarf_cfa: {
2763 if (ExceptionHandling) {
2764 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
Anton Korobeynikov2f597bd2007-08-23 07:21:06 +00002765 SDOperand CfaArg;
2766 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
2767 CfaArg = DAG.getNode(ISD::TRUNCATE,
2768 TLI.getPointerTy(), getValue(I.getOperand(1)));
2769 else
2770 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
2771 TLI.getPointerTy(), getValue(I.getOperand(1)));
2772
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002773 SDOperand Offset = DAG.getNode(ISD::ADD,
2774 TLI.getPointerTy(),
2775 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
Anton Korobeynikov2f597bd2007-08-23 07:21:06 +00002776 TLI.getPointerTy()),
2777 CfaArg);
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002778 setValue(&I, DAG.getNode(ISD::ADD,
2779 TLI.getPointerTy(),
2780 DAG.getNode(ISD::FRAMEADDR,
2781 TLI.getPointerTy(),
2782 DAG.getConstant(0,
2783 TLI.getPointerTy())),
2784 Offset));
2785 } else {
2786 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2787 }
2788
2789 return 0;
2790 }
2791
Reid Spencer0b118202006-01-16 21:12:35 +00002792 case Intrinsic::sqrt_f32:
2793 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002794 setValue(&I, DAG.getNode(ISD::FSQRT,
2795 getValue(I.getOperand(1)).getValueType(),
2796 getValue(I.getOperand(1))));
2797 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002798 case Intrinsic::powi_f32:
2799 case Intrinsic::powi_f64:
2800 setValue(&I, DAG.getNode(ISD::FPOWI,
2801 getValue(I.getOperand(1)).getValueType(),
2802 getValue(I.getOperand(1)),
2803 getValue(I.getOperand(2))));
2804 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002805 case Intrinsic::pcmarker: {
2806 SDOperand Tmp = getValue(I.getOperand(1));
2807 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2808 return 0;
2809 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002810 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002811 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002812 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2813 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2814 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002815 setValue(&I, Tmp);
2816 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002817 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002818 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00002819 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00002820 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00002821 assert(0 && "part_select intrinsic not implemented");
2822 abort();
2823 }
2824 case Intrinsic::part_set: {
2825 // Currently not implemented: just abort
2826 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00002827 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00002828 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002829 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00002830 setValue(&I, DAG.getNode(ISD::BSWAP,
2831 getValue(I.getOperand(1)).getValueType(),
2832 getValue(I.getOperand(1))));
2833 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002834 case Intrinsic::cttz: {
2835 SDOperand Arg = getValue(I.getOperand(1));
2836 MVT::ValueType Ty = Arg.getValueType();
2837 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002838 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002839 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002840 }
2841 case Intrinsic::ctlz: {
2842 SDOperand Arg = getValue(I.getOperand(1));
2843 MVT::ValueType Ty = Arg.getValueType();
2844 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002845 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002846 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002847 }
2848 case Intrinsic::ctpop: {
2849 SDOperand Arg = getValue(I.getOperand(1));
2850 MVT::ValueType Ty = Arg.getValueType();
2851 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002852 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002853 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00002854 }
Chris Lattner140d53c2006-01-13 02:50:02 +00002855 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002856 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002857 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2858 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002859 setValue(&I, Tmp);
2860 DAG.setRoot(Tmp.getValue(1));
2861 return 0;
2862 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002863 case Intrinsic::stackrestore: {
2864 SDOperand Tmp = getValue(I.getOperand(1));
2865 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002866 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002867 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002868 case Intrinsic::prefetch:
2869 // FIXME: Currently discarding prefetches.
2870 return 0;
Tanya Lattner24e5aad2007-06-15 22:26:58 +00002871
2872 case Intrinsic::var_annotation:
2873 // Discard annotate attributes
2874 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00002875
2876 case Intrinsic::adjust_trampoline: {
2877 SDOperand Arg = getValue(I.getOperand(1));
2878 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMP, TLI.getPointerTy(), Arg));
2879 return 0;
2880 }
2881
2882 case Intrinsic::init_trampoline: {
2883 const Function *F =
2884 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
2885
2886 SDOperand Ops[6];
2887 Ops[0] = getRoot();
2888 Ops[1] = getValue(I.getOperand(1));
2889 Ops[2] = getValue(I.getOperand(2));
2890 Ops[3] = getValue(I.getOperand(3));
2891 Ops[4] = DAG.getSrcValue(I.getOperand(1));
2892 Ops[5] = DAG.getSrcValue(F);
2893
2894 DAG.setRoot(DAG.getNode(ISD::TRAMPOLINE, MVT::Other, Ops, 6));
2895 return 0;
2896 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002897 }
2898}
2899
2900
Jim Laskey1da20a72007-02-23 21:45:01 +00002901void SelectionDAGLowering::LowerCallTo(Instruction &I,
2902 const Type *CalledValueTy,
2903 unsigned CallingConv,
2904 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002905 SDOperand Callee, unsigned OpIdx,
2906 MachineBasicBlock *LandingPad) {
Jim Laskey1da20a72007-02-23 21:45:01 +00002907 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey735b6f82007-02-22 15:38:06 +00002908 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer5694b6e2007-04-09 06:17:21 +00002909 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002910 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2911 unsigned BeginLabel = 0, EndLabel = 0;
2912
Jim Laskey735b6f82007-02-22 15:38:06 +00002913 TargetLowering::ArgListTy Args;
2914 TargetLowering::ArgListEntry Entry;
2915 Args.reserve(I.getNumOperands());
2916 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2917 Value *Arg = I.getOperand(i);
2918 SDOperand ArgNode = getValue(Arg);
2919 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00002920
2921 unsigned attrInd = i - OpIdx + 1;
2922 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2923 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2924 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2925 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
Duncan Sands36397f52007-07-27 12:58:54 +00002926 Entry.isNest = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::Nest);
Rafael Espindola21485be2007-08-20 15:18:24 +00002927 Entry.isByVal = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ByVal);
Jim Laskey735b6f82007-02-22 15:38:06 +00002928 Args.push_back(Entry);
2929 }
2930
Duncan Sands9fac0b52007-06-06 10:05:18 +00002931 if (ExceptionHandling && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002932 // Insert a label before the invoke call to mark the try range. This can be
2933 // used to detect deletion of the invoke via the MachineModuleInfo.
2934 BeginLabel = MMI->NextLabelID();
2935 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2936 DAG.getConstant(BeginLabel, MVT::i32)));
2937 }
2938
Jim Laskey735b6f82007-02-22 15:38:06 +00002939 std::pair<SDOperand,SDOperand> Result =
2940 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencer18da0722007-04-11 02:44:20 +00002941 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey1da20a72007-02-23 21:45:01 +00002942 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002943 Callee, Args, DAG);
2944 if (I.getType() != Type::VoidTy)
2945 setValue(&I, Result.first);
2946 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002947
Duncan Sands9fac0b52007-06-06 10:05:18 +00002948 if (ExceptionHandling && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00002949 // Insert a label at the end of the invoke call to mark the try range. This
2950 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2951 EndLabel = MMI->NextLabelID();
2952 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2953 DAG.getConstant(EndLabel, MVT::i32)));
2954
2955 // Inform MachineModuleInfo of range.
2956 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2957 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002958}
2959
2960
Chris Lattner1c08c712005-01-07 07:47:53 +00002961void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002962 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002963 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002964 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002965 if (unsigned IID = F->getIntrinsicID()) {
2966 RenameFn = visitIntrinsicCall(I, IID);
2967 if (!RenameFn)
2968 return;
2969 } else { // Not an LLVM intrinsic.
2970 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002971 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2972 if (I.getNumOperands() == 3 && // Basic sanity checks.
2973 I.getOperand(1)->getType()->isFloatingPoint() &&
2974 I.getType() == I.getOperand(1)->getType() &&
2975 I.getType() == I.getOperand(2)->getType()) {
2976 SDOperand LHS = getValue(I.getOperand(1));
2977 SDOperand RHS = getValue(I.getOperand(2));
2978 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2979 LHS, RHS));
2980 return;
2981 }
2982 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002983 if (I.getNumOperands() == 2 && // Basic sanity checks.
2984 I.getOperand(1)->getType()->isFloatingPoint() &&
2985 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002986 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002987 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2988 return;
2989 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002990 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002991 if (I.getNumOperands() == 2 && // Basic sanity checks.
2992 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002993 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002994 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002995 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2996 return;
2997 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002998 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002999 if (I.getNumOperands() == 2 && // Basic sanity checks.
3000 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00003001 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003002 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003003 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3004 return;
3005 }
3006 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003007 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003008 } else if (isa<InlineAsm>(I.getOperand(0))) {
3009 visitInlineAsm(I);
3010 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003011 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003012
Chris Lattner64e14b12005-01-08 22:48:57 +00003013 SDOperand Callee;
3014 if (!RenameFn)
3015 Callee = getValue(I.getOperand(0));
3016 else
3017 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003018
Jim Laskey1da20a72007-02-23 21:45:01 +00003019 LowerCallTo(I, I.getCalledValue()->getType(),
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003020 I.getCallingConv(),
3021 I.isTailCall(),
3022 Callee,
3023 1);
Chris Lattner1c08c712005-01-07 07:47:53 +00003024}
3025
Jim Laskey735b6f82007-02-22 15:38:06 +00003026
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003027/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3028/// this value and returns the result as a ValueVT value. This uses
3029/// Chain/Flag as the input and updates them for the output Chain/Flag.
3030/// If the Flag pointer is NULL, no flag is used.
3031SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3032 SDOperand &Chain, SDOperand *Flag)const{
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003033 // Copy the legal parts from the registers.
3034 unsigned NumParts = Regs.size();
3035 SmallVector<SDOperand, 8> Parts(NumParts);
Dan Gohman27a70be2007-07-02 16:18:06 +00003036 for (unsigned i = 0; i != NumParts; ++i) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003037 SDOperand Part = Flag ?
3038 DAG.getCopyFromReg(Chain, Regs[i], RegVT, *Flag) :
3039 DAG.getCopyFromReg(Chain, Regs[i], RegVT);
3040 Chain = Part.getValue(1);
3041 if (Flag)
3042 *Flag = Part.getValue(2);
3043 Parts[i] = Part;
Chris Lattnercf752aa2006-06-08 18:22:48 +00003044 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003045
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003046 // Assemble the legal parts into the final value.
Dan Gohman532dc2e2007-07-09 20:59:04 +00003047 return getCopyFromParts(DAG, &Parts[0], NumParts, RegVT, ValueVT);
Chris Lattner864635a2006-02-22 22:37:12 +00003048}
3049
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003050/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3051/// specified value into the registers specified by this object. This uses
3052/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003053/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003054void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003055 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003056 // Get the list of the values's legal parts.
3057 unsigned NumParts = Regs.size();
3058 SmallVector<SDOperand, 8> Parts(NumParts);
Dan Gohman532dc2e2007-07-09 20:59:04 +00003059 getCopyToParts(DAG, Val, &Parts[0], NumParts, RegVT);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003060
3061 // Copy the parts into the registers.
Dan Gohman27a70be2007-07-02 16:18:06 +00003062 for (unsigned i = 0; i != NumParts; ++i) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003063 SDOperand Part = Flag ?
Dan Gohman532dc2e2007-07-09 20:59:04 +00003064 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) :
3065 DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003066 Chain = Part.getValue(0);
3067 if (Flag)
3068 *Flag = Part.getValue(1);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003069 }
3070}
Chris Lattner864635a2006-02-22 22:37:12 +00003071
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003072/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3073/// operand list. This adds the code marker and includes the number of
3074/// values added into it.
3075void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003076 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00003077 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3078 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003079 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
3080 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
3081}
Chris Lattner864635a2006-02-22 22:37:12 +00003082
3083/// isAllocatableRegister - If the specified register is safe to allocate,
3084/// i.e. it isn't a stack pointer or some other special register, return the
3085/// register class for the register. Otherwise, return null.
3086static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003087isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3088 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003089 MVT::ValueType FoundVT = MVT::Other;
3090 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003091 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
3092 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003093 MVT::ValueType ThisVT = MVT::Other;
3094
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003095 const TargetRegisterClass *RC = *RCI;
3096 // If none of the the value types for this register class are valid, we
3097 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003098 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3099 I != E; ++I) {
3100 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003101 // If we have already found this register in a different register class,
3102 // choose the one with the largest VT specified. For example, on
3103 // PowerPC, we favor f64 register classes over f32.
3104 if (FoundVT == MVT::Other ||
3105 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3106 ThisVT = *I;
3107 break;
3108 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003109 }
3110 }
3111
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003112 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003113
Chris Lattner864635a2006-02-22 22:37:12 +00003114 // NOTE: This isn't ideal. In particular, this might allocate the
3115 // frame pointer in functions that need it (due to them not being taken
3116 // out of allocation, because a variable sized allocation hasn't been seen
3117 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003118 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3119 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003120 if (*I == Reg) {
3121 // We found a matching register class. Keep looking at others in case
3122 // we find one with larger registers that this physreg is also in.
3123 FoundRC = RC;
3124 FoundVT = ThisVT;
3125 break;
3126 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003127 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003128 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003129}
3130
Chris Lattner4e4b5762006-02-01 18:59:47 +00003131
Chris Lattner0c583402007-04-28 20:49:53 +00003132namespace {
3133/// AsmOperandInfo - This contains information for each constraint that we are
3134/// lowering.
3135struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3136 /// ConstraintCode - This contains the actual string for the code, like "m".
3137 std::string ConstraintCode;
Chris Lattner2a600be2007-04-28 21:01:43 +00003138
3139 /// ConstraintType - Information about the constraint code, e.g. Register,
3140 /// RegisterClass, Memory, Other, Unknown.
3141 TargetLowering::ConstraintType ConstraintType;
Chris Lattner0c583402007-04-28 20:49:53 +00003142
3143 /// CallOperand/CallOperandval - If this is the result output operand or a
3144 /// clobber, this is null, otherwise it is the incoming operand to the
3145 /// CallInst. This gets modified as the asm is processed.
3146 SDOperand CallOperand;
3147 Value *CallOperandVal;
3148
3149 /// ConstraintVT - The ValueType for the operand value.
3150 MVT::ValueType ConstraintVT;
3151
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003152 /// AssignedRegs - If this is a register or register class operand, this
3153 /// contains the set of register corresponding to the operand.
3154 RegsForValue AssignedRegs;
3155
Chris Lattner0c583402007-04-28 20:49:53 +00003156 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Chris Lattner2a600be2007-04-28 21:01:43 +00003157 : InlineAsm::ConstraintInfo(info),
3158 ConstraintType(TargetLowering::C_Unknown),
Chris Lattner0c583402007-04-28 20:49:53 +00003159 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3160 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003161
3162 void ComputeConstraintToUse(const TargetLowering &TLI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003163
3164 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3165 /// busy in OutputRegs/InputRegs.
3166 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3167 std::set<unsigned> &OutputRegs,
3168 std::set<unsigned> &InputRegs) const {
3169 if (isOutReg)
3170 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3171 if (isInReg)
3172 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3173 }
Chris Lattner0c583402007-04-28 20:49:53 +00003174};
3175} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003176
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003177/// getConstraintGenerality - Return an integer indicating how general CT is.
3178static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3179 switch (CT) {
3180 default: assert(0 && "Unknown constraint type!");
3181 case TargetLowering::C_Other:
3182 case TargetLowering::C_Unknown:
3183 return 0;
3184 case TargetLowering::C_Register:
3185 return 1;
3186 case TargetLowering::C_RegisterClass:
3187 return 2;
3188 case TargetLowering::C_Memory:
3189 return 3;
3190 }
3191}
3192
3193void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3194 assert(!Codes.empty() && "Must have at least one constraint");
3195
3196 std::string *Current = &Codes[0];
3197 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3198 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3199 ConstraintCode = *Current;
3200 ConstraintType = CurType;
3201 return;
3202 }
3203
3204 unsigned CurGenerality = getConstraintGenerality(CurType);
3205
3206 // If we have multiple constraints, try to pick the most general one ahead
3207 // of time. This isn't a wonderful solution, but handles common cases.
3208 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3209 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3210 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3211 if (ThisGenerality > CurGenerality) {
3212 // This constraint letter is more general than the previous one,
3213 // use it.
3214 CurType = ThisType;
3215 Current = &Codes[j];
3216 CurGenerality = ThisGenerality;
3217 }
3218 }
3219
3220 ConstraintCode = *Current;
3221 ConstraintType = CurType;
3222}
3223
3224
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003225void SelectionDAGLowering::
3226GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003227 std::set<unsigned> &OutputRegs,
3228 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003229 // Compute whether this value requires an input register, an output register,
3230 // or both.
3231 bool isOutReg = false;
3232 bool isInReg = false;
3233 switch (OpInfo.Type) {
3234 case InlineAsm::isOutput:
3235 isOutReg = true;
3236
3237 // If this is an early-clobber output, or if there is an input
3238 // constraint that matches this, we need to reserve the input register
3239 // so no other inputs allocate to it.
3240 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3241 break;
3242 case InlineAsm::isInput:
3243 isInReg = true;
3244 isOutReg = false;
3245 break;
3246 case InlineAsm::isClobber:
3247 isOutReg = true;
3248 isInReg = true;
3249 break;
3250 }
3251
3252
3253 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003254 std::vector<unsigned> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003255
3256 // If this is a constraint for a single physreg, or a constraint for a
3257 // register class, find it.
3258 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3259 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3260 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003261
3262 unsigned NumRegs = 1;
3263 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003264 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003265 MVT::ValueType RegVT;
3266 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3267
Chris Lattnerbf996f12007-04-30 17:29:31 +00003268
3269 // If this is a constraint for a specific physical register, like {r17},
3270 // assign it now.
3271 if (PhysReg.first) {
3272 if (OpInfo.ConstraintVT == MVT::Other)
3273 ValueVT = *PhysReg.second->vt_begin();
3274
3275 // Get the actual register value type. This is important, because the user
3276 // may have asked for (e.g.) the AX register in i32 type. We need to
3277 // remember that AX is actually i16 to get the right extension.
3278 RegVT = *PhysReg.second->vt_begin();
3279
3280 // This is a explicit reference to a physical register.
3281 Regs.push_back(PhysReg.first);
3282
3283 // If this is an expanded reference, add the rest of the regs to Regs.
3284 if (NumRegs != 1) {
3285 TargetRegisterClass::iterator I = PhysReg.second->begin();
3286 TargetRegisterClass::iterator E = PhysReg.second->end();
3287 for (; *I != PhysReg.first; ++I)
3288 assert(I != E && "Didn't find reg!");
3289
3290 // Already added the first reg.
3291 --NumRegs; ++I;
3292 for (; NumRegs; --NumRegs, ++I) {
3293 assert(I != E && "Ran out of registers to allocate!");
3294 Regs.push_back(*I);
3295 }
3296 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003297 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3298 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3299 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003300 }
3301
3302 // Otherwise, if this was a reference to an LLVM register class, create vregs
3303 // for this reference.
3304 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003305 const TargetRegisterClass *RC = PhysReg.second;
3306 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003307 // If this is an early clobber or tied register, our regalloc doesn't know
3308 // how to maintain the constraint. If it isn't, go ahead and create vreg
3309 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003310 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3311 // If there is some other early clobber and this is an input register,
3312 // then we are forced to pre-allocate the input reg so it doesn't
3313 // conflict with the earlyclobber.
3314 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003315 RegVT = *PhysReg.second->vt_begin();
3316
3317 if (OpInfo.ConstraintVT == MVT::Other)
3318 ValueVT = RegVT;
3319
3320 // Create the appropriate number of virtual registers.
3321 SSARegMap *RegMap = MF.getSSARegMap();
3322 for (; NumRegs; --NumRegs)
3323 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3324
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003325 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3326 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3327 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003328 }
3329
3330 // Otherwise, we can't allocate it. Let the code below figure out how to
3331 // maintain these constraints.
3332 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3333
3334 } else {
3335 // This is a reference to a register class that doesn't directly correspond
3336 // to an LLVM register class. Allocate NumRegs consecutive, available,
3337 // registers from the class.
3338 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3339 OpInfo.ConstraintVT);
3340 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003341
Chris Lattnerbf996f12007-04-30 17:29:31 +00003342 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3343 unsigned NumAllocated = 0;
3344 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3345 unsigned Reg = RegClassRegs[i];
3346 // See if this register is available.
3347 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3348 (isInReg && InputRegs.count(Reg))) { // Already used.
3349 // Make sure we find consecutive registers.
3350 NumAllocated = 0;
3351 continue;
3352 }
3353
3354 // Check to see if this register is allocatable (i.e. don't give out the
3355 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003356 if (RC == 0) {
3357 RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3358 if (!RC) { // Couldn't allocate this register.
3359 // Reset NumAllocated to make sure we return consecutive registers.
3360 NumAllocated = 0;
3361 continue;
3362 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003363 }
3364
3365 // Okay, this register is good, we can use it.
3366 ++NumAllocated;
3367
3368 // If we allocated enough consecutive registers, succeed.
3369 if (NumAllocated == NumRegs) {
3370 unsigned RegStart = (i-NumAllocated)+1;
3371 unsigned RegEnd = i+1;
3372 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003373 for (unsigned i = RegStart; i != RegEnd; ++i)
3374 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003375
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003376 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3377 OpInfo.ConstraintVT);
3378 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3379 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003380 }
3381 }
3382
3383 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003384 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003385}
3386
3387
Chris Lattnerce7518c2006-01-26 22:24:51 +00003388/// visitInlineAsm - Handle a call to an InlineAsm object.
3389///
3390void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3391 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
Chris Lattnerce7518c2006-01-26 22:24:51 +00003392
Chris Lattner0c583402007-04-28 20:49:53 +00003393 /// ConstraintOperands - Information about all of the constraints.
3394 std::vector<AsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003395
3396 SDOperand Chain = getRoot();
3397 SDOperand Flag;
3398
Chris Lattner4e4b5762006-02-01 18:59:47 +00003399 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003400
Chris Lattner0c583402007-04-28 20:49:53 +00003401 // Do a prepass over the constraints, canonicalizing them, and building up the
3402 // ConstraintOperands list.
3403 std::vector<InlineAsm::ConstraintInfo>
3404 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003405
3406 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3407 // constraint. If so, we can't let the register allocator allocate any input
3408 // registers, because it will not know to avoid the earlyclobbered output reg.
3409 bool SawEarlyClobber = false;
3410
3411 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
Chris Lattner0c583402007-04-28 20:49:53 +00003412 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3413 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3414 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3415
Chris Lattner0c583402007-04-28 20:49:53 +00003416 MVT::ValueType OpVT = MVT::Other;
3417
3418 // Compute the value type for each operand.
3419 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003420 case InlineAsm::isOutput:
Chris Lattner0c583402007-04-28 20:49:53 +00003421 if (!OpInfo.isIndirect) {
3422 // The return value of the call is this value. As such, there is no
3423 // corresponding argument.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003424 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3425 OpVT = TLI.getValueType(I.getType());
3426 } else {
Chris Lattner0c583402007-04-28 20:49:53 +00003427 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003428 }
3429 break;
3430 case InlineAsm::isInput:
Chris Lattner0c583402007-04-28 20:49:53 +00003431 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003432 break;
3433 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003434 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003435 break;
3436 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003437
Chris Lattner0c583402007-04-28 20:49:53 +00003438 // If this is an input or an indirect output, process the call argument.
3439 if (OpInfo.CallOperandVal) {
3440 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3441 const Type *OpTy = OpInfo.CallOperandVal->getType();
Chris Lattner6995cf62007-04-29 18:58:03 +00003442 // If this is an indirect operand, the operand is a pointer to the
3443 // accessed type.
3444 if (OpInfo.isIndirect)
3445 OpTy = cast<PointerType>(OpTy)->getElementType();
3446
3447 // If OpTy is not a first-class value, it may be a struct/union that we
3448 // can tile with integers.
3449 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3450 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3451 switch (BitSize) {
3452 default: break;
3453 case 1:
3454 case 8:
3455 case 16:
3456 case 32:
3457 case 64:
3458 OpTy = IntegerType::get(BitSize);
3459 break;
3460 }
Chris Lattner0c583402007-04-28 20:49:53 +00003461 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003462
3463 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003464 }
3465
3466 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003467
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003468 // Compute the constraint code and ConstraintType to use.
3469 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattner0c583402007-04-28 20:49:53 +00003470
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003471 // Keep track of whether we see an earlyclobber.
3472 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003473
3474 // If this is a memory input, and if the operand is not indirect, do what we
3475 // need to to provide an address for the memory input.
3476 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3477 !OpInfo.isIndirect) {
3478 assert(OpInfo.Type == InlineAsm::isInput &&
3479 "Can only indirectify direct input operands!");
3480
3481 // Memory operands really want the address of the value. If we don't have
3482 // an indirect input, put it in the constpool if we can, otherwise spill
3483 // it to a stack slot.
3484
3485 // If the operand is a float, integer, or vector constant, spill to a
3486 // constant pool entry to get its address.
3487 Value *OpVal = OpInfo.CallOperandVal;
3488 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3489 isa<ConstantVector>(OpVal)) {
3490 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3491 TLI.getPointerTy());
3492 } else {
3493 // Otherwise, create a stack slot and emit a store to it before the
3494 // asm.
3495 const Type *Ty = OpVal->getType();
3496 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3497 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3498 MachineFunction &MF = DAG.getMachineFunction();
3499 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3500 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3501 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3502 OpInfo.CallOperand = StackSlot;
3503 }
3504
3505 // There is no longer a Value* corresponding to this operand.
3506 OpInfo.CallOperandVal = 0;
3507 // It is now an indirect operand.
3508 OpInfo.isIndirect = true;
3509 }
3510
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003511 // If this constraint is for a specific register, allocate it before
3512 // anything else.
3513 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3514 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00003515 }
Chris Lattner0c583402007-04-28 20:49:53 +00003516 ConstraintInfos.clear();
3517
3518
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003519 // Second pass - Loop over all of the operands, assigning virtual or physregs
3520 // to registerclass operands.
3521 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3522 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3523
3524 // C_Register operands have already been allocated, Other/Memory don't need
3525 // to be.
3526 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3527 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3528 }
3529
Chris Lattner0c583402007-04-28 20:49:53 +00003530 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3531 std::vector<SDOperand> AsmNodeOperands;
3532 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3533 AsmNodeOperands.push_back(
3534 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3535
Chris Lattner2cc2f662006-02-01 01:28:23 +00003536
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003537 // Loop over all of the inputs, copying the operand values into the
3538 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003539 RegsForValue RetValRegs;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003540
Chris Lattner0c583402007-04-28 20:49:53 +00003541 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3542 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3543
3544 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3545 AsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00003546
Chris Lattner0c583402007-04-28 20:49:53 +00003547 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00003548 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00003549 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3550 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00003551 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003552 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00003553
Chris Lattner22873462006-02-27 23:45:39 +00003554 // Add information to the INLINEASM node to know about this output.
3555 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003556 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3557 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003558 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00003559 break;
3560 }
3561
Chris Lattner2a600be2007-04-28 21:01:43 +00003562 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00003563
Chris Lattner864635a2006-02-22 22:37:12 +00003564 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003565 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003566 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003567 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003568 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003569 exit(1);
3570 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003571
Chris Lattner0c583402007-04-28 20:49:53 +00003572 if (!OpInfo.isIndirect) {
3573 // This is the result value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00003574 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003575 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00003576 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003577 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003578 } else {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003579 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00003580 OpInfo.CallOperandVal));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003581 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003582
3583 // Add information to the INLINEASM node to know that this register is
3584 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003585 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3586 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003587 break;
3588 }
3589 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00003590 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00003591
Chris Lattner0c583402007-04-28 20:49:53 +00003592 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00003593 // If this is required to match an output register we have already set,
3594 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00003595 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003596
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003597 // Scan until we find the definition we already emitted of this operand.
3598 // When we find it, create a RegsForValue operand.
3599 unsigned CurOp = 2; // The first operand.
3600 for (; OperandNo; --OperandNo) {
3601 // Advance to the next operand.
3602 unsigned NumOps =
3603 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003604 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3605 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003606 "Skipped past definitions?");
3607 CurOp += (NumOps>>3)+1;
3608 }
3609
3610 unsigned NumOps =
3611 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00003612 if ((NumOps & 7) == 2 /*REGDEF*/) {
3613 // Add NumOps>>3 registers to MatchedRegs.
3614 RegsForValue MatchedRegs;
3615 MatchedRegs.ValueVT = InOperandVal.getValueType();
3616 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3617 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3618 unsigned Reg =
3619 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3620 MatchedRegs.Regs.push_back(Reg);
3621 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003622
Chris Lattner527fae12007-02-01 01:21:12 +00003623 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003624 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00003625 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3626 break;
3627 } else {
3628 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3629 assert(0 && "matching constraints for memory operands unimp");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003630 }
Chris Lattner2223aea2006-02-02 00:25:23 +00003631 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003632
Chris Lattner2a600be2007-04-28 21:01:43 +00003633 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00003634 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00003635 "Don't know how to handle indirect other inputs yet!");
3636
Chris Lattner48884cd2007-08-25 00:47:38 +00003637 std::vector<SDOperand> Ops;
3638 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
3639 Ops, DAG);
3640 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003641 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003642 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00003643 exit(1);
3644 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003645
3646 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00003647 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003648 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3649 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00003650 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003651 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00003652 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003653 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00003654 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3655 "Memory operands expect pointer values");
3656
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003657 // Add information to the INLINEASM node to know about this input.
3658 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003659 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3660 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003661 AsmNodeOperands.push_back(InOperandVal);
3662 break;
3663 }
3664
Chris Lattner2a600be2007-04-28 21:01:43 +00003665 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3666 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3667 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00003668 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00003669 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003670
3671 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003672 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3673 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003674
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003675 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00003676
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003677 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3678 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003679 break;
3680 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003681 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003682 // Add the clobbered value to the operand list, so that the register
3683 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003684 if (!OpInfo.AssignedRegs.Regs.empty())
3685 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3686 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003687 break;
3688 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003689 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003690 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003691
3692 // Finish up input operands.
3693 AsmNodeOperands[0] = Chain;
3694 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3695
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003696 Chain = DAG.getNode(ISD::INLINEASM,
3697 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003698 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003699 Flag = Chain.getValue(1);
3700
Chris Lattner6656dd12006-01-31 02:03:41 +00003701 // If this asm returns a register value, copy the result from that register
3702 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00003703 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003704 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3a508c92007-04-12 06:00:20 +00003705
3706 // If the result of the inline asm is a vector, it may have the wrong
3707 // width/num elts. Make sure to convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00003708 // bit_convert.
3709 if (MVT::isVector(Val.getValueType())) {
Chris Lattner3a508c92007-04-12 06:00:20 +00003710 const VectorType *VTy = cast<VectorType>(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00003711 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
Chris Lattner3a508c92007-04-12 06:00:20 +00003712
Dan Gohman7f321562007-06-25 16:23:39 +00003713 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00003714 }
3715
3716 setValue(&I, Val);
3717 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003718
Chris Lattner6656dd12006-01-31 02:03:41 +00003719 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3720
3721 // Process indirect outputs, first output all of the flagged copies out of
3722 // physregs.
3723 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00003724 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00003725 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003726 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00003727 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00003728 }
3729
3730 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003731 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00003732 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00003733 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00003734 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003735 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00003736 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003737 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3738 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003739 DAG.setRoot(Chain);
3740}
3741
3742
Chris Lattner1c08c712005-01-07 07:47:53 +00003743void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3744 SDOperand Src = getValue(I.getOperand(0));
3745
3746 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00003747
3748 if (IntPtr < Src.getValueType())
3749 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3750 else if (IntPtr > Src.getValueType())
3751 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00003752
3753 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00003754 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00003755 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3756 Src, getIntPtrConstant(ElementSize));
3757
Reid Spencer47857812006-12-31 05:55:36 +00003758 TargetLowering::ArgListTy Args;
3759 TargetLowering::ArgListEntry Entry;
3760 Entry.Node = Src;
3761 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003762 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00003763
3764 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003765 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003766 DAG.getExternalSymbol("malloc", IntPtr),
3767 Args, DAG);
3768 setValue(&I, Result.first); // Pointers always fit in registers
3769 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003770}
3771
3772void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00003773 TargetLowering::ArgListTy Args;
3774 TargetLowering::ArgListEntry Entry;
3775 Entry.Node = getValue(I.getOperand(0));
3776 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003777 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00003778 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00003779 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003780 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003781 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3782 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003783}
3784
Chris Lattner025c39b2005-08-26 20:54:47 +00003785// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3786// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3787// instructions are special in various ways, which require special support to
3788// insert. The specified MachineInstr is created but not inserted into any
3789// basic blocks, and the scheduler passes ownership of it to this method.
3790MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3791 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00003792 cerr << "If a target marks an instruction with "
3793 << "'usesCustomDAGSchedInserter', it must implement "
3794 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00003795 abort();
3796 return 0;
3797}
3798
Chris Lattner39ae3622005-01-09 00:00:49 +00003799void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003800 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3801 getValue(I.getOperand(1)),
3802 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00003803}
3804
3805void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003806 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3807 getValue(I.getOperand(0)),
3808 DAG.getSrcValue(I.getOperand(0)));
3809 setValue(&I, V);
3810 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003811}
3812
3813void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003814 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3815 getValue(I.getOperand(1)),
3816 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003817}
3818
3819void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003820 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3821 getValue(I.getOperand(1)),
3822 getValue(I.getOperand(2)),
3823 DAG.getSrcValue(I.getOperand(1)),
3824 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003825}
3826
Chris Lattnerfdfded52006-04-12 16:20:43 +00003827/// TargetLowering::LowerArguments - This is the default LowerArguments
3828/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003829/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3830/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003831std::vector<SDOperand>
3832TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003833 const FunctionType *FTy = F.getFunctionType();
Reid Spencer5694b6e2007-04-09 06:17:21 +00003834 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003835 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3836 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003837 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00003838 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3839 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3840
3841 // Add one result value for each formal argument.
3842 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00003843 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003844 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3845 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003846 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003847 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003848 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003849 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003850
Chris Lattnerddf53e42007-02-26 02:56:58 +00003851 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3852 // that is zero extended!
Reid Spencer18da0722007-04-11 02:44:20 +00003853 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003854 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencer18da0722007-04-11 02:44:20 +00003855 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003856 Flags |= ISD::ParamFlags::SExt;
Reid Spencer18da0722007-04-11 02:44:20 +00003857 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003858 Flags |= ISD::ParamFlags::InReg;
Reid Spencer18da0722007-04-11 02:44:20 +00003859 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003860 Flags |= ISD::ParamFlags::StructReturn;
Rafael Espindola594d37e2007-08-10 14:44:42 +00003861 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ByVal)) {
Rafael Espindola1aa7efb2007-07-06 10:57:03 +00003862 Flags |= ISD::ParamFlags::ByVal;
Rafael Espindola594d37e2007-08-10 14:44:42 +00003863 const PointerType *Ty = cast<PointerType>(I->getType());
3864 const StructType *STy = cast<StructType>(Ty->getElementType());
3865 unsigned StructAlign = Log2_32(getTargetData()->getABITypeAlignment(STy));
3866 unsigned StructSize = getTargetData()->getTypeSize(STy);
3867 Flags |= (StructAlign << ISD::ParamFlags::ByValAlignOffs);
3868 Flags |= (StructSize << ISD::ParamFlags::ByValSizeOffs);
3869 }
Duncan Sands36397f52007-07-27 12:58:54 +00003870 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::Nest))
3871 Flags |= ISD::ParamFlags::Nest;
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003872 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerddf53e42007-02-26 02:56:58 +00003873
Chris Lattnerfdfded52006-04-12 16:20:43 +00003874 switch (getTypeAction(VT)) {
3875 default: assert(0 && "Unknown type action!");
3876 case Legal:
3877 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003878 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003879 break;
3880 case Promote:
3881 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003882 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003883 break;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003884 case Expand: {
3885 // If this is an illegal type, it needs to be broken up to fit into
3886 // registers.
3887 MVT::ValueType RegisterVT = getRegisterType(VT);
3888 unsigned NumRegs = getNumRegisters(VT);
3889 for (unsigned i = 0; i != NumRegs; ++i) {
3890 RetVals.push_back(RegisterVT);
3891 // if it isn't first piece, alignment must be 1
3892 if (i > 0)
3893 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3894 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3895 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003896 }
3897 break;
3898 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003899 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00003900 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00003901
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003902 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00003903
3904 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003905 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3906 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003907 &Ops[0], Ops.size()).Val;
Dan Gohman27a70be2007-07-02 16:18:06 +00003908 unsigned NumArgRegs = Result->getNumValues() - 1;
3909 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003910
3911 // Set up the return result vector.
3912 Ops.clear();
3913 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00003914 unsigned Idx = 1;
3915 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3916 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003917 MVT::ValueType VT = getValueType(I->getType());
3918
3919 switch (getTypeAction(VT)) {
3920 default: assert(0 && "Unknown type action!");
3921 case Legal:
3922 Ops.push_back(SDOperand(Result, i++));
3923 break;
3924 case Promote: {
3925 SDOperand Op(Result, i++);
3926 if (MVT::isInteger(VT)) {
Reid Spencer18da0722007-04-11 02:44:20 +00003927 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003928 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3929 DAG.getValueType(VT));
Reid Spencer18da0722007-04-11 02:44:20 +00003930 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003931 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3932 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003933 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3934 } else {
3935 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3936 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3937 }
3938 Ops.push_back(Op);
3939 break;
3940 }
Dan Gohman27a70be2007-07-02 16:18:06 +00003941 case Expand: {
3942 MVT::ValueType PartVT = getRegisterType(VT);
3943 unsigned NumParts = getNumRegisters(VT);
3944 SmallVector<SDOperand, 4> Parts(NumParts);
3945 for (unsigned j = 0; j != NumParts; ++j)
3946 Parts[j] = SDOperand(Result, i++);
Dan Gohman532dc2e2007-07-09 20:59:04 +00003947 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003948 break;
3949 }
Dan Gohman27a70be2007-07-02 16:18:06 +00003950 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00003951 }
Dan Gohman27a70be2007-07-02 16:18:06 +00003952 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00003953 return Ops;
3954}
3955
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003956
3957/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3958/// implementation, which just inserts an ISD::CALL node, which is later custom
3959/// lowered by the target to something concrete. FIXME: When all targets are
3960/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3961std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003962TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3963 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003964 unsigned CallingConv, bool isTailCall,
3965 SDOperand Callee,
3966 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003967 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003968 Ops.push_back(Chain); // Op#0 - Chain
3969 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3970 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3971 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3972 Ops.push_back(Callee);
3973
3974 // Handle all of the outgoing arguments.
3975 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003976 MVT::ValueType VT = getValueType(Args[i].Ty);
3977 SDOperand Op = Args[i].Node;
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003978 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003979 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003980 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003981
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003982 if (Args[i].isSExt)
3983 Flags |= ISD::ParamFlags::SExt;
3984 if (Args[i].isZExt)
3985 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003986 if (Args[i].isInReg)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003987 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003988 if (Args[i].isSRet)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003989 Flags |= ISD::ParamFlags::StructReturn;
Rafael Espindola21485be2007-08-20 15:18:24 +00003990 if (Args[i].isByVal) {
3991 Flags |= ISD::ParamFlags::ByVal;
3992 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
3993 const StructType *STy = cast<StructType>(Ty->getElementType());
3994 unsigned StructAlign = Log2_32(getTargetData()->getABITypeAlignment(STy));
3995 unsigned StructSize = getTargetData()->getTypeSize(STy);
3996 Flags |= (StructAlign << ISD::ParamFlags::ByValAlignOffs);
3997 Flags |= (StructSize << ISD::ParamFlags::ByValSizeOffs);
3998 }
Duncan Sands36397f52007-07-27 12:58:54 +00003999 if (Args[i].isNest)
4000 Flags |= ISD::ParamFlags::Nest;
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004001 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004002
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004003 switch (getTypeAction(VT)) {
4004 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004005 case Legal:
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004006 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00004007 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004008 break;
4009 case Promote:
4010 if (MVT::isInteger(VT)) {
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004011 unsigned ExtOp;
4012 if (Args[i].isSExt)
4013 ExtOp = ISD::SIGN_EXTEND;
4014 else if (Args[i].isZExt)
4015 ExtOp = ISD::ZERO_EXTEND;
4016 else
4017 ExtOp = ISD::ANY_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004018 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
4019 } else {
4020 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
Dale Johannesen849f2142007-07-03 00:53:03 +00004021 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004022 }
4023 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00004024 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004025 break;
Dan Gohman27a70be2007-07-02 16:18:06 +00004026 case Expand: {
4027 MVT::ValueType PartVT = getRegisterType(VT);
4028 unsigned NumParts = getNumRegisters(VT);
4029 SmallVector<SDOperand, 4> Parts(NumParts);
Dan Gohman532dc2e2007-07-09 20:59:04 +00004030 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT);
Dan Gohman27a70be2007-07-02 16:18:06 +00004031 for (unsigned i = 0; i != NumParts; ++i) {
4032 // if it isn't first piece, alignment must be 1
4033 unsigned MyFlags = Flags;
4034 if (i != 0)
4035 MyFlags = (MyFlags & (~ISD::ParamFlags::OrigAlignment)) |
4036 (1 << ISD::ParamFlags::OrigAlignmentOffs);
4037
4038 Ops.push_back(Parts[i]);
4039 Ops.push_back(DAG.getConstant(MyFlags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004040 }
4041 break;
4042 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004043 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004044 }
4045
4046 // Figure out the result value types.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004047 MVT::ValueType VT = getValueType(RetTy);
4048 MVT::ValueType RegisterVT = getRegisterType(VT);
4049 unsigned NumRegs = getNumRegisters(VT);
4050 SmallVector<MVT::ValueType, 4> RetTys(NumRegs);
4051 for (unsigned i = 0; i != NumRegs; ++i)
4052 RetTys[i] = RegisterVT;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004053
4054 RetTys.push_back(MVT::Other); // Always has a chain.
4055
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004056 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004057 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004058 DAG.getVTList(&RetTys[0], NumRegs + 1),
Chris Lattnerbe384162006-08-16 22:57:46 +00004059 &Ops[0], Ops.size());
Chris Lattnerb15e4952007-08-02 18:08:16 +00004060 Chain = Res.getValue(NumRegs);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004061
4062 // Gather up the call result into a single value.
4063 if (RetTy != Type::VoidTy) {
4064 ISD::NodeType AssertOp = ISD::AssertSext;
4065 if (!RetTyIsSigned)
4066 AssertOp = ISD::AssertZext;
4067 SmallVector<SDOperand, 4> Results(NumRegs);
4068 for (unsigned i = 0; i != NumRegs; ++i)
4069 Results[i] = Res.getValue(i);
Dan Gohman532dc2e2007-07-09 20:59:04 +00004070 Res = getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT, AssertOp);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004071 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004072
4073 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004074}
4075
Chris Lattner50381b62005-05-14 05:50:48 +00004076SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004077 assert(0 && "LowerOperation not implemented for this target!");
4078 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004079 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004080}
4081
Nate Begeman0aed7842006-01-28 03:14:31 +00004082SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4083 SelectionDAG &DAG) {
4084 assert(0 && "CustomPromoteOperation not implemented for this target!");
4085 abort();
4086 return SDOperand();
4087}
4088
Evan Cheng74d0aa92006-02-15 21:59:04 +00004089/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00004090/// operand.
4091static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00004092 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004093 MVT::ValueType CurVT = VT;
4094 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4095 uint64_t Val = C->getValue() & 255;
4096 unsigned Shift = 8;
4097 while (CurVT != MVT::i8) {
4098 Val = (Val << Shift) | Val;
4099 Shift <<= 1;
4100 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004101 }
4102 return DAG.getConstant(Val, VT);
4103 } else {
4104 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4105 unsigned Shift = 8;
4106 while (CurVT != MVT::i8) {
4107 Value =
4108 DAG.getNode(ISD::OR, VT,
4109 DAG.getNode(ISD::SHL, VT, Value,
4110 DAG.getConstant(Shift, MVT::i8)), Value);
4111 Shift <<= 1;
4112 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004113 }
4114
4115 return Value;
4116 }
4117}
4118
Evan Cheng74d0aa92006-02-15 21:59:04 +00004119/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4120/// used when a memcpy is turned into a memset when the source is a constant
4121/// string ptr.
4122static SDOperand getMemsetStringVal(MVT::ValueType VT,
4123 SelectionDAG &DAG, TargetLowering &TLI,
4124 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004125 uint64_t Val = 0;
Dan Gohmanb55757e2007-05-18 17:52:13 +00004126 unsigned MSB = MVT::getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004127 if (TLI.isLittleEndian())
4128 Offset = Offset + MSB - 1;
4129 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00004130 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00004131 Offset += TLI.isLittleEndian() ? -1 : 1;
4132 }
4133 return DAG.getConstant(Val, VT);
4134}
4135
Evan Cheng1db92f92006-02-14 08:22:34 +00004136/// getMemBasePlusOffset - Returns base and offset node for the
4137static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4138 SelectionDAG &DAG, TargetLowering &TLI) {
4139 MVT::ValueType VT = Base.getValueType();
4140 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4141}
4142
Evan Chengc4f8eee2006-02-14 20:12:38 +00004143/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00004144/// to replace the memset / memcpy is below the threshold. It also returns the
4145/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00004146static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4147 unsigned Limit, uint64_t Size,
4148 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004149 MVT::ValueType VT;
4150
4151 if (TLI.allowsUnalignedMemoryAccesses()) {
4152 VT = MVT::i64;
4153 } else {
4154 switch (Align & 7) {
4155 case 0:
4156 VT = MVT::i64;
4157 break;
4158 case 4:
4159 VT = MVT::i32;
4160 break;
4161 case 2:
4162 VT = MVT::i16;
4163 break;
4164 default:
4165 VT = MVT::i8;
4166 break;
4167 }
4168 }
4169
Evan Cheng80e89d72006-02-14 09:11:59 +00004170 MVT::ValueType LVT = MVT::i64;
4171 while (!TLI.isTypeLegal(LVT))
4172 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4173 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00004174
Evan Cheng80e89d72006-02-14 09:11:59 +00004175 if (VT > LVT)
4176 VT = LVT;
4177
Evan Chengdea72452006-02-14 23:05:54 +00004178 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00004179 while (Size != 0) {
Dan Gohmanb55757e2007-05-18 17:52:13 +00004180 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng1db92f92006-02-14 08:22:34 +00004181 while (VTSize > Size) {
4182 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00004183 VTSize >>= 1;
4184 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004185 assert(MVT::isInteger(VT));
4186
4187 if (++NumMemOps > Limit)
4188 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00004189 MemOps.push_back(VT);
4190 Size -= VTSize;
4191 }
Evan Cheng80e89d72006-02-14 09:11:59 +00004192
4193 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00004194}
4195
Chris Lattner7041ee32005-01-11 05:56:49 +00004196void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00004197 SDOperand Op1 = getValue(I.getOperand(1));
4198 SDOperand Op2 = getValue(I.getOperand(2));
4199 SDOperand Op3 = getValue(I.getOperand(3));
4200 SDOperand Op4 = getValue(I.getOperand(4));
4201 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4202 if (Align == 0) Align = 1;
4203
Dan Gohman5f43f922007-08-27 16:26:13 +00004204 // If the source and destination are known to not be aliases, we can
4205 // lower memmove as memcpy.
4206 if (Op == ISD::MEMMOVE) {
4207 uint64_t Size = -1;
4208 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
4209 Size = C->getValue();
4210 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
4211 AliasAnalysis::NoAlias)
4212 Op = ISD::MEMCPY;
4213 }
4214
Evan Cheng1db92f92006-02-14 08:22:34 +00004215 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4216 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00004217
4218 // Expand memset / memcpy to a series of load / store ops
4219 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004220 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00004221 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00004222 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00004223 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00004224 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4225 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00004226 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00004227 unsigned Offset = 0;
4228 for (unsigned i = 0; i < NumMemOps; i++) {
4229 MVT::ValueType VT = MemOps[i];
Dan Gohmanb55757e2007-05-18 17:52:13 +00004230 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00004231 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00004232 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00004233 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004234 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00004235 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00004236 Offset += VTSize;
4237 }
Evan Cheng1db92f92006-02-14 08:22:34 +00004238 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004239 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00004240 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004241 case ISD::MEMCPY: {
4242 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4243 Size->getValue(), Align, TLI)) {
4244 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00004245 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004246 GlobalAddressSDNode *G = NULL;
4247 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00004248 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004249
4250 if (Op2.getOpcode() == ISD::GlobalAddress)
4251 G = cast<GlobalAddressSDNode>(Op2);
4252 else if (Op2.getOpcode() == ISD::ADD &&
4253 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4254 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4255 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00004256 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00004257 }
4258 if (G) {
4259 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00004260 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00004261 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00004262 if (!Str.empty()) {
4263 CopyFromStr = true;
4264 SrcOff += SrcDelta;
4265 }
4266 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00004267 }
4268
Evan Chengc080d6f2006-02-15 01:54:51 +00004269 for (unsigned i = 0; i < NumMemOps; i++) {
4270 MVT::ValueType VT = MemOps[i];
Dan Gohmanb55757e2007-05-18 17:52:13 +00004271 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00004272 SDOperand Value, Chain, Store;
4273
Evan Chengcffbb512006-02-16 23:11:42 +00004274 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00004275 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4276 Chain = getRoot();
4277 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004278 DAG.getStore(Chain, Value,
4279 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004280 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004281 } else {
4282 Value = DAG.getLoad(VT, getRoot(),
4283 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00004284 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004285 Chain = Value.getValue(1);
4286 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00004287 DAG.getStore(Chain, Value,
4288 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004289 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004290 }
Evan Chengc080d6f2006-02-15 01:54:51 +00004291 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00004292 SrcOff += VTSize;
4293 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00004294 }
4295 }
4296 break;
4297 }
4298 }
4299
4300 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004301 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4302 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00004303 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00004304 }
4305 }
4306
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004307 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00004308}
4309
Chris Lattner7041ee32005-01-11 05:56:49 +00004310//===----------------------------------------------------------------------===//
4311// SelectionDAGISel code
4312//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004313
4314unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4315 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4316}
4317
Chris Lattner495a0b52005-08-17 06:37:43 +00004318void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004319 AU.addRequired<AliasAnalysis>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004320 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004321}
Chris Lattner1c08c712005-01-07 07:47:53 +00004322
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004323
Chris Lattnerbad7f482006-10-28 19:22:10 +00004324
Chris Lattner1c08c712005-01-07 07:47:53 +00004325bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004326 // Get alias analysis for load/store combining.
4327 AA = &getAnalysis<AliasAnalysis>();
4328
Chris Lattner1c08c712005-01-07 07:47:53 +00004329 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4330 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00004331 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004332
4333 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4334
Duncan Sandsea632432007-06-13 16:53:21 +00004335 if (ExceptionHandling)
4336 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4337 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4338 // Mark landing pad.
4339 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004340
4341 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004342 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004343
Evan Chengad2070c2007-02-10 02:43:39 +00004344 // Add function live-ins to entry block live-in set.
4345 BasicBlock *EntryBB = &Fn.getEntryBlock();
4346 BB = FuncInfo.MBBMap[EntryBB];
4347 if (!MF.livein_empty())
4348 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4349 E = MF.livein_end(); I != E; ++I)
4350 BB->addLiveIn(I->first);
4351
Duncan Sandsf4070822007-06-15 19:04:19 +00004352#ifndef NDEBUG
4353 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4354 "Not all catch info was assigned to a landing pad!");
4355#endif
4356
Chris Lattner1c08c712005-01-07 07:47:53 +00004357 return true;
4358}
4359
Chris Lattner571e4342006-10-27 21:36:01 +00004360SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4361 unsigned Reg) {
4362 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004363 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004364 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004365 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004366
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004367 MVT::ValueType SrcVT = Op.getValueType();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004368 MVT::ValueType RegisterVT = TLI.getRegisterType(SrcVT);
4369 unsigned NumRegs = TLI.getNumRegisters(SrcVT);
4370 SmallVector<SDOperand, 8> Regs(NumRegs);
4371 SmallVector<SDOperand, 8> Chains(NumRegs);
4372
4373 // Copy the value by legal parts into sequential virtual registers.
Dan Gohman532dc2e2007-07-09 20:59:04 +00004374 getCopyToParts(DAG, Op, &Regs[0], NumRegs, RegisterVT);
Dan Gohman27a70be2007-07-02 16:18:06 +00004375 for (unsigned i = 0; i != NumRegs; ++i)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004376 Chains[i] = DAG.getCopyToReg(getRoot(), Reg + i, Regs[i]);
4377 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattner1c08c712005-01-07 07:47:53 +00004378}
4379
Chris Lattner068a81e2005-01-17 17:15:02 +00004380void SelectionDAGISel::
Evan Cheng15699fc2007-02-10 01:08:18 +00004381LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner068a81e2005-01-17 17:15:02 +00004382 std::vector<SDOperand> &UnorderedChains) {
4383 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004384 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004385 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004386 SDOperand OldRoot = SDL.DAG.getRoot();
4387 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004388
Chris Lattnerbf209482005-10-30 19:42:35 +00004389 unsigned a = 0;
4390 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4391 AI != E; ++AI, ++a)
4392 if (!AI->use_empty()) {
4393 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004394
Chris Lattnerbf209482005-10-30 19:42:35 +00004395 // If this argument is live outside of the entry block, insert a copy from
4396 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004397 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4398 if (VMI != FuncInfo.ValueMap.end()) {
4399 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004400 UnorderedChains.push_back(Copy);
4401 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004402 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004403
Chris Lattnerbf209482005-10-30 19:42:35 +00004404 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004405 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004406 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004407}
4408
Duncan Sandsf4070822007-06-15 19:04:19 +00004409static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4410 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4411 assert(!FLI.MBBMap[SrcBB]->isLandingPad() &&
4412 "Copying catch info out of a landing pad!");
4413 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004414 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004415 // Apply the catch info to DestBB.
4416 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4417#ifndef NDEBUG
4418 FLI.CatchInfoFound.insert(I);
4419#endif
4420 }
4421}
4422
Chris Lattner1c08c712005-01-07 07:47:53 +00004423void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4424 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004425 FunctionLoweringInfo &FuncInfo) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004426 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004427
4428 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004429
Chris Lattnerbf209482005-10-30 19:42:35 +00004430 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004431 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattnerbf209482005-10-30 19:42:35 +00004432 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004433
4434 BB = FuncInfo.MBBMap[LLVMBB];
4435 SDL.setCurrentBasicBlock(BB);
4436
Duncan Sandsf4070822007-06-15 19:04:19 +00004437 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004438
Duncan Sandsf4070822007-06-15 19:04:19 +00004439 if (ExceptionHandling && MMI && BB->isLandingPad()) {
4440 // Add a label to mark the beginning of the landing pad. Deletion of the
4441 // landing pad can thus be detected via the MachineModuleInfo.
4442 unsigned LabelID = MMI->addLandingPad(BB);
4443 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4444 DAG.getConstant(LabelID, MVT::i32)));
4445
Evan Chenge47c3332007-06-27 18:45:32 +00004446 // Mark exception register as live in.
4447 unsigned Reg = TLI.getExceptionAddressRegister();
4448 if (Reg) BB->addLiveIn(Reg);
4449
4450 // Mark exception selector register as live in.
4451 Reg = TLI.getExceptionSelectorRegister();
4452 if (Reg) BB->addLiveIn(Reg);
4453
Duncan Sandsf4070822007-06-15 19:04:19 +00004454 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4455 // function and list of typeids logically belong to the invoke (or, if you
4456 // like, the basic block containing the invoke), and need to be associated
4457 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004458 // information is provided by an intrinsic (eh.selector) that can be moved
4459 // to unexpected places by the optimizers: if the unwind edge is critical,
4460 // then breaking it can result in the intrinsics being in the successor of
4461 // the landing pad, not the landing pad itself. This results in exceptions
4462 // not being caught because no typeids are associated with the invoke.
4463 // This may not be the only way things can go wrong, but it is the only way
4464 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004465 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4466
4467 if (Br && Br->isUnconditional()) { // Critical edge?
4468 BasicBlock::iterator I, E;
4469 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004470 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004471 break;
4472
4473 if (I == E)
4474 // No catch info found - try to extract some from the successor.
4475 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004476 }
4477 }
4478
Chris Lattner1c08c712005-01-07 07:47:53 +00004479 // Lower all of the non-terminator instructions.
4480 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4481 I != E; ++I)
4482 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004483
Chris Lattner1c08c712005-01-07 07:47:53 +00004484 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004485 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004486 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004487 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004488 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004489 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004490 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004491 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004492 }
4493
4494 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4495 // ensure constants are generated when needed. Remember the virtual registers
4496 // that need to be added to the Machine PHI nodes as input. We cannot just
4497 // directly add them, because expansion might result in multiple MBB's for one
4498 // BB. As such, the start of the BB might correspond to a different MBB than
4499 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004500 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004501 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004502
4503 // Emit constants only once even if used by multiple PHI nodes.
4504 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004505
Chris Lattner8c494ab2006-10-27 23:50:33 +00004506 // Vector bool would be better, but vector<bool> is really slow.
4507 std::vector<unsigned char> SuccsHandled;
4508 if (TI->getNumSuccessors())
4509 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4510
Dan Gohman532dc2e2007-07-09 20:59:04 +00004511 // Check successor nodes' PHI nodes that expect a constant to be available
4512 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004513 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4514 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004515 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004516 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004517
Chris Lattner8c494ab2006-10-27 23:50:33 +00004518 // If this terminator has multiple identical successors (common for
4519 // switches), only handle each succ once.
4520 unsigned SuccMBBNo = SuccMBB->getNumber();
4521 if (SuccsHandled[SuccMBBNo]) continue;
4522 SuccsHandled[SuccMBBNo] = true;
4523
4524 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004525 PHINode *PN;
4526
4527 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4528 // nodes and Machine PHI nodes, but the incoming operands have not been
4529 // emitted yet.
4530 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004531 (PN = dyn_cast<PHINode>(I)); ++I) {
4532 // Ignore dead phi's.
4533 if (PN->use_empty()) continue;
4534
4535 unsigned Reg;
4536 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004537
Chris Lattner8c494ab2006-10-27 23:50:33 +00004538 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4539 unsigned &RegOut = ConstantsOut[C];
4540 if (RegOut == 0) {
4541 RegOut = FuncInfo.CreateRegForValue(C);
4542 UnorderedChains.push_back(
4543 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004544 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004545 Reg = RegOut;
4546 } else {
4547 Reg = FuncInfo.ValueMap[PHIOp];
4548 if (Reg == 0) {
4549 assert(isa<AllocaInst>(PHIOp) &&
4550 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4551 "Didn't codegen value into a register!??");
4552 Reg = FuncInfo.CreateRegForValue(PHIOp);
4553 UnorderedChains.push_back(
4554 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004555 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004556 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004557
4558 // Remember that this register needs to added to the machine PHI node as
4559 // the input for this MBB.
4560 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004561 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004562 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004563 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4564 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004565 }
4566 ConstantsOut.clear();
4567
Chris Lattnerddb870b2005-01-13 17:59:43 +00004568 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004569 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004570 SDOperand Root = SDL.getRoot();
4571 if (Root.getOpcode() != ISD::EntryToken) {
4572 unsigned i = 0, e = UnorderedChains.size();
4573 for (; i != e; ++i) {
4574 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4575 if (UnorderedChains[i].Val->getOperand(0) == Root)
4576 break; // Don't add the root if we already indirectly depend on it.
4577 }
4578
4579 if (i == e)
4580 UnorderedChains.push_back(Root);
4581 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004582 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4583 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004584 }
4585
Chris Lattner1c08c712005-01-07 07:47:53 +00004586 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004587 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004588
Nate Begemanf15485a2006-03-27 01:32:24 +00004589 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004590 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004591 SwitchCases.clear();
4592 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004593 JTCases.clear();
4594 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004595 BitTestCases.clear();
4596 BitTestCases = SDL.BitTestCases;
4597
Chris Lattnera651cf62005-01-17 19:43:36 +00004598 // Make sure the root of the DAG is up-to-date.
4599 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004600}
4601
Nate Begemanf15485a2006-03-27 01:32:24 +00004602void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Chris Lattneraf21d552005-10-10 16:47:10 +00004603 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004604 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004605
Bill Wendling832171c2006-12-07 20:04:42 +00004606 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004607 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004608
Chris Lattner1c08c712005-01-07 07:47:53 +00004609 // Second step, hack on the DAG until it only uses operations and types that
4610 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004611 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004612
Bill Wendling832171c2006-12-07 20:04:42 +00004613 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004614 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004615
Chris Lattneraf21d552005-10-10 16:47:10 +00004616 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004617 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004618
Evan Chenga9c20912006-01-21 02:32:06 +00004619 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004620
Chris Lattnera33ef482005-03-30 01:10:47 +00004621 // Third, instruction select all of the operations to machine code, adding the
4622 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004623 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004624
Bill Wendling832171c2006-12-07 20:04:42 +00004625 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004626 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004627}
Chris Lattner1c08c712005-01-07 07:47:53 +00004628
Nate Begemanf15485a2006-03-27 01:32:24 +00004629void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4630 FunctionLoweringInfo &FuncInfo) {
4631 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4632 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004633 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004634 CurDAG = &DAG;
4635
4636 // First step, lower LLVM code to some DAG. This DAG may use operations and
4637 // types that are not supported by the target.
4638 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4639
4640 // Second step, emit the lowered DAG as machine code.
4641 CodeGenAndEmitDAG(DAG);
4642 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004643
4644 DOUT << "Total amount of phi nodes to update: "
4645 << PHINodesToUpdate.size() << "\n";
4646 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4647 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4648 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004649
Chris Lattnera33ef482005-03-30 01:10:47 +00004650 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004651 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004652 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004653 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4654 MachineInstr *PHI = PHINodesToUpdate[i].first;
4655 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4656 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004657 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004658 PHI->addMachineBasicBlockOperand(BB);
4659 }
4660 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004661 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004662
4663 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4664 // Lower header first, if it wasn't already lowered
4665 if (!BitTestCases[i].Emitted) {
4666 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4667 CurDAG = &HSDAG;
Dan Gohman5f43f922007-08-27 16:26:13 +00004668 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004669 // Set the current basic block to the mbb we wish to insert the code into
4670 BB = BitTestCases[i].Parent;
4671 HSDL.setCurrentBasicBlock(BB);
4672 // Emit the code
4673 HSDL.visitBitTestHeader(BitTestCases[i]);
4674 HSDAG.setRoot(HSDL.getRoot());
4675 CodeGenAndEmitDAG(HSDAG);
4676 }
4677
4678 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4679 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4680 CurDAG = &BSDAG;
Dan Gohman5f43f922007-08-27 16:26:13 +00004681 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004682 // Set the current basic block to the mbb we wish to insert the code into
4683 BB = BitTestCases[i].Cases[j].ThisBB;
4684 BSDL.setCurrentBasicBlock(BB);
4685 // Emit the code
4686 if (j+1 != ej)
4687 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4688 BitTestCases[i].Reg,
4689 BitTestCases[i].Cases[j]);
4690 else
4691 BSDL.visitBitTestCase(BitTestCases[i].Default,
4692 BitTestCases[i].Reg,
4693 BitTestCases[i].Cases[j]);
4694
4695
4696 BSDAG.setRoot(BSDL.getRoot());
4697 CodeGenAndEmitDAG(BSDAG);
4698 }
4699
4700 // Update PHI Nodes
4701 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4702 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4703 MachineBasicBlock *PHIBB = PHI->getParent();
4704 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4705 "This is not a machine PHI node that we are updating!");
4706 // This is "default" BB. We have two jumps to it. From "header" BB and
4707 // from last "case" BB.
4708 if (PHIBB == BitTestCases[i].Default) {
4709 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4710 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikov8085bcf2007-04-13 06:53:51 +00004711 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004712 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4713 }
4714 // One of "cases" BB.
4715 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4716 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4717 if (cBB->succ_end() !=
4718 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4719 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4720 PHI->addMachineBasicBlockOperand(cBB);
4721 }
4722 }
4723 }
4724 }
4725
Nate Begeman9453eea2006-04-23 06:26:20 +00004726 // If the JumpTable record is filled in, then we need to emit a jump table.
4727 // Updating the PHI nodes is tricky in this case, since we need to determine
4728 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004729 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4730 // Lower header first, if it wasn't already lowered
4731 if (!JTCases[i].first.Emitted) {
4732 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4733 CurDAG = &HSDAG;
Dan Gohman5f43f922007-08-27 16:26:13 +00004734 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004735 // Set the current basic block to the mbb we wish to insert the code into
4736 BB = JTCases[i].first.HeaderBB;
4737 HSDL.setCurrentBasicBlock(BB);
4738 // Emit the code
4739 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4740 HSDAG.setRoot(HSDL.getRoot());
4741 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004742 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004743
4744 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4745 CurDAG = &JSDAG;
Dan Gohman5f43f922007-08-27 16:26:13 +00004746 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo);
Nate Begeman37efe672006-04-22 18:53:45 +00004747 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004748 BB = JTCases[i].second.MBB;
4749 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004750 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004751 JSDL.visitJumpTable(JTCases[i].second);
4752 JSDAG.setRoot(JSDL.getRoot());
4753 CodeGenAndEmitDAG(JSDAG);
4754
Nate Begeman37efe672006-04-22 18:53:45 +00004755 // Update PHI Nodes
4756 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4757 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4758 MachineBasicBlock *PHIBB = PHI->getParent();
4759 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4760 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004761 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004762 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004763 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004764 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemanf4360a42006-05-03 03:48:02 +00004765 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004766 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00004767 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004768 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004769 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004770 }
4771 }
Nate Begeman37efe672006-04-22 18:53:45 +00004772 }
4773
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004774 // If the switch block involved a branch to one of the actual successors, we
4775 // need to update PHI nodes in that block.
4776 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4777 MachineInstr *PHI = PHINodesToUpdate[i].first;
4778 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4779 "This is not a machine PHI node that we are updating!");
4780 if (BB->isSuccessor(PHI->getParent())) {
4781 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4782 PHI->addMachineBasicBlockOperand(BB);
4783 }
4784 }
4785
Nate Begemanf15485a2006-03-27 01:32:24 +00004786 // If we generated any switch lowering information, build and codegen any
4787 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004788 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004789 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004790 CurDAG = &SDAG;
Dan Gohman5f43f922007-08-27 16:26:13 +00004791 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004792
Nate Begemanf15485a2006-03-27 01:32:24 +00004793 // Set the current basic block to the mbb we wish to insert the code into
4794 BB = SwitchCases[i].ThisBB;
4795 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004796
Nate Begemanf15485a2006-03-27 01:32:24 +00004797 // Emit the code
4798 SDL.visitSwitchCase(SwitchCases[i]);
4799 SDAG.setRoot(SDL.getRoot());
4800 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004801
4802 // Handle any PHI nodes in successors of this chunk, as if we were coming
4803 // from the original BB before switch expansion. Note that PHI nodes can
4804 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4805 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004806 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004807 for (MachineBasicBlock::iterator Phi = BB->begin();
4808 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4809 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4810 for (unsigned pn = 0; ; ++pn) {
4811 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4812 if (PHINodesToUpdate[pn].first == Phi) {
4813 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4814 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4815 break;
4816 }
4817 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004818 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004819
4820 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004821 if (BB == SwitchCases[i].FalseBB)
4822 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004823
4824 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004825 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004826 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004827 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004828 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004829 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004830}
Evan Chenga9c20912006-01-21 02:32:06 +00004831
Jim Laskey13ec7022006-08-01 14:21:23 +00004832
Evan Chenga9c20912006-01-21 02:32:06 +00004833//===----------------------------------------------------------------------===//
4834/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4835/// target node in the graph.
4836void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4837 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004838
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004839 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004840
4841 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004842 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004843 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004844 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004845
Jim Laskey9ff542f2006-08-01 18:29:48 +00004846 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004847 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00004848
4849 if (ViewSUnitDAGs) SL->viewGraph();
4850
Evan Chengcccf1232006-02-04 06:49:00 +00004851 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004852}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004853
Chris Lattner03fc53c2006-03-06 00:22:00 +00004854
Jim Laskey9ff542f2006-08-01 18:29:48 +00004855HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4856 return new HazardRecognizer();
4857}
4858
Chris Lattner75548062006-10-11 03:58:02 +00004859//===----------------------------------------------------------------------===//
4860// Helper functions used by the generated instruction selector.
4861//===----------------------------------------------------------------------===//
4862// Calls to these methods are generated by tblgen.
4863
4864/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4865/// the dag combiner simplified the 255, we still want to match. RHS is the
4866/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4867/// specified in the .td file (e.g. 255).
4868bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00004869 int64_t DesiredMaskS) const {
Chris Lattner75548062006-10-11 03:58:02 +00004870 uint64_t ActualMask = RHS->getValue();
4871 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4872
4873 // If the actual mask exactly matches, success!
4874 if (ActualMask == DesiredMask)
4875 return true;
4876
4877 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4878 if (ActualMask & ~DesiredMask)
4879 return false;
4880
4881 // Otherwise, the DAG Combiner may have proven that the value coming in is
4882 // either already zero or is not demanded. Check for known zero input bits.
4883 uint64_t NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00004884 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00004885 return true;
4886
4887 // TODO: check to see if missing bits are just not demanded.
4888
4889 // Otherwise, this pattern doesn't match.
4890 return false;
4891}
4892
4893/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4894/// the dag combiner simplified the 255, we still want to match. RHS is the
4895/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4896/// specified in the .td file (e.g. 255).
4897bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00004898 int64_t DesiredMaskS) const {
Chris Lattner75548062006-10-11 03:58:02 +00004899 uint64_t ActualMask = RHS->getValue();
4900 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4901
4902 // If the actual mask exactly matches, success!
4903 if (ActualMask == DesiredMask)
4904 return true;
4905
4906 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4907 if (ActualMask & ~DesiredMask)
4908 return false;
4909
4910 // Otherwise, the DAG Combiner may have proven that the value coming in is
4911 // either already zero or is not demanded. Check for known zero input bits.
4912 uint64_t NeededMask = DesiredMask & ~ActualMask;
4913
4914 uint64_t KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00004915 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00004916
4917 // If all the missing bits in the or are already known to be set, match!
4918 if ((NeededMask & KnownOne) == NeededMask)
4919 return true;
4920
4921 // TODO: check to see if missing bits are just not demanded.
4922
4923 // Otherwise, this pattern doesn't match.
4924 return false;
4925}
4926
Jim Laskey9ff542f2006-08-01 18:29:48 +00004927
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004928/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4929/// by tblgen. Others should not call it.
4930void SelectionDAGISel::
4931SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4932 std::vector<SDOperand> InOps;
4933 std::swap(InOps, Ops);
4934
4935 Ops.push_back(InOps[0]); // input chain.
4936 Ops.push_back(InOps[1]); // input asm string.
4937
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004938 unsigned i = 2, e = InOps.size();
4939 if (InOps[e-1].getValueType() == MVT::Flag)
4940 --e; // Don't process a flag operand if it is here.
4941
4942 while (i != e) {
4943 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4944 if ((Flags & 7) != 4 /*MEM*/) {
4945 // Just skip over this operand, copying the operands verbatim.
4946 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4947 i += (Flags >> 3) + 1;
4948 } else {
4949 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4950 // Otherwise, this is a memory operand. Ask the target to select it.
4951 std::vector<SDOperand> SelOps;
4952 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004953 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004954 exit(1);
4955 }
4956
4957 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00004958 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00004959 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00004960 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004961 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4962 i += 2;
4963 }
4964 }
4965
4966 // Add the flag input back if present.
4967 if (e != InOps.size())
4968 Ops.push_back(InOps.back());
4969}
Devang Patel794fd752007-05-01 21:15:47 +00004970
Devang Patel19974732007-05-03 01:11:54 +00004971char SelectionDAGISel::ID = 0;