blob: 664979512f2c64dd8bf8f62a64879d64718a74b3 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000027#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000028#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000047#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000048#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000049#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000050#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000051using namespace llvm;
52
Chris Lattner975f5c92005-09-01 18:44:10 +000053#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000054static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000055ViewISelDAGs("view-isel-dags", cl::Hidden,
56 cl::desc("Pop up a window to show isel dags as they are selected"));
57static cl::opt<bool>
58ViewSchedDAGs("view-sched-dags", cl::Hidden,
59 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000060#else
Chris Lattneref598052006-04-02 03:07:27 +000061static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000062#endif
63
Jim Laskey29e635d2006-08-02 12:30:23 +000064
65//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000077namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000080 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000082 cl::desc("Instruction schedulers available:"));
83
Jim Laskey03593f72006-08-01 18:29:48 +000084 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000085 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000087} // namespace
88
Chris Lattner6f87d182006-02-22 22:37:12 +000089namespace {
90 /// RegsForValue - This struct represents the physical registers that a
91 /// particular value is assigned and the type information about the value.
92 /// This is needed because values can be promoted into larger registers and
93 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000094 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000095 /// Regs - This list hold the register (for legal and promoted values)
96 /// or register set (for expanded values) that the value should be assigned
97 /// to.
98 std::vector<unsigned> Regs;
99
100 /// RegVT - The value type of each register.
101 ///
102 MVT::ValueType RegVT;
103
104 /// ValueVT - The value type of the LLVM value, which may be promoted from
105 /// RegVT or made from merging the two expanded parts.
106 MVT::ValueType ValueVT;
107
108 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
109
110 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
111 : RegVT(regvt), ValueVT(valuevt) {
112 Regs.push_back(Reg);
113 }
114 RegsForValue(const std::vector<unsigned> &regs,
115 MVT::ValueType regvt, MVT::ValueType valuevt)
116 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 }
118
119 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
120 /// this value and returns the result as a ValueVT value. This uses
121 /// Chain/Flag as the input and updates them for the output Chain/Flag.
122 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000123 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000124
125 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
126 /// specified value into the registers specified by this object. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000129 SDOperand &Chain, SDOperand &Flag,
130 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000131
132 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
133 /// operand list. This adds the code marker and includes the number of
134 /// values added into it.
135 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000136 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000137 };
138}
Evan Chengc1e1d972006-01-23 07:01:07 +0000139
Chris Lattner7a60d912005-01-07 07:47:53 +0000140namespace llvm {
141 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000142 /// createDefaultScheduler - This creates an instruction scheduler appropriate
143 /// for the target.
144 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
145 SelectionDAG *DAG,
146 MachineBasicBlock *BB) {
147 TargetLowering &TLI = IS->getTargetLowering();
148
149 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
150 return createTDListDAGScheduler(IS, DAG, BB);
151 } else {
152 assert(TLI.getSchedulingPreference() ==
153 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
154 return createBURRListDAGScheduler(IS, DAG, BB);
155 }
156 }
157
158
159 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000160 /// FunctionLoweringInfo - This contains information that is global to a
161 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000162 class FunctionLoweringInfo {
163 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000164 TargetLowering &TLI;
165 Function &Fn;
166 MachineFunction &MF;
167 SSARegMap *RegMap;
168
169 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
170
171 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
172 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
173
174 /// ValueMap - Since we emit code for the function a basic block at a time,
175 /// we must remember which virtual registers hold the values for
176 /// cross-basic-block values.
177 std::map<const Value*, unsigned> ValueMap;
178
179 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
180 /// the entry block. This allows the allocas to be efficiently referenced
181 /// anywhere in the function.
182 std::map<const AllocaInst*, int> StaticAllocaMap;
183
184 unsigned MakeReg(MVT::ValueType VT) {
185 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
186 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000187
188 /// isExportedInst - Return true if the specified value is an instruction
189 /// exported from its block.
190 bool isExportedInst(const Value *V) {
191 return ValueMap.count(V);
192 }
Misha Brukman835702a2005-04-21 22:36:52 +0000193
Chris Lattner49409cb2006-03-16 19:51:18 +0000194 unsigned CreateRegForValue(const Value *V);
195
Chris Lattner7a60d912005-01-07 07:47:53 +0000196 unsigned InitializeRegForValue(const Value *V) {
197 unsigned &R = ValueMap[V];
198 assert(R == 0 && "Already initialized this value register!");
199 return R = CreateRegForValue(V);
200 }
201 };
202}
203
204/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000205/// PHI nodes or outside of the basic block that defines it, or used by a
206/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000207static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
208 if (isa<PHINode>(I)) return true;
209 BasicBlock *BB = I->getParent();
210 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000211 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000212 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000213 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000214 return true;
215 return false;
216}
217
Chris Lattner6871b232005-10-30 19:42:35 +0000218/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000219/// entry block, return true. This includes arguments used by switches, since
220/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000221static bool isOnlyUsedInEntryBlock(Argument *A) {
222 BasicBlock *Entry = A->getParent()->begin();
223 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000224 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000225 return false; // Use not in entry block.
226 return true;
227}
228
Chris Lattner7a60d912005-01-07 07:47:53 +0000229FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000230 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000231 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
232
Chris Lattner6871b232005-10-30 19:42:35 +0000233 // Create a vreg for each argument register that is not dead and is used
234 // outside of the entry block for the function.
235 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
236 AI != E; ++AI)
237 if (!isOnlyUsedInEntryBlock(AI))
238 InitializeRegForValue(AI);
239
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 // Initialize the mapping of values to registers. This is only set up for
241 // instruction values that are used outside of the block that defines
242 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000243 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
245 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000246 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000247 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000248 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000249 unsigned Align =
Owen Anderson20a631f2006-05-03 01:29:57 +0000250 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000251 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000252
Reid Spencere0fc4df2006-10-20 07:07:24 +0000253 // If the alignment of the value is smaller than the size of the
254 // value, and if the size of the value is particularly small
255 // (<= 8 bytes), round up to the size of the value for potentially
256 // better performance.
Chris Lattnercbefe722005-05-13 23:14:17 +0000257 //
258 // FIXME: This could be made better with a preferred alignment hook in
259 // TargetData. It serves primarily to 8-byte align doubles for X86.
260 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000261 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000262 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000263 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000264 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000265 }
266
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000267 for (; BB != EB; ++BB)
268 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000269 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
270 if (!isa<AllocaInst>(I) ||
271 !StaticAllocaMap.count(cast<AllocaInst>(I)))
272 InitializeRegForValue(I);
273
274 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
275 // also creates the initial PHI MachineInstrs, though none of the input
276 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000277 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000278 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
279 MBBMap[BB] = MBB;
280 MF.getBasicBlockList().push_back(MBB);
281
282 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
283 // appropriate.
284 PHINode *PN;
285 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000286 (PN = dyn_cast<PHINode>(I)); ++I)
287 if (!PN->use_empty()) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000288 MVT::ValueType VT = TLI.getValueType(PN->getType());
289 unsigned NumElements;
290 if (VT != MVT::Vector)
291 NumElements = TLI.getNumElements(VT);
292 else {
293 MVT::ValueType VT1,VT2;
294 NumElements =
295 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
296 VT1, VT2);
297 }
Chris Lattner8ea875f2005-01-07 21:34:19 +0000298 unsigned PHIReg = ValueMap[PN];
299 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
300 for (unsigned i = 0; i != NumElements; ++i)
301 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
302 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000303 }
304}
305
Chris Lattner49409cb2006-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
312 // The number of multiples of registers that we need, to, e.g., split up
313 // a <2 x int64> -> 4 x i32 registers.
314 unsigned NumVectorRegs = 1;
315
316 // If this is a packed type, figure out what type it will decompose into
317 // and how many of the elements it will use.
318 if (VT == MVT::Vector) {
319 const PackedType *PTy = cast<PackedType>(V->getType());
320 unsigned NumElts = PTy->getNumElements();
321 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
322
323 // Divide the input until we get to a supported size. This will always
324 // end with a scalar if the target doesn't support vectors.
325 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
326 NumElts >>= 1;
327 NumVectorRegs <<= 1;
328 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000329 if (NumElts == 1)
330 VT = EltTy;
331 else
332 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000333 }
334
335 // The common case is that we will only create one register for this
336 // value. If we have that case, create and return the virtual register.
337 unsigned NV = TLI.getNumElements(VT);
338 if (NV == 1) {
339 // If we are promoting this value, pick the next largest supported type.
340 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
341 unsigned Reg = MakeReg(PromotedType);
342 // If this is a vector of supported or promoted types (e.g. 4 x i16),
343 // create all of the registers.
344 for (unsigned i = 1; i != NumVectorRegs; ++i)
345 MakeReg(PromotedType);
346 return Reg;
347 }
348
349 // If this value is represented with multiple target registers, make sure
350 // to create enough consecutive registers of the right (smaller) type.
351 unsigned NT = VT-1; // Find the type to use.
352 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
353 --NT;
354
355 unsigned R = MakeReg((MVT::ValueType)NT);
356 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
357 MakeReg((MVT::ValueType)NT);
358 return R;
359}
Chris Lattner7a60d912005-01-07 07:47:53 +0000360
361//===----------------------------------------------------------------------===//
362/// SelectionDAGLowering - This is the common target-independent lowering
363/// implementation that is parameterized by a TargetLowering object.
364/// Also, targets can overload any lowering method.
365///
366namespace llvm {
367class SelectionDAGLowering {
368 MachineBasicBlock *CurMBB;
369
370 std::map<const Value*, SDOperand> NodeMap;
371
Chris Lattner4d9651c2005-01-17 22:19:26 +0000372 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
373 /// them up and then emit token factor nodes when possible. This allows us to
374 /// get simple disambiguation between loads without worrying about alias
375 /// analysis.
376 std::vector<SDOperand> PendingLoads;
377
Nate Begemaned728c12006-03-27 01:32:24 +0000378 /// Case - A pair of values to record the Value for a switch case, and the
379 /// case's target basic block.
380 typedef std::pair<Constant*, MachineBasicBlock*> Case;
381 typedef std::vector<Case>::iterator CaseItr;
382 typedef std::pair<CaseItr, CaseItr> CaseRange;
383
384 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
385 /// of conditional branches.
386 struct CaseRec {
387 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
388 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
389
390 /// CaseBB - The MBB in which to emit the compare and branch
391 MachineBasicBlock *CaseBB;
392 /// LT, GE - If nonzero, we know the current case value must be less-than or
393 /// greater-than-or-equal-to these Constants.
394 Constant *LT;
395 Constant *GE;
396 /// Range - A pair of iterators representing the range of case values to be
397 /// processed at this point in the binary search tree.
398 CaseRange Range;
399 };
400
401 /// The comparison function for sorting Case values.
402 struct CaseCmp {
403 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000404 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
405 if (I1->getType()->isUnsigned())
406 return I1->getZExtValue() <
407 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000408
Reid Spencere0fc4df2006-10-20 07:07:24 +0000409 return cast<const ConstantInt>(C1.first)->getSExtValue() <
410 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000411 }
412 };
413
Chris Lattner7a60d912005-01-07 07:47:53 +0000414public:
415 // TLI - This is information that describes the available target features we
416 // need for lowering. This indicates when operations are unavailable,
417 // implemented with a libcall, etc.
418 TargetLowering &TLI;
419 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000420 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000421
Nate Begemaned728c12006-03-27 01:32:24 +0000422 /// SwitchCases - Vector of CaseBlock structures used to communicate
423 /// SwitchInst code generation information.
424 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000425 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000426
Chris Lattner7a60d912005-01-07 07:47:53 +0000427 /// FuncInfo - Information about the function as a whole.
428 ///
429 FunctionLoweringInfo &FuncInfo;
430
431 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000432 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000433 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000434 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000435 }
436
Chris Lattner4108bb02005-01-17 19:43:36 +0000437 /// getRoot - Return the current virtual root of the Selection DAG.
438 ///
439 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000440 if (PendingLoads.empty())
441 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000442
Chris Lattner4d9651c2005-01-17 22:19:26 +0000443 if (PendingLoads.size() == 1) {
444 SDOperand Root = PendingLoads[0];
445 DAG.setRoot(Root);
446 PendingLoads.clear();
447 return Root;
448 }
449
450 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000451 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
452 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000453 PendingLoads.clear();
454 DAG.setRoot(Root);
455 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000456 }
457
Chris Lattnered0110b2006-10-27 21:36:01 +0000458 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
459
Chris Lattner7a60d912005-01-07 07:47:53 +0000460 void visit(Instruction &I) { visit(I.getOpcode(), I); }
461
462 void visit(unsigned Opcode, User &I) {
463 switch (Opcode) {
464 default: assert(0 && "Unknown instruction type encountered!");
465 abort();
466 // Build the switch statement using the Instruction.def file.
467#define HANDLE_INST(NUM, OPCODE, CLASS) \
468 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
469#include "llvm/Instruction.def"
470 }
471 }
472
473 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
474
Chris Lattner4024c002006-03-15 22:19:46 +0000475 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000476 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000477 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000478
479 SDOperand getIntPtrConstant(uint64_t Val) {
480 return DAG.getConstant(Val, TLI.getPointerTy());
481 }
482
Chris Lattner8471b152006-03-16 19:57:50 +0000483 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000484
485 const SDOperand &setValue(const Value *V, SDOperand NewN) {
486 SDOperand &N = NodeMap[V];
487 assert(N.Val == 0 && "Already set a value for this node!");
488 return N = NewN;
489 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000490
Chris Lattner6f87d182006-02-22 22:37:12 +0000491 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
492 MVT::ValueType VT,
493 bool OutReg, bool InReg,
494 std::set<unsigned> &OutputRegs,
495 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000496
Chris Lattnered0110b2006-10-27 21:36:01 +0000497 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
498 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
499 unsigned Opc);
500 void ExportFromCurrentBlock(Value *V);
501
Chris Lattner7a60d912005-01-07 07:47:53 +0000502 // Terminator instructions.
503 void visitRet(ReturnInst &I);
504 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000505 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000506 void visitUnreachable(UnreachableInst &I) { /* noop */ }
507
Nate Begemaned728c12006-03-27 01:32:24 +0000508 // Helper for visitSwitch
509 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000510 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000511
Chris Lattner7a60d912005-01-07 07:47:53 +0000512 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000513 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
514 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
515
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000516 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
517 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000518 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000519 void visitAdd(User &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000520 if (I.getType()->isFloatingPoint())
521 visitFPBinary(I, ISD::FADD, ISD::VADD);
522 else
523 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000524 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000525 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000526 void visitMul(User &I) {
527 if (I.getType()->isFloatingPoint())
528 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
529 else
530 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000531 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000532 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
533 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
534 void visitFDiv(User &I) { visitFPBinary(I, ISD::FDIV, ISD::VSDIV); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000535 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000536 const Type *Ty = I.getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000537 if (Ty->isFloatingPoint())
538 visitFPBinary(I, ISD::FREM, 0);
539 else
540 visitIntBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000541 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000542 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
543 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
544 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000545 void visitShl(User &I) { visitShift(I, ISD::SHL); }
546 void visitShr(User &I) {
547 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000548 }
549
Evan Cheng1c5b7d12006-05-23 06:40:47 +0000550 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
551 ISD::CondCode FPOpc);
552 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
553 ISD::SETOEQ); }
554 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
555 ISD::SETUNE); }
556 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
557 ISD::SETOLE); }
558 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
559 ISD::SETOGE); }
560 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
561 ISD::SETOLT); }
562 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
563 ISD::SETOGT); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000564
Chris Lattner67271862006-03-29 00:11:43 +0000565 void visitExtractElement(User &I);
566 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000567 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000568
Chris Lattner7a60d912005-01-07 07:47:53 +0000569 void visitGetElementPtr(User &I);
570 void visitCast(User &I);
571 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000572
573 void visitMalloc(MallocInst &I);
574 void visitFree(FreeInst &I);
575 void visitAlloca(AllocaInst &I);
576 void visitLoad(LoadInst &I);
577 void visitStore(StoreInst &I);
578 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
579 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000580 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000581 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000582 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000583
Chris Lattner7a60d912005-01-07 07:47:53 +0000584 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000585 void visitVAArg(VAArgInst &I);
586 void visitVAEnd(CallInst &I);
587 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000588 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000589
Chris Lattner875def92005-01-11 05:56:49 +0000590 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000591
592 void visitUserOp1(Instruction &I) {
593 assert(0 && "UserOp1 should not exist at instruction selection time!");
594 abort();
595 }
596 void visitUserOp2(Instruction &I) {
597 assert(0 && "UserOp2 should not exist at instruction selection time!");
598 abort();
599 }
600};
601} // end namespace llvm
602
Chris Lattner8471b152006-03-16 19:57:50 +0000603SDOperand SelectionDAGLowering::getValue(const Value *V) {
604 SDOperand &N = NodeMap[V];
605 if (N.Val) return N;
606
607 const Type *VTy = V->getType();
608 MVT::ValueType VT = TLI.getValueType(VTy);
609 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
611 visit(CE->getOpcode(), *CE);
612 assert(N.Val && "visit didn't populate the ValueMap!");
613 return N;
614 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
615 return N = DAG.getGlobalAddress(GV, VT);
616 } else if (isa<ConstantPointerNull>(C)) {
617 return N = DAG.getConstant(0, TLI.getPointerTy());
618 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000619 if (!isa<PackedType>(VTy))
620 return N = DAG.getNode(ISD::UNDEF, VT);
621
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000622 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000623 const PackedType *PTy = cast<PackedType>(VTy);
624 unsigned NumElements = PTy->getNumElements();
625 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
626
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000627 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000628 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
629
630 // Create a VConstant node with generic Vector type.
631 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
632 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000633 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
634 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000635 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
636 return N = DAG.getConstantFP(CFP->getValue(), VT);
637 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
638 unsigned NumElements = PTy->getNumElements();
639 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000640
641 // Now that we know the number and type of the elements, push a
642 // Constant or ConstantFP node onto the ops list for each element of
643 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000644 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000645 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000646 for (unsigned i = 0; i != NumElements; ++i)
647 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000648 } else {
649 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
650 SDOperand Op;
651 if (MVT::isFloatingPoint(PVT))
652 Op = DAG.getConstantFP(0, PVT);
653 else
654 Op = DAG.getConstant(0, PVT);
655 Ops.assign(NumElements, Op);
656 }
657
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000658 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000659 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
660 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000661 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000662 } else {
663 // Canonicalize all constant ints to be unsigned.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000664 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000665 }
666 }
667
668 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
669 std::map<const AllocaInst*, int>::iterator SI =
670 FuncInfo.StaticAllocaMap.find(AI);
671 if (SI != FuncInfo.StaticAllocaMap.end())
672 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
673 }
674
675 std::map<const Value*, unsigned>::const_iterator VMI =
676 FuncInfo.ValueMap.find(V);
677 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
678
679 unsigned InReg = VMI->second;
680
681 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000682 if (VT != MVT::Vector) {
683 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000684
Chris Lattner5fe1f542006-03-31 02:06:56 +0000685 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
686 if (DestVT < VT) {
687 // Source must be expanded. This input value is actually coming from the
688 // register pair VMI->second and VMI->second+1.
689 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
690 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
691 } else if (DestVT > VT) { // Promotion case
Chris Lattner8471b152006-03-16 19:57:50 +0000692 if (MVT::isFloatingPoint(VT))
693 N = DAG.getNode(ISD::FP_ROUND, VT, N);
694 else
695 N = DAG.getNode(ISD::TRUNCATE, VT, N);
696 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000697 } else {
698 // Otherwise, if this is a vector, make it available as a generic vector
699 // here.
700 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000701 const PackedType *PTy = cast<PackedType>(VTy);
702 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000703 PTyLegalElementVT);
704
705 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000706 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000707 if (PTyElementVT == PTyLegalElementVT) {
708 // If the value types are legal, just VBUILD the CopyFromReg nodes.
709 for (unsigned i = 0; i != NE; ++i)
710 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
711 PTyElementVT));
712 } else if (PTyElementVT < PTyLegalElementVT) {
713 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
714 for (unsigned i = 0; i != NE; ++i) {
715 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
716 PTyElementVT);
717 if (MVT::isFloatingPoint(PTyElementVT))
718 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
719 else
720 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
721 Ops.push_back(Op);
722 }
723 } else {
724 // If the register was expanded, use BUILD_PAIR.
725 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
726 for (unsigned i = 0; i != NE/2; ++i) {
727 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
728 PTyElementVT);
729 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
730 PTyElementVT);
731 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
732 }
733 }
734
735 Ops.push_back(DAG.getConstant(NE, MVT::i32));
736 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000737 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000738
739 // Finally, use a VBIT_CONVERT to make this available as the appropriate
740 // vector type.
741 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
742 DAG.getConstant(PTy->getNumElements(),
743 MVT::i32),
744 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000745 }
746
747 return N;
748}
749
750
Chris Lattner7a60d912005-01-07 07:47:53 +0000751void SelectionDAGLowering::visitRet(ReturnInst &I) {
752 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000753 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000754 return;
755 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000756 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000757 NewValues.push_back(getRoot());
758 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
759 SDOperand RetOp = getValue(I.getOperand(i));
Evan Chenga2e99532006-05-26 23:09:09 +0000760 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000761
762 // If this is an integer return value, we need to promote it ourselves to
763 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
764 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000765 // FIXME: C calling convention requires the return type to be promoted to
766 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000767 if (MVT::isInteger(RetOp.getValueType()) &&
768 RetOp.getValueType() < MVT::i64) {
769 MVT::ValueType TmpVT;
770 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
771 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
772 else
773 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000774
Evan Chenga2e99532006-05-26 23:09:09 +0000775 if (isSigned)
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000776 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
777 else
778 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
779 }
780 NewValues.push_back(RetOp);
Evan Chenga2e99532006-05-26 23:09:09 +0000781 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000782 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000783 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
784 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000785}
786
Chris Lattnered0110b2006-10-27 21:36:01 +0000787/// ExportFromCurrentBlock - If this condition isn't known to be exported from
788/// the current basic block, add it to ValueMap now so that we'll get a
789/// CopyTo/FromReg.
790void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
791 // No need to export constants.
792 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
793
794 // Already exported?
795 if (FuncInfo.isExportedInst(V)) return;
796
797 unsigned Reg = FuncInfo.InitializeRegForValue(V);
798 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
799}
800
801/// FindMergedConditions - If Cond is an expression like
802void SelectionDAGLowering::FindMergedConditions(Value *Cond,
803 MachineBasicBlock *TBB,
804 MachineBasicBlock *FBB,
805 MachineBasicBlock *CurBB,
806 unsigned Opc) {
807 // FIXME: HANDLE AND.
808 // FIXME: HANDLE NOT
809
810 // If this node is not part of the or/and tree, emit it as a branch.
811 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
812
813 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
814 BOp->getParent() != CurBB->getBasicBlock()) {
815 const BasicBlock *BB = CurBB->getBasicBlock();
816
817 // If the leaf of the tree is a setcond inst, merge the condition into the
818 // caseblock.
819 if (BOp && isa<SetCondInst>(BOp) &&
820 // The operands of the setcc have to be in this block. We don't know
821 // how to export them from some other block.
822 (!isa<Instruction>(BOp->getOperand(0)) ||
823 cast<Instruction>(BOp->getOperand(0))->getParent() == BB ||
824 FuncInfo.isExportedInst(BOp->getOperand(0))) &&
825 (!isa<Instruction>(BOp->getOperand(1)) ||
826 cast<Instruction>(BOp->getOperand(1))->getParent() == BB ||
827 FuncInfo.isExportedInst(BOp->getOperand(1)))) {
828 ExportFromCurrentBlock(BOp->getOperand(0));
829 ExportFromCurrentBlock(BOp->getOperand(1));
830
831 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
832 switch (BOp->getOpcode()) {
833 default: assert(0 && "Unknown setcc opcode!");
834 case Instruction::SetEQ:
835 SignCond = ISD::SETEQ;
836 UnsCond = ISD::SETEQ;
837 FPCond = ISD::SETOEQ;
838 break;
839 case Instruction::SetNE:
840 SignCond = ISD::SETNE;
841 UnsCond = ISD::SETNE;
842 FPCond = ISD::SETUNE;
843 break;
844 case Instruction::SetLE:
845 SignCond = ISD::SETLE;
846 UnsCond = ISD::SETULE;
847 FPCond = ISD::SETOLE;
848 break;
849 case Instruction::SetGE:
850 SignCond = ISD::SETGE;
851 UnsCond = ISD::SETUGE;
852 FPCond = ISD::SETOGE;
853 break;
854 case Instruction::SetLT:
855 SignCond = ISD::SETLT;
856 UnsCond = ISD::SETULT;
857 FPCond = ISD::SETOLT;
858 break;
859 case Instruction::SetGT:
860 SignCond = ISD::SETGT;
861 UnsCond = ISD::SETUGT;
862 FPCond = ISD::SETOGT;
863 break;
864 }
865
866 const Type *OpType = BOp->getOperand(0)->getType();
867 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
868 OpType = PTy->getElementType();
869
870 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
871 Condition = FPCond;
872 else if (OpType->isUnsigned())
873 Condition = UnsCond;
874 else
875 Condition = SignCond;
876
877 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
878 BOp->getOperand(1), TBB, FBB, CurBB);
879 SwitchCases.push_back(CB);
880 return;
881 }
882
883 // Create a CaseBlock record representing this branch.
884 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
885 TBB, FBB, CurBB);
886 SwitchCases.push_back(CB);
887 ExportFromCurrentBlock(Cond);
888 return;
889 }
890
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000891
892 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000893 MachineFunction::iterator BBI = CurBB;
894 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
895 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
896
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000897 if (Opc == Instruction::Or) {
898 // Codegen X | Y as:
899 // jmp_if_X TBB
900 // jmp TmpBB
901 // TmpBB:
902 // jmp_if_Y TBB
903 // jmp FBB
904 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000905
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000906 // Emit the LHS condition.
907 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
908
909 // Emit the RHS condition into TmpBB.
910 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
911 } else {
912 assert(Opc == Instruction::And && "Unknown merge op!");
913 // Codegen X & Y as:
914 // jmp_if_X TmpBB
915 // jmp FBB
916 // TmpBB:
917 // jmp_if_Y TBB
918 // jmp FBB
919 //
920 // This requires creation of TmpBB after CurBB.
921
922 // Emit the LHS condition.
923 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
924
925 // Emit the RHS condition into TmpBB.
926 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
927 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000928}
929
Chris Lattner7a60d912005-01-07 07:47:53 +0000930void SelectionDAGLowering::visitBr(BranchInst &I) {
931 // Update machine-CFG edges.
932 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000933
934 // Figure out which block is immediately after the current one.
935 MachineBasicBlock *NextBlock = 0;
936 MachineFunction::iterator BBI = CurMBB;
937 if (++BBI != CurMBB->getParent()->end())
938 NextBlock = BBI;
939
940 if (I.isUnconditional()) {
941 // If this is not a fall-through branch, emit the branch.
942 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000943 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000944 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000945
Chris Lattner963ddad2006-10-24 17:57:59 +0000946 // Update machine-CFG edges.
947 CurMBB->addSuccessor(Succ0MBB);
948
949 return;
950 }
951
952 // If this condition is one of the special cases we handle, do special stuff
953 // now.
954 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +0000955 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +0000956
957 // If this is a series of conditions that are or'd or and'd together, emit
958 // this as a sequence of branches instead of setcc's with and/or operations.
959 // For example, instead of something like:
960 // cmp A, B
961 // C = seteq
962 // cmp D, E
963 // F = setle
964 // or C, F
965 // jnz foo
966 // Emit:
967 // cmp A, B
968 // je foo
969 // cmp D, E
970 // jle foo
971 //
972 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
973 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000974 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000975 BOp->getOpcode() == Instruction::Or)) {
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000976 if (BOp->getOpcode() == Instruction::And)
977 I.getParent()->dump();
Chris Lattnered0110b2006-10-27 21:36:01 +0000978 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnered0110b2006-10-27 21:36:01 +0000979 visitSwitchCase(SwitchCases[0]);
980 SwitchCases.erase(SwitchCases.begin());
981 return;
982 }
983 }
Chris Lattner61bcf912006-10-24 18:07:37 +0000984
985 // Create a CaseBlock record representing this branch.
Chris Lattnered0110b2006-10-27 21:36:01 +0000986 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +0000987 Succ0MBB, Succ1MBB, CurMBB);
988 // Use visitSwitchCase to actually insert the fast branch sequence for this
989 // cond branch.
990 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000991}
992
Nate Begemaned728c12006-03-27 01:32:24 +0000993/// visitSwitchCase - Emits the necessary code to represent a single node in
994/// the binary search tree resulting from lowering a switch instruction.
995void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +0000996 SDOperand Cond;
997 SDOperand CondLHS = getValue(CB.CmpLHS);
998
Chris Lattnered0110b2006-10-27 21:36:01 +0000999 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1000 // handle common cases produced by branch lowering.
1001 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001002 Cond = CondLHS;
Chris Lattnered0110b2006-10-27 21:36:01 +00001003 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1004 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1005 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1006 } else
1007 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemaned728c12006-03-27 01:32:24 +00001008
1009 // Set NextBlock to be the MBB immediately after the current one, if any.
1010 // This is used to avoid emitting unnecessary branches to the next block.
1011 MachineBasicBlock *NextBlock = 0;
1012 MachineFunction::iterator BBI = CurMBB;
1013 if (++BBI != CurMBB->getParent()->end())
1014 NextBlock = BBI;
1015
1016 // If the lhs block is the next block, invert the condition so that we can
1017 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001018 if (CB.TrueBB == NextBlock) {
1019 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001020 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1021 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1022 }
1023 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001024 DAG.getBasicBlock(CB.TrueBB));
1025 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001026 DAG.setRoot(BrCond);
1027 else
1028 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001029 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001030 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001031 CurMBB->addSuccessor(CB.TrueBB);
1032 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001033}
1034
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001035void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001036 // Emit the code for the jump table
1037 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng6ae6ac12006-08-01 01:03:13 +00001038 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
1039 "Jump table entries are 32-bit values");
Evan Cheng77c07572006-09-24 05:22:38 +00001040 bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
Evan Cheng6ae6ac12006-08-01 01:03:13 +00001041 // PIC jump table entries are 32-bit values.
Evan Cheng77c07572006-09-24 05:22:38 +00001042 unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001043 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1044 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
Evan Cheng6ae6ac12006-08-01 01:03:13 +00001045 DAG.getConstant(EntrySize, PTy));
Nate Begeman78756502006-07-27 01:13:04 +00001046 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
1047 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
Evan Cheng77c07572006-09-24 05:22:38 +00001048 SDOperand LD = DAG.getLoad(isPIC ? MVT::i32 : PTy, Copy.getValue(1), ADD,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001049 NULL, 0);
Evan Cheng77c07572006-09-24 05:22:38 +00001050 if (isPIC) {
Andrew Lenharthc19ef922006-09-26 20:02:30 +00001051 // For Pic, the sequence is:
1052 // BRIND(load(Jumptable + index) + RelocBase)
1053 // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
Andrew Lenhartha6bbf332006-10-11 04:29:42 +00001054 SDOperand Reloc;
1055 if (TLI.usesGlobalOffsetTable())
1056 Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
1057 else
1058 Reloc = TAB;
Chris Lattner4c3ef472006-10-22 22:47:10 +00001059 ADD = (PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD;
1060 ADD = DAG.getNode(ISD::ADD, PTy, ADD, Reloc);
Nate Begeman78756502006-07-27 01:13:04 +00001061 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
1062 } else {
1063 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
1064 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001065}
1066
Nate Begemaned728c12006-03-27 01:32:24 +00001067void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1068 // Figure out which block is immediately after the current one.
1069 MachineBasicBlock *NextBlock = 0;
1070 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001071
Nate Begemaned728c12006-03-27 01:32:24 +00001072 if (++BBI != CurMBB->getParent()->end())
1073 NextBlock = BBI;
1074
Chris Lattner6d6fc262006-10-22 21:36:53 +00001075 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1076
Nate Begemaned728c12006-03-27 01:32:24 +00001077 // If there is only the default destination, branch to it if it is not the
1078 // next basic block. Otherwise, just fall through.
1079 if (I.getNumOperands() == 2) {
1080 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001081
Nate Begemaned728c12006-03-27 01:32:24 +00001082 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001083 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001084 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001085 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001086
Chris Lattner6d6fc262006-10-22 21:36:53 +00001087 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001088 return;
1089 }
1090
1091 // If there are any non-default case statements, create a vector of Cases
1092 // representing each one, and sort the vector so that we can efficiently
1093 // create a binary search tree from them.
1094 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001095
Nate Begemaned728c12006-03-27 01:32:24 +00001096 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1097 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1098 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1099 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001100
Nate Begemaned728c12006-03-27 01:32:24 +00001101 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1102
1103 // Get the Value to be switched on and default basic blocks, which will be
1104 // inserted into CaseBlock records, representing basic blocks in the binary
1105 // search tree.
1106 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001107
1108 // Get the MachineFunction which holds the current MBB. This is used during
1109 // emission of jump tables, and when inserting any additional MBBs necessary
1110 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +00001111 MachineFunction *CurMF = CurMBB->getParent();
1112 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +00001113
1114 // If the switch has few cases (two or less) emit a series of specific
1115 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +00001116 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +00001117 // TODO: If any two of the cases has the same destination, and if one value
1118 // is the same as the other, but has one bit unset that the other has set,
1119 // use bit manipulation to do two compares at once. For example:
1120 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1121
Chris Lattner4c931502006-10-23 18:38:22 +00001122 // Rearrange the case blocks so that the last one falls through if possible.
1123 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1124 // The last case block won't fall through into 'NextBlock' if we emit the
1125 // branches in this order. See if rearranging a case value would help.
1126 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1127 if (Cases[i].second == NextBlock) {
1128 std::swap(Cases[i], Cases.back());
1129 break;
1130 }
1131 }
1132 }
1133
Chris Lattner6d6fc262006-10-22 21:36:53 +00001134 // Create a CaseBlock record representing a conditional branch to
1135 // the Case's target mbb if the value being switched on SV is equal
1136 // to C.
1137 MachineBasicBlock *CurBlock = CurMBB;
1138 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1139 MachineBasicBlock *FallThrough;
1140 if (i != e-1) {
1141 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1142 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1143 } else {
1144 // If the last case doesn't match, go to the default block.
1145 FallThrough = Default;
1146 }
1147
1148 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1149 Cases[i].second, FallThrough, CurBlock);
1150
1151 // If emitting the first comparison, just call visitSwitchCase to emit the
1152 // code into the current block. Otherwise, push the CaseBlock onto the
1153 // vector to be later processed by SDISel, and insert the node's MBB
1154 // before the next MBB.
1155 if (CurBlock == CurMBB)
1156 visitSwitchCase(CB);
1157 else
1158 SwitchCases.push_back(CB);
1159
1160 CurBlock = FallThrough;
1161 }
1162 return;
1163 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001164
Nate Begemand7a19102006-05-08 16:51:36 +00001165 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1166 // target supports indirect branches, then emit a jump table rather than
1167 // lowering the switch to a binary tree of conditional branches.
Nate Begeman866b4b42006-04-23 06:26:20 +00001168 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
Nate Begemandf488392006-05-03 03:48:02 +00001169 Cases.size() > 5) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001170 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1171 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemandf488392006-05-03 03:48:02 +00001172 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1173
Nate Begemand7a19102006-05-08 16:51:36 +00001174 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001175 // Create a new basic block to hold the code for loading the address
1176 // of the jump table, and jumping to it. Update successor information;
1177 // we will either branch to the default case for the switch, or the jump
1178 // table.
1179 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1180 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1181 CurMBB->addSuccessor(Default);
1182 CurMBB->addSuccessor(JumpTableBB);
1183
1184 // Subtract the lowest switch case value from the value being switched on
1185 // and conditional branch to default mbb if the result is greater than the
1186 // difference between smallest and largest cases.
1187 SDOperand SwitchOp = getValue(SV);
1188 MVT::ValueType VT = SwitchOp.getValueType();
1189 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1190 DAG.getConstant(First, VT));
1191
1192 // The SDNode we just created, which holds the value being switched on
1193 // minus the the smallest case value, needs to be copied to a virtual
1194 // register so it can be used as an index into the jump table in a
1195 // subsequent basic block. This value may be smaller or larger than the
1196 // target's pointer type, and therefore require extension or truncating.
1197 if (VT > TLI.getPointerTy())
1198 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1199 else
1200 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001201
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001202 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1203 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1204
1205 // Emit the range check for the jump table, and branch to the default
1206 // block for the switch statement if the value being switched on exceeds
1207 // the largest case in the switch.
1208 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1209 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1210 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1211 DAG.getBasicBlock(Default)));
1212
Nate Begemandf488392006-05-03 03:48:02 +00001213 // Build a vector of destination BBs, corresponding to each target
1214 // of the jump table. If the value of the jump table slot corresponds to
1215 // a case statement, push the case's BB onto the vector, otherwise, push
1216 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001217 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +00001218 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001219 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001220 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001221 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001222 ++ii;
1223 } else {
1224 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001225 }
Nate Begemandf488392006-05-03 03:48:02 +00001226
1227 // Update successor info
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001228 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1229 E = DestBBs.end(); I != E; ++I)
1230 JumpTableBB->addSuccessor(*I);
Nate Begemandf488392006-05-03 03:48:02 +00001231
1232 // Create a jump table index for this jump table, or return an existing
1233 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001234 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1235
1236 // Set the jump table information so that we can codegen it as a second
1237 // MachineBasicBlock
1238 JT.Reg = JumpTableReg;
1239 JT.JTI = JTI;
1240 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001241 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001242 return;
1243 }
1244 }
Nate Begemaned728c12006-03-27 01:32:24 +00001245
1246 // Push the initial CaseRec onto the worklist
1247 std::vector<CaseRec> CaseVec;
1248 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1249
1250 while (!CaseVec.empty()) {
1251 // Grab a record representing a case range to process off the worklist
1252 CaseRec CR = CaseVec.back();
1253 CaseVec.pop_back();
1254
1255 // Size is the number of Cases represented by this range. If Size is 1,
1256 // then we are processing a leaf of the binary search tree. Otherwise,
1257 // we need to pick a pivot, and push left and right ranges onto the
1258 // worklist.
1259 unsigned Size = CR.Range.second - CR.Range.first;
1260
1261 if (Size == 1) {
1262 // Create a CaseBlock record representing a conditional branch to
1263 // the Case's target mbb if the value being switched on SV is equal
1264 // to C. Otherwise, branch to default.
1265 Constant *C = CR.Range.first->first;
1266 MachineBasicBlock *Target = CR.Range.first->second;
1267 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1268 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001269
Nate Begemaned728c12006-03-27 01:32:24 +00001270 // If the MBB representing the leaf node is the current MBB, then just
1271 // call visitSwitchCase to emit the code into the current block.
1272 // Otherwise, push the CaseBlock onto the vector to be later processed
1273 // by SDISel, and insert the node's MBB before the next MBB.
1274 if (CR.CaseBB == CurMBB)
1275 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001276 else
Nate Begemaned728c12006-03-27 01:32:24 +00001277 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001278 } else {
1279 // split case range at pivot
1280 CaseItr Pivot = CR.Range.first + (Size / 2);
1281 CaseRange LHSR(CR.Range.first, Pivot);
1282 CaseRange RHSR(Pivot, CR.Range.second);
1283 Constant *C = Pivot->first;
Chris Lattner963ddad2006-10-24 17:57:59 +00001284 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001285
Nate Begemaned728c12006-03-27 01:32:24 +00001286 // We know that we branch to the LHS if the Value being switched on is
1287 // less than the Pivot value, C. We use this to optimize our binary
1288 // tree a bit, by recognizing that if SV is greater than or equal to the
1289 // LHS's Case Value, and that Case Value is exactly one less than the
1290 // Pivot's Value, then we can branch directly to the LHS's Target,
1291 // rather than creating a leaf node for it.
1292 if ((LHSR.second - LHSR.first) == 1 &&
1293 LHSR.first->first == CR.GE &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001294 cast<ConstantIntegral>(C)->getZExtValue() ==
1295 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001296 TrueBB = LHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001297 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001298 TrueBB = new MachineBasicBlock(LLVMBB);
1299 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1300 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001301 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001302
Nate Begemaned728c12006-03-27 01:32:24 +00001303 // Similar to the optimization above, if the Value being switched on is
1304 // known to be less than the Constant CR.LT, and the current Case Value
1305 // is CR.LT - 1, then we can branch directly to the target block for
1306 // the current Case Value, rather than emitting a RHS leaf node for it.
1307 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001308 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1309 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001310 FalseBB = RHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001311 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001312 FalseBB = new MachineBasicBlock(LLVMBB);
1313 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1314 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001315 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001316
Nate Begemaned728c12006-03-27 01:32:24 +00001317 // Create a CaseBlock record representing a conditional branch to
1318 // the LHS node if the value being switched on SV is less than C.
1319 // Otherwise, branch to LHS.
1320 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner963ddad2006-10-24 17:57:59 +00001321 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001322
Nate Begemaned728c12006-03-27 01:32:24 +00001323 if (CR.CaseBB == CurMBB)
1324 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001325 else
Nate Begemaned728c12006-03-27 01:32:24 +00001326 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001327 }
1328 }
1329}
1330
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001331void SelectionDAGLowering::visitSub(User &I) {
1332 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001333 if (I.getType()->isFloatingPoint()) {
1334 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1335 if (CFP->isExactlyValue(-0.0)) {
1336 SDOperand Op2 = getValue(I.getOperand(1));
1337 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1338 return;
1339 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001340 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1341 } else
1342 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001343}
1344
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001345void
1346SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001347 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001348 SDOperand Op1 = getValue(I.getOperand(0));
1349 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001350
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001351 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattner32206f52006-03-18 01:44:44 +00001352 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1353 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1354 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001355 } else {
1356 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1357 }
1358}
1359
1360void
1361SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1362 const Type *Ty = I.getType();
1363 SDOperand Op1 = getValue(I.getOperand(0));
1364 SDOperand Op2 = getValue(I.getOperand(1));
1365
1366 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1367 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1368 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1369 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1370 } else {
1371 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001372 }
Nate Begeman127321b2005-11-18 07:42:56 +00001373}
Chris Lattner96c26752005-01-19 22:31:21 +00001374
Nate Begeman127321b2005-11-18 07:42:56 +00001375void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1376 SDOperand Op1 = getValue(I.getOperand(0));
1377 SDOperand Op2 = getValue(I.getOperand(1));
1378
1379 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1380
Chris Lattner7a60d912005-01-07 07:47:53 +00001381 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1382}
1383
1384void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001385 ISD::CondCode UnsignedOpcode,
1386 ISD::CondCode FPOpcode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001387 SDOperand Op1 = getValue(I.getOperand(0));
1388 SDOperand Op2 = getValue(I.getOperand(1));
1389 ISD::CondCode Opcode = SignedOpcode;
Evan Chengac4f66f2006-05-23 18:18:46 +00001390 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001391 Opcode = FPOpcode;
1392 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner7a60d912005-01-07 07:47:53 +00001393 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +00001394 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +00001395}
1396
1397void SelectionDAGLowering::visitSelect(User &I) {
1398 SDOperand Cond = getValue(I.getOperand(0));
1399 SDOperand TrueVal = getValue(I.getOperand(1));
1400 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001401 if (!isa<PackedType>(I.getType())) {
1402 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1403 TrueVal, FalseVal));
1404 } else {
1405 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1406 *(TrueVal.Val->op_end()-2),
1407 *(TrueVal.Val->op_end()-1)));
1408 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001409}
1410
1411void SelectionDAGLowering::visitCast(User &I) {
1412 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001413 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001414 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001415
Chris Lattner2f4119a2006-03-22 20:09:35 +00001416 if (DestVT == MVT::Vector) {
1417 // This is a cast to a vector from something else. This is always a bit
1418 // convert. Get information about the input vector.
1419 const PackedType *DestTy = cast<PackedType>(I.getType());
1420 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1421 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1422 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1423 DAG.getValueType(EltVT)));
1424 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001425 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001426 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001427 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001428 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001429 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001430 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001431 } else if (isInteger(SrcVT)) {
1432 if (isInteger(DestVT)) { // Int -> Int cast
1433 if (DestVT < SrcVT) // Truncating cast?
1434 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001435 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001436 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001437 else
Chris Lattner4024c002006-03-15 22:19:46 +00001438 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001439 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001440 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001441 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001442 else
Chris Lattner4024c002006-03-15 22:19:46 +00001443 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001444 } else {
1445 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001446 }
Chris Lattner4024c002006-03-15 22:19:46 +00001447 } else if (isFloatingPoint(SrcVT)) {
1448 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1449 if (DestVT < SrcVT) // Rounding cast?
1450 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001451 else
Chris Lattner4024c002006-03-15 22:19:46 +00001452 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001453 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001454 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001455 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001456 else
Chris Lattner4024c002006-03-15 22:19:46 +00001457 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001458 } else {
1459 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001460 }
1461 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001462 assert(SrcVT == MVT::Vector && "Unknown cast!");
1463 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1464 // This is a cast from a vector to something else. This is always a bit
1465 // convert. Get information about the input vector.
1466 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001467 }
1468}
1469
Chris Lattner67271862006-03-29 00:11:43 +00001470void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001471 SDOperand InVec = getValue(I.getOperand(0));
1472 SDOperand InVal = getValue(I.getOperand(1));
1473 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1474 getValue(I.getOperand(2)));
1475
Chris Lattner29b23012006-03-19 01:17:20 +00001476 SDOperand Num = *(InVec.Val->op_end()-2);
1477 SDOperand Typ = *(InVec.Val->op_end()-1);
1478 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1479 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001480}
1481
Chris Lattner67271862006-03-29 00:11:43 +00001482void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001483 SDOperand InVec = getValue(I.getOperand(0));
1484 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1485 getValue(I.getOperand(1)));
1486 SDOperand Typ = *(InVec.Val->op_end()-1);
1487 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1488 TLI.getValueType(I.getType()), InVec, InIdx));
1489}
Chris Lattner32206f52006-03-18 01:44:44 +00001490
Chris Lattner098c01e2006-04-08 04:15:24 +00001491void SelectionDAGLowering::visitShuffleVector(User &I) {
1492 SDOperand V1 = getValue(I.getOperand(0));
1493 SDOperand V2 = getValue(I.getOperand(1));
1494 SDOperand Mask = getValue(I.getOperand(2));
1495
1496 SDOperand Num = *(V1.Val->op_end()-2);
1497 SDOperand Typ = *(V2.Val->op_end()-1);
1498 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1499 V1, V2, Mask, Num, Typ));
1500}
1501
1502
Chris Lattner7a60d912005-01-07 07:47:53 +00001503void SelectionDAGLowering::visitGetElementPtr(User &I) {
1504 SDOperand N = getValue(I.getOperand(0));
1505 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001506
1507 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1508 OI != E; ++OI) {
1509 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001510 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001511 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001512 if (Field) {
1513 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001514 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001515 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001516 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001517 }
1518 Ty = StTy->getElementType(Field);
1519 } else {
1520 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001521
Chris Lattner43535a12005-11-09 04:45:33 +00001522 // If this is a constant subscript, handle it quickly.
1523 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001524 if (CI->getZExtValue() == 0) continue;
Chris Lattner43535a12005-11-09 04:45:33 +00001525 uint64_t Offs;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001526 if (CI->getType()->isSigned())
1527 Offs = (int64_t)
1528 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001529 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00001530 Offs =
1531 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001532 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1533 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001534 }
Chris Lattner43535a12005-11-09 04:45:33 +00001535
1536 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001537 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001538 SDOperand IdxN = getValue(Idx);
1539
1540 // If the index is smaller or larger than intptr_t, truncate or extend
1541 // it.
1542 if (IdxN.getValueType() < N.getValueType()) {
1543 if (Idx->getType()->isSigned())
1544 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1545 else
1546 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1547 } else if (IdxN.getValueType() > N.getValueType())
1548 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1549
1550 // If this is a multiply by a power of two, turn it into a shl
1551 // immediately. This is a very common case.
1552 if (isPowerOf2_64(ElementSize)) {
1553 unsigned Amt = Log2_64(ElementSize);
1554 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001555 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001556 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1557 continue;
1558 }
1559
1560 SDOperand Scale = getIntPtrConstant(ElementSize);
1561 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1562 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001563 }
1564 }
1565 setValue(&I, N);
1566}
1567
1568void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1569 // If this is a fixed sized alloca in the entry block of the function,
1570 // allocate it statically on the stack.
1571 if (FuncInfo.StaticAllocaMap.count(&I))
1572 return; // getValue will auto-populate this.
1573
1574 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001575 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1576 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001577 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001578
1579 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001580 MVT::ValueType IntPtr = TLI.getPointerTy();
1581 if (IntPtr < AllocSize.getValueType())
1582 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1583 else if (IntPtr > AllocSize.getValueType())
1584 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001585
Chris Lattnereccb73d2005-01-22 23:04:37 +00001586 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001587 getIntPtrConstant(TySize));
1588
1589 // Handle alignment. If the requested alignment is less than or equal to the
1590 // stack alignment, ignore it and round the size of the allocation up to the
1591 // stack alignment size. If the size is greater than the stack alignment, we
1592 // note this in the DYNAMIC_STACKALLOC node.
1593 unsigned StackAlign =
1594 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1595 if (Align <= StackAlign) {
1596 Align = 0;
1597 // Add SA-1 to the size.
1598 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1599 getIntPtrConstant(StackAlign-1));
1600 // Mask out the low bits for alignment purposes.
1601 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1602 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1603 }
1604
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001605 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001606 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1607 MVT::Other);
1608 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001609 DAG.setRoot(setValue(&I, DSA).getValue(1));
1610
1611 // Inform the Frame Information that we have just allocated a variable-sized
1612 // object.
1613 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1614}
1615
Chris Lattner7a60d912005-01-07 07:47:53 +00001616void SelectionDAGLowering::visitLoad(LoadInst &I) {
1617 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001618
Chris Lattner4d9651c2005-01-17 22:19:26 +00001619 SDOperand Root;
1620 if (I.isVolatile())
1621 Root = getRoot();
1622 else {
1623 // Do not serialize non-volatile loads against each other.
1624 Root = DAG.getRoot();
1625 }
Chris Lattner4024c002006-03-15 22:19:46 +00001626
Evan Chenge71fe34d2006-10-09 20:57:25 +00001627 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001628 Root, I.isVolatile()));
1629}
1630
1631SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001632 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001633 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001634 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001635 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001636 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001637 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1638 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001639 } else {
Evan Chenge71fe34d2006-10-09 20:57:25 +00001640 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001641 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001642
Chris Lattner4024c002006-03-15 22:19:46 +00001643 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001644 DAG.setRoot(L.getValue(1));
1645 else
1646 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001647
1648 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001649}
1650
1651
1652void SelectionDAGLowering::visitStore(StoreInst &I) {
1653 Value *SrcV = I.getOperand(0);
1654 SDOperand Src = getValue(SrcV);
1655 SDOperand Ptr = getValue(I.getOperand(1));
Evan Chengab51cf22006-10-13 21:14:26 +00001656 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1657 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001658}
1659
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001660/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1661/// access memory and has no other side effects at all.
1662static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1663#define GET_NO_MEMORY_INTRINSICS
1664#include "llvm/Intrinsics.gen"
1665#undef GET_NO_MEMORY_INTRINSICS
1666 return false;
1667}
1668
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001669// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1670// have any side-effects or if it only reads memory.
1671static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1672#define GET_SIDE_EFFECT_INFO
1673#include "llvm/Intrinsics.gen"
1674#undef GET_SIDE_EFFECT_INFO
1675 return false;
1676}
1677
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001678/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1679/// node.
1680void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1681 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001682 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001683 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001684
1685 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001686 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001687 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1688 if (OnlyLoad) {
1689 // We don't need to serialize loads against other loads.
1690 Ops.push_back(DAG.getRoot());
1691 } else {
1692 Ops.push_back(getRoot());
1693 }
1694 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001695
1696 // Add the intrinsic ID as an integer operand.
1697 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1698
1699 // Add all operands of the call to the operand list.
1700 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1701 SDOperand Op = getValue(I.getOperand(i));
1702
1703 // If this is a vector type, force it to the right packed type.
1704 if (Op.getValueType() == MVT::Vector) {
1705 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1706 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1707
1708 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1709 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1710 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1711 }
1712
1713 assert(TLI.isTypeLegal(Op.getValueType()) &&
1714 "Intrinsic uses a non-legal type?");
1715 Ops.push_back(Op);
1716 }
1717
1718 std::vector<MVT::ValueType> VTs;
1719 if (I.getType() != Type::VoidTy) {
1720 MVT::ValueType VT = TLI.getValueType(I.getType());
1721 if (VT == MVT::Vector) {
1722 const PackedType *DestTy = cast<PackedType>(I.getType());
1723 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1724
1725 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1726 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1727 }
1728
1729 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1730 VTs.push_back(VT);
1731 }
1732 if (HasChain)
1733 VTs.push_back(MVT::Other);
1734
Chris Lattnerbd887772006-08-14 23:53:35 +00001735 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1736
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001737 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001738 SDOperand Result;
1739 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001740 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1741 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001742 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001743 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1744 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001745 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001746 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1747 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001748
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001749 if (HasChain) {
1750 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1751 if (OnlyLoad)
1752 PendingLoads.push_back(Chain);
1753 else
1754 DAG.setRoot(Chain);
1755 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001756 if (I.getType() != Type::VoidTy) {
1757 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1758 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1759 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1760 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1761 DAG.getValueType(EVT));
1762 }
1763 setValue(&I, Result);
1764 }
1765}
1766
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001767/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1768/// we want to emit this as a call to a named external function, return the name
1769/// otherwise lower it and return null.
1770const char *
1771SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1772 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001773 default:
1774 // By default, turn this into a target intrinsic node.
1775 visitTargetIntrinsic(I, Intrinsic);
1776 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001777 case Intrinsic::vastart: visitVAStart(I); return 0;
1778 case Intrinsic::vaend: visitVAEnd(I); return 0;
1779 case Intrinsic::vacopy: visitVACopy(I); return 0;
1780 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1781 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1782 case Intrinsic::setjmp:
1783 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1784 break;
1785 case Intrinsic::longjmp:
1786 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1787 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001788 case Intrinsic::memcpy_i32:
1789 case Intrinsic::memcpy_i64:
1790 visitMemIntrinsic(I, ISD::MEMCPY);
1791 return 0;
1792 case Intrinsic::memset_i32:
1793 case Intrinsic::memset_i64:
1794 visitMemIntrinsic(I, ISD::MEMSET);
1795 return 0;
1796 case Intrinsic::memmove_i32:
1797 case Intrinsic::memmove_i64:
1798 visitMemIntrinsic(I, ISD::MEMMOVE);
1799 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001800
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001801 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001802 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001803 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001804 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001805 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001806
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001807 Ops[0] = getRoot();
1808 Ops[1] = getValue(SPI.getLineValue());
1809 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001810
Jim Laskeya8bdac82006-03-23 18:06:46 +00001811 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001812 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001813 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1814
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001815 Ops[3] = DAG.getString(CompileUnit->getFileName());
1816 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00001817
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001818 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001819 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001820
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001821 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001822 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001823 case Intrinsic::dbg_region_start: {
1824 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1825 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001826 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001827 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001828 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1829 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001830 }
1831
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001832 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001833 }
1834 case Intrinsic::dbg_region_end: {
1835 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1836 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001837 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001838 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001839 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1840 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001841 }
1842
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001843 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001844 }
1845 case Intrinsic::dbg_func_start: {
1846 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1847 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001848 if (DebugInfo && FSI.getSubprogram() &&
1849 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001850 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001851 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1852 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001853 }
1854
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001855 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001856 }
1857 case Intrinsic::dbg_declare: {
1858 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1859 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001860 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001861 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001862 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00001863 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001864 }
1865
1866 return 0;
1867 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001868
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001869 case Intrinsic::isunordered_f32:
1870 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001871 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1872 getValue(I.getOperand(2)), ISD::SETUO));
1873 return 0;
1874
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001875 case Intrinsic::sqrt_f32:
1876 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001877 setValue(&I, DAG.getNode(ISD::FSQRT,
1878 getValue(I.getOperand(1)).getValueType(),
1879 getValue(I.getOperand(1))));
1880 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00001881 case Intrinsic::powi_f32:
1882 case Intrinsic::powi_f64:
1883 setValue(&I, DAG.getNode(ISD::FPOWI,
1884 getValue(I.getOperand(1)).getValueType(),
1885 getValue(I.getOperand(1)),
1886 getValue(I.getOperand(2))));
1887 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001888 case Intrinsic::pcmarker: {
1889 SDOperand Tmp = getValue(I.getOperand(1));
1890 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1891 return 0;
1892 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001893 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001894 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001895 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1896 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1897 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001898 setValue(&I, Tmp);
1899 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001900 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001901 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001902 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001903 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001904 case Intrinsic::bswap_i64:
1905 setValue(&I, DAG.getNode(ISD::BSWAP,
1906 getValue(I.getOperand(1)).getValueType(),
1907 getValue(I.getOperand(1))));
1908 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001909 case Intrinsic::cttz_i8:
1910 case Intrinsic::cttz_i16:
1911 case Intrinsic::cttz_i32:
1912 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001913 setValue(&I, DAG.getNode(ISD::CTTZ,
1914 getValue(I.getOperand(1)).getValueType(),
1915 getValue(I.getOperand(1))));
1916 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001917 case Intrinsic::ctlz_i8:
1918 case Intrinsic::ctlz_i16:
1919 case Intrinsic::ctlz_i32:
1920 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001921 setValue(&I, DAG.getNode(ISD::CTLZ,
1922 getValue(I.getOperand(1)).getValueType(),
1923 getValue(I.getOperand(1))));
1924 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001925 case Intrinsic::ctpop_i8:
1926 case Intrinsic::ctpop_i16:
1927 case Intrinsic::ctpop_i32:
1928 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001929 setValue(&I, DAG.getNode(ISD::CTPOP,
1930 getValue(I.getOperand(1)).getValueType(),
1931 getValue(I.getOperand(1))));
1932 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001933 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001934 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001935 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1936 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00001937 setValue(&I, Tmp);
1938 DAG.setRoot(Tmp.getValue(1));
1939 return 0;
1940 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001941 case Intrinsic::stackrestore: {
1942 SDOperand Tmp = getValue(I.getOperand(1));
1943 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001944 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001945 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001946 case Intrinsic::prefetch:
1947 // FIXME: Currently discarding prefetches.
1948 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001949 }
1950}
1951
1952
Chris Lattner7a60d912005-01-07 07:47:53 +00001953void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001954 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001955 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001956 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001957 if (unsigned IID = F->getIntrinsicID()) {
1958 RenameFn = visitIntrinsicCall(I, IID);
1959 if (!RenameFn)
1960 return;
1961 } else { // Not an LLVM intrinsic.
1962 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001963 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1964 if (I.getNumOperands() == 3 && // Basic sanity checks.
1965 I.getOperand(1)->getType()->isFloatingPoint() &&
1966 I.getType() == I.getOperand(1)->getType() &&
1967 I.getType() == I.getOperand(2)->getType()) {
1968 SDOperand LHS = getValue(I.getOperand(1));
1969 SDOperand RHS = getValue(I.getOperand(2));
1970 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1971 LHS, RHS));
1972 return;
1973 }
1974 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001975 if (I.getNumOperands() == 2 && // Basic sanity checks.
1976 I.getOperand(1)->getType()->isFloatingPoint() &&
1977 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001978 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001979 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1980 return;
1981 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001982 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001983 if (I.getNumOperands() == 2 && // Basic sanity checks.
1984 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001985 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001986 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001987 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1988 return;
1989 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001990 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001991 if (I.getNumOperands() == 2 && // Basic sanity checks.
1992 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001993 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001994 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001995 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1996 return;
1997 }
1998 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001999 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002000 } else if (isa<InlineAsm>(I.getOperand(0))) {
2001 visitInlineAsm(I);
2002 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002003 }
Misha Brukman835702a2005-04-21 22:36:52 +00002004
Chris Lattner18d2b342005-01-08 22:48:57 +00002005 SDOperand Callee;
2006 if (!RenameFn)
2007 Callee = getValue(I.getOperand(0));
2008 else
2009 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00002010 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002011 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00002012 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2013 Value *Arg = I.getOperand(i);
2014 SDOperand ArgNode = getValue(Arg);
2015 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2016 }
Misha Brukman835702a2005-04-21 22:36:52 +00002017
Nate Begemanf6565252005-03-26 01:29:23 +00002018 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2019 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00002020
Chris Lattner1f45cd72005-01-08 19:26:18 +00002021 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00002022 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00002023 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00002024 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00002025 setValue(&I, Result.first);
2026 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002027}
2028
Chris Lattner6f87d182006-02-22 22:37:12 +00002029SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002030 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002031 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2032 Chain = Val.getValue(1);
2033 Flag = Val.getValue(2);
2034
2035 // If the result was expanded, copy from the top part.
2036 if (Regs.size() > 1) {
2037 assert(Regs.size() == 2 &&
2038 "Cannot expand to more than 2 elts yet!");
2039 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002040 Chain = Hi.getValue(1);
2041 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002042 if (DAG.getTargetLoweringInfo().isLittleEndian())
2043 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2044 else
2045 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002046 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002047
Chris Lattner705948d2006-06-08 18:22:48 +00002048 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002049 // appropriate type.
2050 if (RegVT == ValueVT)
2051 return Val;
2052
Chris Lattner705948d2006-06-08 18:22:48 +00002053 if (MVT::isInteger(RegVT)) {
2054 if (ValueVT < RegVT)
2055 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2056 else
2057 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2058 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00002059 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002060 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002061}
2062
Chris Lattner571d9642006-02-23 19:21:04 +00002063/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2064/// specified value into the registers specified by this object. This uses
2065/// Chain/Flag as the input and updates them for the output Chain/Flag.
2066void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002067 SDOperand &Chain, SDOperand &Flag,
2068 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002069 if (Regs.size() == 1) {
2070 // If there is a single register and the types differ, this must be
2071 // a promotion.
2072 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002073 if (MVT::isInteger(RegVT)) {
2074 if (RegVT < ValueVT)
2075 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2076 else
2077 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2078 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002079 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2080 }
2081 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2082 Flag = Chain.getValue(1);
2083 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002084 std::vector<unsigned> R(Regs);
2085 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2086 std::reverse(R.begin(), R.end());
2087
2088 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002089 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002090 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002091 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002092 Flag = Chain.getValue(1);
2093 }
2094 }
2095}
Chris Lattner6f87d182006-02-22 22:37:12 +00002096
Chris Lattner571d9642006-02-23 19:21:04 +00002097/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2098/// operand list. This adds the code marker and includes the number of
2099/// values added into it.
2100void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002101 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002102 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2103 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2104 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2105}
Chris Lattner6f87d182006-02-22 22:37:12 +00002106
2107/// isAllocatableRegister - If the specified register is safe to allocate,
2108/// i.e. it isn't a stack pointer or some other special register, return the
2109/// register class for the register. Otherwise, return null.
2110static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002111isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2112 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002113 MVT::ValueType FoundVT = MVT::Other;
2114 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002115 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2116 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002117 MVT::ValueType ThisVT = MVT::Other;
2118
Chris Lattnerb1124f32006-02-22 23:09:03 +00002119 const TargetRegisterClass *RC = *RCI;
2120 // If none of the the value types for this register class are valid, we
2121 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002122 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2123 I != E; ++I) {
2124 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002125 // If we have already found this register in a different register class,
2126 // choose the one with the largest VT specified. For example, on
2127 // PowerPC, we favor f64 register classes over f32.
2128 if (FoundVT == MVT::Other ||
2129 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2130 ThisVT = *I;
2131 break;
2132 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002133 }
2134 }
2135
Chris Lattnerbec582f2006-04-02 00:24:45 +00002136 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002137
Chris Lattner6f87d182006-02-22 22:37:12 +00002138 // NOTE: This isn't ideal. In particular, this might allocate the
2139 // frame pointer in functions that need it (due to them not being taken
2140 // out of allocation, because a variable sized allocation hasn't been seen
2141 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002142 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2143 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002144 if (*I == Reg) {
2145 // We found a matching register class. Keep looking at others in case
2146 // we find one with larger registers that this physreg is also in.
2147 FoundRC = RC;
2148 FoundVT = ThisVT;
2149 break;
2150 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002151 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002152 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002153}
2154
2155RegsForValue SelectionDAGLowering::
2156GetRegistersForValue(const std::string &ConstrCode,
2157 MVT::ValueType VT, bool isOutReg, bool isInReg,
2158 std::set<unsigned> &OutputRegs,
2159 std::set<unsigned> &InputRegs) {
2160 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2161 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2162 std::vector<unsigned> Regs;
2163
2164 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2165 MVT::ValueType RegVT;
2166 MVT::ValueType ValueVT = VT;
2167
2168 if (PhysReg.first) {
2169 if (VT == MVT::Other)
2170 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002171
2172 // Get the actual register value type. This is important, because the user
2173 // may have asked for (e.g.) the AX register in i32 type. We need to
2174 // remember that AX is actually i16 to get the right extension.
2175 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002176
2177 // This is a explicit reference to a physical register.
2178 Regs.push_back(PhysReg.first);
2179
2180 // If this is an expanded reference, add the rest of the regs to Regs.
2181 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002182 TargetRegisterClass::iterator I = PhysReg.second->begin();
2183 TargetRegisterClass::iterator E = PhysReg.second->end();
2184 for (; *I != PhysReg.first; ++I)
2185 assert(I != E && "Didn't find reg!");
2186
2187 // Already added the first reg.
2188 --NumRegs; ++I;
2189 for (; NumRegs; --NumRegs, ++I) {
2190 assert(I != E && "Ran out of registers to allocate!");
2191 Regs.push_back(*I);
2192 }
2193 }
2194 return RegsForValue(Regs, RegVT, ValueVT);
2195 }
2196
2197 // This is a reference to a register class. Allocate NumRegs consecutive,
2198 // available, registers from the class.
2199 std::vector<unsigned> RegClassRegs =
2200 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2201
2202 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2203 MachineFunction &MF = *CurMBB->getParent();
2204 unsigned NumAllocated = 0;
2205 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2206 unsigned Reg = RegClassRegs[i];
2207 // See if this register is available.
2208 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2209 (isInReg && InputRegs.count(Reg))) { // Already used.
2210 // Make sure we find consecutive registers.
2211 NumAllocated = 0;
2212 continue;
2213 }
2214
2215 // Check to see if this register is allocatable (i.e. don't give out the
2216 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002217 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002218 if (!RC) {
2219 // Make sure we find consecutive registers.
2220 NumAllocated = 0;
2221 continue;
2222 }
2223
2224 // Okay, this register is good, we can use it.
2225 ++NumAllocated;
2226
2227 // If we allocated enough consecutive
2228 if (NumAllocated == NumRegs) {
2229 unsigned RegStart = (i-NumAllocated)+1;
2230 unsigned RegEnd = i+1;
2231 // Mark all of the allocated registers used.
2232 for (unsigned i = RegStart; i != RegEnd; ++i) {
2233 unsigned Reg = RegClassRegs[i];
2234 Regs.push_back(Reg);
2235 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2236 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2237 }
2238
2239 return RegsForValue(Regs, *RC->vt_begin(), VT);
2240 }
2241 }
2242
2243 // Otherwise, we couldn't allocate enough registers for this.
2244 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002245}
2246
Chris Lattner6f87d182006-02-22 22:37:12 +00002247
Chris Lattner476e67b2006-01-26 22:24:51 +00002248/// visitInlineAsm - Handle a call to an InlineAsm object.
2249///
2250void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2251 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2252
2253 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2254 MVT::Other);
2255
2256 // Note, we treat inline asms both with and without side-effects as the same.
2257 // If an inline asm doesn't have side effects and doesn't access memory, we
2258 // could not choose to not chain it.
2259 bool hasSideEffects = IA->hasSideEffects();
2260
Chris Lattner3a5ed552006-02-01 01:28:23 +00002261 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002262 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002263
2264 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2265 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2266 /// if it is a def of that register.
2267 std::vector<SDOperand> AsmNodeOperands;
2268 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2269 AsmNodeOperands.push_back(AsmStr);
2270
2271 SDOperand Chain = getRoot();
2272 SDOperand Flag;
2273
Chris Lattner1558fc62006-02-01 18:59:47 +00002274 // We fully assign registers here at isel time. This is not optimal, but
2275 // should work. For register classes that correspond to LLVM classes, we
2276 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2277 // over the constraints, collecting fixed registers that we know we can't use.
2278 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002279 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002280 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2281 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2282 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002283
Chris Lattner7ad77df2006-02-22 00:56:39 +00002284 MVT::ValueType OpVT;
2285
2286 // Compute the value type for each operand and add it to ConstraintVTs.
2287 switch (Constraints[i].Type) {
2288 case InlineAsm::isOutput:
2289 if (!Constraints[i].isIndirectOutput) {
2290 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2291 OpVT = TLI.getValueType(I.getType());
2292 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002293 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002294 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2295 OpNum++; // Consumes a call operand.
2296 }
2297 break;
2298 case InlineAsm::isInput:
2299 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2300 OpNum++; // Consumes a call operand.
2301 break;
2302 case InlineAsm::isClobber:
2303 OpVT = MVT::Other;
2304 break;
2305 }
2306
2307 ConstraintVTs.push_back(OpVT);
2308
Chris Lattner6f87d182006-02-22 22:37:12 +00002309 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2310 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002311
Chris Lattner6f87d182006-02-22 22:37:12 +00002312 // Build a list of regs that this operand uses. This always has a single
2313 // element for promoted/expanded operands.
2314 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2315 false, false,
2316 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002317
2318 switch (Constraints[i].Type) {
2319 case InlineAsm::isOutput:
2320 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002321 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002322 // If this is an early-clobber output, it cannot be assigned to the same
2323 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002324 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002325 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002326 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002327 case InlineAsm::isInput:
2328 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002329 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002330 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002331 case InlineAsm::isClobber:
2332 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002333 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2334 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002335 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002336 }
2337 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002338
Chris Lattner5c79f982006-02-21 23:12:12 +00002339 // Loop over all of the inputs, copying the operand values into the
2340 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002341 RegsForValue RetValRegs;
2342 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002343 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002344
Chris Lattner2e56e892006-01-31 02:03:41 +00002345 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002346 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2347 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002348
Chris Lattner3a5ed552006-02-01 01:28:23 +00002349 switch (Constraints[i].Type) {
2350 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002351 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2352 if (ConstraintCode.size() == 1) // not a physreg name.
2353 CTy = TLI.getConstraintType(ConstraintCode[0]);
2354
2355 if (CTy == TargetLowering::C_Memory) {
2356 // Memory output.
2357 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2358
2359 // Check that the operand (the address to store to) isn't a float.
2360 if (!MVT::isInteger(InOperandVal.getValueType()))
2361 assert(0 && "MATCH FAIL!");
2362
2363 if (!Constraints[i].isIndirectOutput)
2364 assert(0 && "MATCH FAIL!");
2365
2366 OpNum++; // Consumes a call operand.
2367
2368 // Extend/truncate to the right pointer type if needed.
2369 MVT::ValueType PtrType = TLI.getPointerTy();
2370 if (InOperandVal.getValueType() < PtrType)
2371 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2372 else if (InOperandVal.getValueType() > PtrType)
2373 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2374
2375 // Add information to the INLINEASM node to know about this output.
2376 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2377 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2378 AsmNodeOperands.push_back(InOperandVal);
2379 break;
2380 }
2381
2382 // Otherwise, this is a register output.
2383 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2384
Chris Lattner6f87d182006-02-22 22:37:12 +00002385 // If this is an early-clobber output, or if there is an input
2386 // constraint that matches this, we need to reserve the input register
2387 // so no other inputs allocate to it.
2388 bool UsesInputRegister = false;
2389 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2390 UsesInputRegister = true;
2391
2392 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002393 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002394 RegsForValue Regs =
2395 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2396 true, UsesInputRegister,
2397 OutputRegs, InputRegs);
2398 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00002399
Chris Lattner3a5ed552006-02-01 01:28:23 +00002400 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002401 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002402 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002403 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002404 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002405 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002406 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2407 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002408 OpNum++; // Consumes a call operand.
2409 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002410
2411 // Add information to the INLINEASM node to know that this register is
2412 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002413 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002414 break;
2415 }
2416 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002417 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002418 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002419
Chris Lattner7f5880b2006-02-02 00:25:23 +00002420 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2421 // If this is required to match an output register we have already set,
2422 // just use its register.
2423 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002424
Chris Lattner571d9642006-02-23 19:21:04 +00002425 // Scan until we find the definition we already emitted of this operand.
2426 // When we find it, create a RegsForValue operand.
2427 unsigned CurOp = 2; // The first operand.
2428 for (; OperandNo; --OperandNo) {
2429 // Advance to the next operand.
2430 unsigned NumOps =
2431 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002432 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2433 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002434 "Skipped past definitions?");
2435 CurOp += (NumOps>>3)+1;
2436 }
2437
2438 unsigned NumOps =
2439 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2440 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2441 "Skipped past definitions?");
2442
2443 // Add NumOps>>3 registers to MatchedRegs.
2444 RegsForValue MatchedRegs;
2445 MatchedRegs.ValueVT = InOperandVal.getValueType();
2446 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2447 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2448 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2449 MatchedRegs.Regs.push_back(Reg);
2450 }
2451
2452 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002453 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2454 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002455 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002456 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002457 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002458
2459 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2460 if (ConstraintCode.size() == 1) // not a physreg name.
2461 CTy = TLI.getConstraintType(ConstraintCode[0]);
2462
2463 if (CTy == TargetLowering::C_Other) {
2464 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2465 assert(0 && "MATCH FAIL!");
2466
2467 // Add information to the INLINEASM node to know about this input.
2468 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2469 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2470 AsmNodeOperands.push_back(InOperandVal);
2471 break;
2472 } else if (CTy == TargetLowering::C_Memory) {
2473 // Memory input.
2474
2475 // Check that the operand isn't a float.
2476 if (!MVT::isInteger(InOperandVal.getValueType()))
2477 assert(0 && "MATCH FAIL!");
2478
2479 // Extend/truncate to the right pointer type if needed.
2480 MVT::ValueType PtrType = TLI.getPointerTy();
2481 if (InOperandVal.getValueType() < PtrType)
2482 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2483 else if (InOperandVal.getValueType() > PtrType)
2484 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2485
2486 // Add information to the INLINEASM node to know about this input.
2487 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2488 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2489 AsmNodeOperands.push_back(InOperandVal);
2490 break;
2491 }
2492
2493 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2494
2495 // Copy the input into the appropriate registers.
2496 RegsForValue InRegs =
2497 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2498 false, true, OutputRegs, InputRegs);
2499 // FIXME: should be match fail.
2500 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2501
Evan Chengef9e07d2006-06-15 08:11:54 +00002502 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002503
2504 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002505 break;
2506 }
Chris Lattner571d9642006-02-23 19:21:04 +00002507 case InlineAsm::isClobber: {
2508 RegsForValue ClobberedRegs =
2509 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2510 OutputRegs, InputRegs);
2511 // Add the clobbered value to the operand list, so that the register
2512 // allocator is aware that the physreg got clobbered.
2513 if (!ClobberedRegs.Regs.empty())
2514 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002515 break;
2516 }
Chris Lattner571d9642006-02-23 19:21:04 +00002517 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002518 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002519
2520 // Finish up input operands.
2521 AsmNodeOperands[0] = Chain;
2522 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2523
Chris Lattnerbd887772006-08-14 23:53:35 +00002524 Chain = DAG.getNode(ISD::INLINEASM,
2525 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002526 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002527 Flag = Chain.getValue(1);
2528
Chris Lattner2e56e892006-01-31 02:03:41 +00002529 // If this asm returns a register value, copy the result from that register
2530 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002531 if (!RetValRegs.Regs.empty())
2532 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002533
Chris Lattner2e56e892006-01-31 02:03:41 +00002534 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2535
2536 // Process indirect outputs, first output all of the flagged copies out of
2537 // physregs.
2538 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002539 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002540 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002541 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2542 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002543 }
2544
2545 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002546 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002547 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002548 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002549 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002550 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002551 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002552 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2553 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002554 DAG.setRoot(Chain);
2555}
2556
2557
Chris Lattner7a60d912005-01-07 07:47:53 +00002558void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2559 SDOperand Src = getValue(I.getOperand(0));
2560
2561 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002562
2563 if (IntPtr < Src.getValueType())
2564 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2565 else if (IntPtr > Src.getValueType())
2566 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002567
2568 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002569 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002570 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2571 Src, getIntPtrConstant(ElementSize));
2572
2573 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002574 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002575
2576 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002577 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002578 DAG.getExternalSymbol("malloc", IntPtr),
2579 Args, DAG);
2580 setValue(&I, Result.first); // Pointers always fit in registers
2581 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002582}
2583
2584void SelectionDAGLowering::visitFree(FreeInst &I) {
2585 std::vector<std::pair<SDOperand, const Type*> > Args;
2586 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002587 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002588 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002589 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002590 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002591 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2592 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002593}
2594
Chris Lattner13d7c252005-08-26 20:54:47 +00002595// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2596// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2597// instructions are special in various ways, which require special support to
2598// insert. The specified MachineInstr is created but not inserted into any
2599// basic blocks, and the scheduler passes ownership of it to this method.
2600MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2601 MachineBasicBlock *MBB) {
2602 std::cerr << "If a target marks an instruction with "
2603 "'usesCustomDAGSchedInserter', it must implement "
2604 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2605 abort();
2606 return 0;
2607}
2608
Chris Lattner58cfd792005-01-09 00:00:49 +00002609void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002610 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2611 getValue(I.getOperand(1)),
2612 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002613}
2614
2615void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002616 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2617 getValue(I.getOperand(0)),
2618 DAG.getSrcValue(I.getOperand(0)));
2619 setValue(&I, V);
2620 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002621}
2622
2623void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002624 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2625 getValue(I.getOperand(1)),
2626 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002627}
2628
2629void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002630 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2631 getValue(I.getOperand(1)),
2632 getValue(I.getOperand(2)),
2633 DAG.getSrcValue(I.getOperand(1)),
2634 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002635}
2636
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002637/// TargetLowering::LowerArguments - This is the default LowerArguments
2638/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002639/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2640/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002641std::vector<SDOperand>
2642TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2643 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2644 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002645 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002646 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2647 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2648
2649 // Add one result value for each formal argument.
2650 std::vector<MVT::ValueType> RetVals;
2651 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2652 MVT::ValueType VT = getValueType(I->getType());
2653
2654 switch (getTypeAction(VT)) {
2655 default: assert(0 && "Unknown type action!");
2656 case Legal:
2657 RetVals.push_back(VT);
2658 break;
2659 case Promote:
2660 RetVals.push_back(getTypeToTransformTo(VT));
2661 break;
2662 case Expand:
2663 if (VT != MVT::Vector) {
2664 // If this is a large integer, it needs to be broken up into small
2665 // integers. Figure out what the destination type is and how many small
2666 // integers it turns into.
2667 MVT::ValueType NVT = getTypeToTransformTo(VT);
2668 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2669 for (unsigned i = 0; i != NumVals; ++i)
2670 RetVals.push_back(NVT);
2671 } else {
2672 // Otherwise, this is a vector type. We only support legal vectors
2673 // right now.
2674 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2675 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002676
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002677 // Figure out if there is a Packed type corresponding to this Vector
2678 // type. If so, convert to the packed type.
2679 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2680 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2681 RetVals.push_back(TVT);
2682 } else {
2683 assert(0 && "Don't support illegal by-val vector arguments yet!");
2684 }
2685 }
2686 break;
2687 }
2688 }
Evan Cheng9618df12006-04-25 23:03:35 +00002689
Chris Lattner3d826992006-05-16 06:45:34 +00002690 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002691
2692 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002693 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2694 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002695 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002696
2697 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002698
2699 // Set up the return result vector.
2700 Ops.clear();
2701 unsigned i = 0;
2702 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2703 MVT::ValueType VT = getValueType(I->getType());
2704
2705 switch (getTypeAction(VT)) {
2706 default: assert(0 && "Unknown type action!");
2707 case Legal:
2708 Ops.push_back(SDOperand(Result, i++));
2709 break;
2710 case Promote: {
2711 SDOperand Op(Result, i++);
2712 if (MVT::isInteger(VT)) {
2713 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2714 : ISD::AssertZext;
2715 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2716 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2717 } else {
2718 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2719 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2720 }
2721 Ops.push_back(Op);
2722 break;
2723 }
2724 case Expand:
2725 if (VT != MVT::Vector) {
2726 // If this is a large integer, it needs to be reassembled from small
2727 // integers. Figure out what the source elt type is and how many small
2728 // integers it is.
2729 MVT::ValueType NVT = getTypeToTransformTo(VT);
2730 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2731 if (NumVals == 2) {
2732 SDOperand Lo = SDOperand(Result, i++);
2733 SDOperand Hi = SDOperand(Result, i++);
2734
2735 if (!isLittleEndian())
2736 std::swap(Lo, Hi);
2737
2738 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2739 } else {
2740 // Value scalarized into many values. Unimp for now.
2741 assert(0 && "Cannot expand i64 -> i16 yet!");
2742 }
2743 } else {
2744 // Otherwise, this is a vector type. We only support legal vectors
2745 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002746 const PackedType *PTy = cast<PackedType>(I->getType());
2747 unsigned NumElems = PTy->getNumElements();
2748 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002749
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002750 // Figure out if there is a Packed type corresponding to this Vector
2751 // type. If so, convert to the packed type.
2752 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002753 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002754 SDOperand N = SDOperand(Result, i++);
2755 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002756 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2757 DAG.getConstant(NumElems, MVT::i32),
2758 DAG.getValueType(getValueType(EltTy)));
2759 Ops.push_back(N);
2760 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002761 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002762 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002763 }
2764 }
2765 break;
2766 }
2767 }
2768 return Ops;
2769}
2770
Chris Lattneraaa23d92006-05-16 22:53:20 +00002771
2772/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2773/// implementation, which just inserts an ISD::CALL node, which is later custom
2774/// lowered by the target to something concrete. FIXME: When all targets are
2775/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2776std::pair<SDOperand, SDOperand>
2777TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2778 unsigned CallingConv, bool isTailCall,
2779 SDOperand Callee,
2780 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00002781 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002782 Ops.push_back(Chain); // Op#0 - Chain
2783 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2784 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2785 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2786 Ops.push_back(Callee);
2787
2788 // Handle all of the outgoing arguments.
2789 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2790 MVT::ValueType VT = getValueType(Args[i].second);
2791 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00002792 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00002793 switch (getTypeAction(VT)) {
2794 default: assert(0 && "Unknown type action!");
2795 case Legal:
2796 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002797 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002798 break;
2799 case Promote:
2800 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00002801 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002802 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2803 } else {
2804 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2805 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2806 }
2807 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002808 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002809 break;
2810 case Expand:
2811 if (VT != MVT::Vector) {
2812 // If this is a large integer, it needs to be broken down into small
2813 // integers. Figure out what the source elt type is and how many small
2814 // integers it is.
2815 MVT::ValueType NVT = getTypeToTransformTo(VT);
2816 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2817 if (NumVals == 2) {
2818 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2819 DAG.getConstant(0, getPointerTy()));
2820 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2821 DAG.getConstant(1, getPointerTy()));
2822 if (!isLittleEndian())
2823 std::swap(Lo, Hi);
2824
2825 Ops.push_back(Lo);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002826 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002827 Ops.push_back(Hi);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002828 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002829 } else {
2830 // Value scalarized into many values. Unimp for now.
2831 assert(0 && "Cannot expand i64 -> i16 yet!");
2832 }
2833 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002834 // Otherwise, this is a vector type. We only support legal vectors
2835 // right now.
2836 const PackedType *PTy = cast<PackedType>(Args[i].second);
2837 unsigned NumElems = PTy->getNumElements();
2838 const Type *EltTy = PTy->getElementType();
2839
2840 // Figure out if there is a Packed type corresponding to this Vector
2841 // type. If so, convert to the packed type.
2842 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00002843 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2844 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2845 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2846 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002847 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00002848 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002849 assert(0 && "Don't support illegal by-val vector call args yet!");
2850 abort();
2851 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002852 }
2853 break;
2854 }
2855 }
2856
2857 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00002858 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002859
2860 if (RetTy != Type::VoidTy) {
2861 MVT::ValueType VT = getValueType(RetTy);
2862 switch (getTypeAction(VT)) {
2863 default: assert(0 && "Unknown type action!");
2864 case Legal:
2865 RetTys.push_back(VT);
2866 break;
2867 case Promote:
2868 RetTys.push_back(getTypeToTransformTo(VT));
2869 break;
2870 case Expand:
2871 if (VT != MVT::Vector) {
2872 // If this is a large integer, it needs to be reassembled from small
2873 // integers. Figure out what the source elt type is and how many small
2874 // integers it is.
2875 MVT::ValueType NVT = getTypeToTransformTo(VT);
2876 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2877 for (unsigned i = 0; i != NumVals; ++i)
2878 RetTys.push_back(NVT);
2879 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002880 // Otherwise, this is a vector type. We only support legal vectors
2881 // right now.
2882 const PackedType *PTy = cast<PackedType>(RetTy);
2883 unsigned NumElems = PTy->getNumElements();
2884 const Type *EltTy = PTy->getElementType();
2885
2886 // Figure out if there is a Packed type corresponding to this Vector
2887 // type. If so, convert to the packed type.
2888 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2889 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2890 RetTys.push_back(TVT);
2891 } else {
2892 assert(0 && "Don't support illegal by-val vector call results yet!");
2893 abort();
2894 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002895 }
2896 }
2897 }
2898
2899 RetTys.push_back(MVT::Other); // Always has a chain.
2900
2901 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00002902 SDOperand Res = DAG.getNode(ISD::CALL,
2903 DAG.getVTList(&RetTys[0], RetTys.size()),
2904 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00002905
2906 // This returns a pair of operands. The first element is the
2907 // return value for the function (if RetTy is not VoidTy). The second
2908 // element is the outgoing token chain.
2909 SDOperand ResVal;
2910 if (RetTys.size() != 1) {
2911 MVT::ValueType VT = getValueType(RetTy);
2912 if (RetTys.size() == 2) {
2913 ResVal = Res;
2914
2915 // If this value was promoted, truncate it down.
2916 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002917 if (VT == MVT::Vector) {
2918 // Insert a VBITCONVERT to convert from the packed result type to the
2919 // MVT::Vector type.
2920 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2921 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2922
2923 // Figure out if there is a Packed type corresponding to this Vector
2924 // type. If so, convert to the packed type.
2925 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2926 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002927 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2928 // "N x PTyElementVT" MVT::Vector type.
2929 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00002930 DAG.getConstant(NumElems, MVT::i32),
2931 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00002932 } else {
2933 abort();
2934 }
2935 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00002936 unsigned AssertOp = RetTy->isSigned() ?
2937 ISD::AssertSext : ISD::AssertZext;
2938 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2939 DAG.getValueType(VT));
2940 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2941 } else {
2942 assert(MVT::isFloatingPoint(VT));
2943 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2944 }
2945 }
2946 } else if (RetTys.size() == 3) {
2947 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2948 Res.getValue(0), Res.getValue(1));
2949
2950 } else {
2951 assert(0 && "Case not handled yet!");
2952 }
2953 }
2954
2955 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2956}
2957
2958
2959
Chris Lattner58cfd792005-01-09 00:00:49 +00002960// It is always conservatively correct for llvm.returnaddress and
2961// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00002962//
2963// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2964// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00002965std::pair<SDOperand, SDOperand>
2966TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2967 unsigned Depth, SelectionDAG &DAG) {
2968 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002969}
2970
Chris Lattner29dcc712005-05-14 05:50:48 +00002971SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002972 assert(0 && "LowerOperation not implemented for this target!");
2973 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002974 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002975}
2976
Nate Begeman595ec732006-01-28 03:14:31 +00002977SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2978 SelectionDAG &DAG) {
2979 assert(0 && "CustomPromoteOperation not implemented for this target!");
2980 abort();
2981 return SDOperand();
2982}
2983
Chris Lattner58cfd792005-01-09 00:00:49 +00002984void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002985 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner58cfd792005-01-09 00:00:49 +00002986 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002987 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002988 setValue(&I, Result.first);
2989 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002990}
2991
Evan Cheng6781b6e2006-02-15 21:59:04 +00002992/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002993/// operand.
2994static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002995 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002996 MVT::ValueType CurVT = VT;
2997 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2998 uint64_t Val = C->getValue() & 255;
2999 unsigned Shift = 8;
3000 while (CurVT != MVT::i8) {
3001 Val = (Val << Shift) | Val;
3002 Shift <<= 1;
3003 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003004 }
3005 return DAG.getConstant(Val, VT);
3006 } else {
3007 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3008 unsigned Shift = 8;
3009 while (CurVT != MVT::i8) {
3010 Value =
3011 DAG.getNode(ISD::OR, VT,
3012 DAG.getNode(ISD::SHL, VT, Value,
3013 DAG.getConstant(Shift, MVT::i8)), Value);
3014 Shift <<= 1;
3015 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003016 }
3017
3018 return Value;
3019 }
3020}
3021
Evan Cheng6781b6e2006-02-15 21:59:04 +00003022/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3023/// used when a memcpy is turned into a memset when the source is a constant
3024/// string ptr.
3025static SDOperand getMemsetStringVal(MVT::ValueType VT,
3026 SelectionDAG &DAG, TargetLowering &TLI,
3027 std::string &Str, unsigned Offset) {
3028 MVT::ValueType CurVT = VT;
3029 uint64_t Val = 0;
3030 unsigned MSB = getSizeInBits(VT) / 8;
3031 if (TLI.isLittleEndian())
3032 Offset = Offset + MSB - 1;
3033 for (unsigned i = 0; i != MSB; ++i) {
3034 Val = (Val << 8) | Str[Offset];
3035 Offset += TLI.isLittleEndian() ? -1 : 1;
3036 }
3037 return DAG.getConstant(Val, VT);
3038}
3039
Evan Cheng81fcea82006-02-14 08:22:34 +00003040/// getMemBasePlusOffset - Returns base and offset node for the
3041static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3042 SelectionDAG &DAG, TargetLowering &TLI) {
3043 MVT::ValueType VT = Base.getValueType();
3044 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3045}
3046
Evan Chengdb2a7a72006-02-14 20:12:38 +00003047/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003048/// to replace the memset / memcpy is below the threshold. It also returns the
3049/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003050static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3051 unsigned Limit, uint64_t Size,
3052 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003053 MVT::ValueType VT;
3054
3055 if (TLI.allowsUnalignedMemoryAccesses()) {
3056 VT = MVT::i64;
3057 } else {
3058 switch (Align & 7) {
3059 case 0:
3060 VT = MVT::i64;
3061 break;
3062 case 4:
3063 VT = MVT::i32;
3064 break;
3065 case 2:
3066 VT = MVT::i16;
3067 break;
3068 default:
3069 VT = MVT::i8;
3070 break;
3071 }
3072 }
3073
Evan Chengd5026102006-02-14 09:11:59 +00003074 MVT::ValueType LVT = MVT::i64;
3075 while (!TLI.isTypeLegal(LVT))
3076 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3077 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003078
Evan Chengd5026102006-02-14 09:11:59 +00003079 if (VT > LVT)
3080 VT = LVT;
3081
Evan Cheng04514992006-02-14 23:05:54 +00003082 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003083 while (Size != 0) {
3084 unsigned VTSize = getSizeInBits(VT) / 8;
3085 while (VTSize > Size) {
3086 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003087 VTSize >>= 1;
3088 }
Evan Chengd5026102006-02-14 09:11:59 +00003089 assert(MVT::isInteger(VT));
3090
3091 if (++NumMemOps > Limit)
3092 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003093 MemOps.push_back(VT);
3094 Size -= VTSize;
3095 }
Evan Chengd5026102006-02-14 09:11:59 +00003096
3097 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003098}
3099
Chris Lattner875def92005-01-11 05:56:49 +00003100void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003101 SDOperand Op1 = getValue(I.getOperand(1));
3102 SDOperand Op2 = getValue(I.getOperand(2));
3103 SDOperand Op3 = getValue(I.getOperand(3));
3104 SDOperand Op4 = getValue(I.getOperand(4));
3105 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3106 if (Align == 0) Align = 1;
3107
3108 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3109 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003110
3111 // Expand memset / memcpy to a series of load / store ops
3112 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003113 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003114 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003115 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003116 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003117 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3118 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003119 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003120 unsigned Offset = 0;
3121 for (unsigned i = 0; i < NumMemOps; i++) {
3122 MVT::ValueType VT = MemOps[i];
3123 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003124 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003125 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003126 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003127 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003128 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003129 Offset += VTSize;
3130 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003131 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003132 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003133 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003134 case ISD::MEMCPY: {
3135 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3136 Size->getValue(), Align, TLI)) {
3137 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003138 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003139 GlobalAddressSDNode *G = NULL;
3140 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003141 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003142
3143 if (Op2.getOpcode() == ISD::GlobalAddress)
3144 G = cast<GlobalAddressSDNode>(Op2);
3145 else if (Op2.getOpcode() == ISD::ADD &&
3146 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3147 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3148 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003149 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003150 }
3151 if (G) {
3152 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003153 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00003154 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003155 if (!Str.empty()) {
3156 CopyFromStr = true;
3157 SrcOff += SrcDelta;
3158 }
3159 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003160 }
3161
Evan Chenge2038bd2006-02-15 01:54:51 +00003162 for (unsigned i = 0; i < NumMemOps; i++) {
3163 MVT::ValueType VT = MemOps[i];
3164 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003165 SDOperand Value, Chain, Store;
3166
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003167 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003168 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3169 Chain = getRoot();
3170 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003171 DAG.getStore(Chain, Value,
3172 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003173 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003174 } else {
3175 Value = DAG.getLoad(VT, getRoot(),
3176 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003177 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003178 Chain = Value.getValue(1);
3179 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003180 DAG.getStore(Chain, Value,
3181 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003182 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003183 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003184 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003185 SrcOff += VTSize;
3186 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003187 }
3188 }
3189 break;
3190 }
3191 }
3192
3193 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003194 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3195 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003196 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003197 }
3198 }
3199
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003200 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003201}
3202
Chris Lattner875def92005-01-11 05:56:49 +00003203//===----------------------------------------------------------------------===//
3204// SelectionDAGISel code
3205//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003206
3207unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3208 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3209}
3210
Chris Lattnerc9950c12005-08-17 06:37:43 +00003211void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003212 // FIXME: we only modify the CFG to split critical edges. This
3213 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003214 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003215}
Chris Lattner7a60d912005-01-07 07:47:53 +00003216
Chris Lattner35397782005-12-05 07:10:48 +00003217
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003218/// OptimizeNoopCopyExpression - We have determined that the specified cast
3219/// instruction is a noop copy (e.g. it's casting from one pointer type to
3220/// another, int->uint, or int->sbyte on PPC.
3221///
3222/// Return true if any changes are made.
3223static bool OptimizeNoopCopyExpression(CastInst *CI) {
3224 BasicBlock *DefBB = CI->getParent();
3225
3226 /// InsertedCasts - Only insert a cast in each block once.
3227 std::map<BasicBlock*, CastInst*> InsertedCasts;
3228
3229 bool MadeChange = false;
3230 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3231 UI != E; ) {
3232 Use &TheUse = UI.getUse();
3233 Instruction *User = cast<Instruction>(*UI);
3234
3235 // Figure out which BB this cast is used in. For PHI's this is the
3236 // appropriate predecessor block.
3237 BasicBlock *UserBB = User->getParent();
3238 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3239 unsigned OpVal = UI.getOperandNo()/2;
3240 UserBB = PN->getIncomingBlock(OpVal);
3241 }
3242
3243 // Preincrement use iterator so we don't invalidate it.
3244 ++UI;
3245
3246 // If this user is in the same block as the cast, don't change the cast.
3247 if (UserBB == DefBB) continue;
3248
3249 // If we have already inserted a cast into this block, use it.
3250 CastInst *&InsertedCast = InsertedCasts[UserBB];
3251
3252 if (!InsertedCast) {
3253 BasicBlock::iterator InsertPt = UserBB->begin();
3254 while (isa<PHINode>(InsertPt)) ++InsertPt;
3255
3256 InsertedCast =
3257 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3258 MadeChange = true;
3259 }
3260
3261 // Replace a use of the cast with a use of the new casat.
3262 TheUse = InsertedCast;
3263 }
3264
3265 // If we removed all uses, nuke the cast.
3266 if (CI->use_empty())
3267 CI->eraseFromParent();
3268
3269 return MadeChange;
3270}
3271
Chris Lattner35397782005-12-05 07:10:48 +00003272/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3273/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003274static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3275 Instruction *GEPI, Value *Ptr,
3276 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003277 if (V) return V; // Already computed.
3278
3279 BasicBlock::iterator InsertPt;
3280 if (BB == GEPI->getParent()) {
3281 // If insert into the GEP's block, insert right after the GEP.
3282 InsertPt = GEPI;
3283 ++InsertPt;
3284 } else {
3285 // Otherwise, insert at the top of BB, after any PHI nodes
3286 InsertPt = BB->begin();
3287 while (isa<PHINode>(InsertPt)) ++InsertPt;
3288 }
3289
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003290 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3291 // BB so that there is only one value live across basic blocks (the cast
3292 // operand).
3293 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3294 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3295 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3296
Chris Lattner35397782005-12-05 07:10:48 +00003297 // Add the offset, cast it to the right type.
3298 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattner21cd9902006-05-06 09:10:37 +00003299 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003300}
3301
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003302/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3303/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3304/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3305/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3306/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3307/// the constant add into a load or store instruction. Additionally, if a user
3308/// is a pointer-pointer cast, we look through it to find its users.
3309static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3310 Constant *PtrOffset, BasicBlock *DefBB,
3311 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003312 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003313 while (!RepPtr->use_empty()) {
3314 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003315
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003316 // If the user is a Pointer-Pointer cast, recurse.
3317 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3318 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003319
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003320 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3321 // could invalidate an iterator.
3322 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3323 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003324 }
3325
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003326 // If this is a load of the pointer, or a store through the pointer, emit
3327 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003328 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003329 if (isa<LoadInst>(User) ||
3330 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3331 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3332 User->getParent(), GEPI,
3333 Ptr, PtrOffset);
3334 } else {
3335 // If this use is not foldable into the addressing mode, use a version
3336 // emitted in the GEP block.
3337 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3338 Ptr, PtrOffset);
3339 }
3340
Chris Lattner21cd9902006-05-06 09:10:37 +00003341 if (GEPI->getType() != RepPtr->getType()) {
3342 BasicBlock::iterator IP = NewVal;
3343 ++IP;
3344 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3345 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003346 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003347 }
3348}
Chris Lattner35397782005-12-05 07:10:48 +00003349
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003350
Chris Lattner35397782005-12-05 07:10:48 +00003351/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3352/// selection, we want to be a bit careful about some things. In particular, if
3353/// we have a GEP instruction that is used in a different block than it is
3354/// defined, the addressing expression of the GEP cannot be folded into loads or
3355/// stores that use it. In this case, decompose the GEP and move constant
3356/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003357static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003358 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003359 // If this GEP is only used inside the block it is defined in, there is no
3360 // need to rewrite it.
3361 bool isUsedOutsideDefBB = false;
3362 BasicBlock *DefBB = GEPI->getParent();
3363 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3364 UI != E; ++UI) {
3365 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3366 isUsedOutsideDefBB = true;
3367 break;
3368 }
3369 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003370 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003371
3372 // If this GEP has no non-zero constant indices, there is nothing we can do,
3373 // ignore it.
3374 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003375 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003376 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3377 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003378 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003379 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003380 hasConstantIndex = true;
3381 break;
3382 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003383 } else {
3384 hasVariableIndex = true;
3385 }
Chris Lattner35397782005-12-05 07:10:48 +00003386 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003387
3388 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3389 if (!hasConstantIndex && !hasVariableIndex) {
3390 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3391 GEPI->getName(), GEPI);
3392 GEPI->replaceAllUsesWith(NC);
3393 GEPI->eraseFromParent();
3394 return true;
3395 }
3396
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003397 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003398 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3399 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003400
3401 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3402 // constant offset (which we now know is non-zero) and deal with it later.
3403 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003404 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattner35397782005-12-05 07:10:48 +00003405 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3406 const Type *Ty = GEPI->getOperand(0)->getType();
3407
3408 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3409 E = GEPI->op_end(); OI != E; ++OI) {
3410 Value *Idx = *OI;
3411 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003412 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003413 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003414 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003415 Ty = StTy->getElementType(Field);
3416 } else {
3417 Ty = cast<SequentialType>(Ty)->getElementType();
3418
3419 // Handle constant subscripts.
3420 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003421 if (CI->getZExtValue() == 0) continue;
3422 if (CI->getType()->isSigned())
3423 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003424 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00003425 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003426 continue;
3427 }
3428
3429 // Ptr = Ptr + Idx * ElementSize;
3430
3431 // Cast Idx to UIntPtrTy if needed.
3432 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3433
Owen Anderson20a631f2006-05-03 01:29:57 +00003434 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003435 // Mask off bits that should not be set.
3436 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003437 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003438
3439 // Multiply by the element size and add to the base.
3440 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3441 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3442 }
3443 }
3444
3445 // Make sure that the offset fits in uintptr_t.
3446 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003447 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003448
3449 // Okay, we have now emitted all of the variable index parts to the BB that
3450 // the GEP is defined in. Loop over all of the using instructions, inserting
3451 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003452 // instruction to use the newly computed value, making GEPI dead. When the
3453 // user is a load or store instruction address, we emit the add into the user
3454 // block, otherwise we use a canonical version right next to the gep (these
3455 // won't be foldable as addresses, so we might as well share the computation).
3456
Chris Lattner21cd9902006-05-06 09:10:37 +00003457 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003458 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003459
3460 // Finally, the GEP is dead, remove it.
3461 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003462
3463 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003464}
3465
Chris Lattnera9caf952006-09-28 06:17:10 +00003466/// SplitCritEdgesForPHIConstants - If this block has any PHI nodes with
3467/// constant operands, and if any of the edges feeding the PHI node are
3468/// critical, split them so that the assignments of a constant to a register
3469/// will not be executed on a path that isn't relevant.
3470void SelectionDAGISel::SplitCritEdgesForPHIConstants(BasicBlock *BB) {
Chris Lattner6df34962006-10-11 03:58:02 +00003471 // The most common case is that this is a PHI node with two incoming
3472 // successors handle this case efficiently, because it is simple.
3473 PHINode *PN = cast<PHINode>(BB->begin());
3474 if (PN->getNumIncomingValues() == 2) {
3475 // If neither edge is critical, we never need to split.
3476 if (PN->getIncomingBlock(0)->getTerminator()->getNumSuccessors() == 1 &&
3477 PN->getIncomingBlock(1)->getTerminator()->getNumSuccessors() == 1)
3478 return;
3479
3480 BasicBlock::iterator BBI = BB->begin();
3481 while ((PN = dyn_cast<PHINode>(BBI++))) {
3482 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3483 if (isa<Constant>(PN->getIncomingValue(i)))
3484 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3485 }
3486 return;
3487 }
3488
3489 // Otherwise, things are a bit trickier.
3490
3491 // BE SMART HERE.
3492
Chris Lattnera9caf952006-09-28 06:17:10 +00003493 BasicBlock::iterator BBI = BB->begin();
3494 while ((PN = dyn_cast<PHINode>(BBI++))) {
3495 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3496 if (isa<Constant>(PN->getIncomingValue(i)))
3497 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3498 }
3499}
3500
3501
Chris Lattner7a60d912005-01-07 07:47:53 +00003502bool SelectionDAGISel::runOnFunction(Function &Fn) {
3503 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3504 RegMap = MF.getSSARegMap();
3505 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3506
Chris Lattner35397782005-12-05 07:10:48 +00003507 // First, split all critical edges for PHI nodes with incoming values that are
3508 // constants, this way the load of the constant into a vreg will not be placed
3509 // into MBBs that are used some other way.
3510 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003511 // In this pass we also look for GEP and cast instructions that are used
3512 // across basic blocks and rewrite them to improve basic-block-at-a-time
3513 // selection.
3514 //
Chris Lattner35397782005-12-05 07:10:48 +00003515 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003516 bool MadeChange = true;
3517 while (MadeChange) {
3518 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003519 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnera9caf952006-09-28 06:17:10 +00003520 // If this block has any PHI nodes with constant operands, and if any of the
3521 // edges feeding the PHI node are critical, split them.
3522 if (isa<PHINode>(BB->begin()))
3523 SplitCritEdgesForPHIConstants(BB);
Chris Lattner35397782005-12-05 07:10:48 +00003524
Chris Lattnera9caf952006-09-28 06:17:10 +00003525 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003526 Instruction *I = BBI++;
3527 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003528 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003529 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003530 // If the source of the cast is a constant, then this should have
3531 // already been constant folded. The only reason NOT to constant fold
3532 // it is if something (e.g. LSR) was careful to place the constant
3533 // evaluation in a block other than then one that uses it (e.g. to hoist
3534 // the address of globals out of a loop). If this is the case, we don't
3535 // want to forward-subst the cast.
3536 if (isa<Constant>(CI->getOperand(0)))
3537 continue;
3538
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003539 // If this is a noop copy, sink it into user blocks to reduce the number
3540 // of virtual registers that must be created and coallesced.
3541 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3542 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3543
3544 // This is an fp<->int conversion?
3545 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3546 continue;
3547
3548 // If this is an extension, it will be a zero or sign extension, which
3549 // isn't a noop.
3550 if (SrcVT < DstVT) continue;
3551
3552 // If these values will be promoted, find out what they will be promoted
3553 // to. This helps us consider truncates on PPC as noop copies when they
3554 // are.
3555 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3556 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3557 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3558 DstVT = TLI.getTypeToTransformTo(DstVT);
3559
3560 // If, after promotion, these are the same types, this is a noop copy.
3561 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003562 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003563 }
3564 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003565 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003566 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003567
Chris Lattner7a60d912005-01-07 07:47:53 +00003568 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3569
3570 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3571 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003572
Chris Lattner7a60d912005-01-07 07:47:53 +00003573 return true;
3574}
3575
Chris Lattnered0110b2006-10-27 21:36:01 +00003576SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3577 unsigned Reg) {
3578 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003579 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003580 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003581 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003582
3583 // If this type is not legal, we must make sure to not create an invalid
3584 // register use.
3585 MVT::ValueType SrcVT = Op.getValueType();
3586 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00003587 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00003588 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003589 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003590 // Handle copies from generic vectors to registers.
3591 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3592 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3593 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003594
Chris Lattner5fe1f542006-03-31 02:06:56 +00003595 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3596 // MVT::Vector type.
3597 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3598 DAG.getConstant(NE, MVT::i32),
3599 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003600
Chris Lattner5fe1f542006-03-31 02:06:56 +00003601 // Loop over all of the elements of the resultant vector,
3602 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3603 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003604 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00003605 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00003606 for (unsigned i = 0; i != NE; ++i) {
3607 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003608 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003609 if (PTyElementVT == PTyLegalElementVT) {
3610 // Elements are legal.
3611 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3612 } else if (PTyLegalElementVT > PTyElementVT) {
3613 // Elements are promoted.
3614 if (MVT::isFloatingPoint(PTyLegalElementVT))
3615 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3616 else
3617 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3618 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3619 } else {
3620 // Elements are expanded.
3621 // The src value is expanded into multiple registers.
3622 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003623 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003624 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003625 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003626 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3627 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3628 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003629 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003630 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3631 &OutChains[0], OutChains.size());
Chris Lattner33182322005-08-16 21:55:35 +00003632 } else if (SrcVT < DestVT) {
3633 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003634 if (MVT::isFloatingPoint(SrcVT))
3635 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3636 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003637 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00003638 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003639 } else {
3640 // The src value is expanded into multiple registers.
3641 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003642 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003643 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003644 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00003645 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00003646 return DAG.getCopyToReg(Op, Reg+1, Hi);
3647 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003648}
3649
Chris Lattner16f64df2005-01-17 17:15:02 +00003650void SelectionDAGISel::
3651LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3652 std::vector<SDOperand> &UnorderedChains) {
3653 // If this is the entry block, emit arguments.
3654 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003655 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003656 SDOperand OldRoot = SDL.DAG.getRoot();
3657 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003658
Chris Lattner6871b232005-10-30 19:42:35 +00003659 unsigned a = 0;
3660 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3661 AI != E; ++AI, ++a)
3662 if (!AI->use_empty()) {
3663 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003664
Chris Lattner6871b232005-10-30 19:42:35 +00003665 // If this argument is live outside of the entry block, insert a copy from
3666 // whereever we got it to the vreg that other BB's will reference it as.
3667 if (FuncInfo.ValueMap.count(AI)) {
3668 SDOperand Copy =
Chris Lattnered0110b2006-10-27 21:36:01 +00003669 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattner6871b232005-10-30 19:42:35 +00003670 UnorderedChains.push_back(Copy);
3671 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003672 }
Chris Lattner6871b232005-10-30 19:42:35 +00003673
Chris Lattner6871b232005-10-30 19:42:35 +00003674 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003675 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003676 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003677}
3678
Chris Lattner7a60d912005-01-07 07:47:53 +00003679void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3680 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003681 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003682 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003683
3684 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003685
Chris Lattner6871b232005-10-30 19:42:35 +00003686 // Lower any arguments needed in this block if this is the entry block.
3687 if (LLVMBB == &LLVMBB->getParent()->front())
3688 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003689
3690 BB = FuncInfo.MBBMap[LLVMBB];
3691 SDL.setCurrentBasicBlock(BB);
3692
3693 // Lower all of the non-terminator instructions.
3694 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3695 I != E; ++I)
3696 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003697
Chris Lattner7a60d912005-01-07 07:47:53 +00003698 // Ensure that all instructions which are used outside of their defining
3699 // blocks are available as virtual registers.
3700 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003701 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003702 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003703 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003704 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003705 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003706 }
3707
3708 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3709 // ensure constants are generated when needed. Remember the virtual registers
3710 // that need to be added to the Machine PHI nodes as input. We cannot just
3711 // directly add them, because expansion might result in multiple MBB's for one
3712 // BB. As such, the start of the BB might correspond to a different MBB than
3713 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003714 //
Chris Lattner7a60d912005-01-07 07:47:53 +00003715
3716 // Emit constants only once even if used by multiple PHI nodes.
3717 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00003718
Chris Lattner7a60d912005-01-07 07:47:53 +00003719 // Check successor nodes PHI nodes that expect a constant to be available from
3720 // this block.
3721 TerminatorInst *TI = LLVMBB->getTerminator();
3722 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3723 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00003724 if (!isa<PHINode>(SuccBB->begin())) continue;
3725
Chris Lattner7a60d912005-01-07 07:47:53 +00003726 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3727 PHINode *PN;
3728
3729 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3730 // nodes and Machine PHI nodes, but the incoming operands have not been
3731 // emitted yet.
3732 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00003733 (PN = dyn_cast<PHINode>(I)); ++I)
3734 if (!PN->use_empty()) {
3735 unsigned Reg;
3736 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3737 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3738 unsigned &RegOut = ConstantsOut[C];
3739 if (RegOut == 0) {
3740 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00003741 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003742 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00003743 }
3744 Reg = RegOut;
3745 } else {
3746 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00003747 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00003748 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00003749 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3750 "Didn't codegen value into a register!??");
3751 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00003752 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003753 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00003754 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003755 }
Misha Brukman835702a2005-04-21 22:36:52 +00003756
Chris Lattner8ea875f2005-01-07 21:34:19 +00003757 // Remember that this register needs to added to the machine PHI node as
3758 // the input for this MBB.
Chris Lattnerba380352006-03-31 02:12:18 +00003759 MVT::ValueType VT = TLI.getValueType(PN->getType());
3760 unsigned NumElements;
3761 if (VT != MVT::Vector)
3762 NumElements = TLI.getNumElements(VT);
3763 else {
3764 MVT::ValueType VT1,VT2;
3765 NumElements =
3766 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3767 VT1, VT2);
3768 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00003769 for (unsigned i = 0, e = NumElements; i != e; ++i)
3770 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00003771 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003772 }
3773 ConstantsOut.clear();
3774
Chris Lattner718b5c22005-01-13 17:59:43 +00003775 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003776 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003777 SDOperand Root = SDL.getRoot();
3778 if (Root.getOpcode() != ISD::EntryToken) {
3779 unsigned i = 0, e = UnorderedChains.size();
3780 for (; i != e; ++i) {
3781 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3782 if (UnorderedChains[i].Val->getOperand(0) == Root)
3783 break; // Don't add the root if we already indirectly depend on it.
3784 }
3785
3786 if (i == e)
3787 UnorderedChains.push_back(Root);
3788 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003789 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3790 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00003791 }
3792
Chris Lattner7a60d912005-01-07 07:47:53 +00003793 // Lower the terminator after the copies are emitted.
3794 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003795
Nate Begemaned728c12006-03-27 01:32:24 +00003796 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003797 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00003798 SwitchCases.clear();
3799 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003800 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00003801
Chris Lattner4108bb02005-01-17 19:43:36 +00003802 // Make sure the root of the DAG is up-to-date.
3803 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003804}
3805
Nate Begemaned728c12006-03-27 01:32:24 +00003806void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003807 // Get alias analysis for load/store combining.
3808 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3809
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003810 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003811 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003812
Chris Lattner7a60d912005-01-07 07:47:53 +00003813 DEBUG(std::cerr << "Lowered selection DAG:\n");
3814 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003815
Chris Lattner7a60d912005-01-07 07:47:53 +00003816 // Second step, hack on the DAG until it only uses operations and types that
3817 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00003818 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00003819
Chris Lattner7a60d912005-01-07 07:47:53 +00003820 DEBUG(std::cerr << "Legalized selection DAG:\n");
3821 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003822
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003823 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003824 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003825
Evan Cheng739a6a42006-01-21 02:32:06 +00003826 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00003827
Chris Lattner5ca31d92005-03-30 01:10:47 +00003828 // Third, instruction select all of the operations to machine code, adding the
3829 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00003830 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00003831
Chris Lattner7a60d912005-01-07 07:47:53 +00003832 DEBUG(std::cerr << "Selected machine code:\n");
3833 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003834}
Chris Lattner7a60d912005-01-07 07:47:53 +00003835
Nate Begemaned728c12006-03-27 01:32:24 +00003836void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3837 FunctionLoweringInfo &FuncInfo) {
3838 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3839 {
3840 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3841 CurDAG = &DAG;
3842
3843 // First step, lower LLVM code to some DAG. This DAG may use operations and
3844 // types that are not supported by the target.
3845 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3846
3847 // Second step, emit the lowered DAG as machine code.
3848 CodeGenAndEmitDAG(DAG);
3849 }
3850
Chris Lattner5ca31d92005-03-30 01:10:47 +00003851 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00003852 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003853 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00003854 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3855 MachineInstr *PHI = PHINodesToUpdate[i].first;
3856 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3857 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003858 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00003859 PHI->addMachineBasicBlockOperand(BB);
3860 }
3861 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00003862 }
Nate Begemaned728c12006-03-27 01:32:24 +00003863
Nate Begeman866b4b42006-04-23 06:26:20 +00003864 // If the JumpTable record is filled in, then we need to emit a jump table.
3865 // Updating the PHI nodes is tricky in this case, since we need to determine
3866 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003867 if (JT.Reg) {
3868 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3869 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3870 CurDAG = &SDAG;
3871 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00003872 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003873 // Set the current basic block to the mbb we wish to insert the code into
3874 BB = JT.MBB;
3875 SDL.setCurrentBasicBlock(BB);
3876 // Emit the code
3877 SDL.visitJumpTable(JT);
3878 SDAG.setRoot(SDL.getRoot());
3879 CodeGenAndEmitDAG(SDAG);
3880 // Update PHI Nodes
3881 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3882 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3883 MachineBasicBlock *PHIBB = PHI->getParent();
3884 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3885 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00003886 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003887 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003888 PHI->addMachineBasicBlockOperand(RangeBB);
3889 }
3890 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003891 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003892 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003893 }
3894 }
3895 return;
3896 }
3897
Chris Lattner76a7bc82006-10-22 23:00:53 +00003898 // If the switch block involved a branch to one of the actual successors, we
3899 // need to update PHI nodes in that block.
3900 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3901 MachineInstr *PHI = PHINodesToUpdate[i].first;
3902 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3903 "This is not a machine PHI node that we are updating!");
3904 if (BB->isSuccessor(PHI->getParent())) {
3905 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3906 PHI->addMachineBasicBlockOperand(BB);
3907 }
3908 }
3909
Nate Begemaned728c12006-03-27 01:32:24 +00003910 // If we generated any switch lowering information, build and codegen any
3911 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00003912 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00003913 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3914 CurDAG = &SDAG;
3915 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00003916
Nate Begemaned728c12006-03-27 01:32:24 +00003917 // Set the current basic block to the mbb we wish to insert the code into
3918 BB = SwitchCases[i].ThisBB;
3919 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00003920
Nate Begemaned728c12006-03-27 01:32:24 +00003921 // Emit the code
3922 SDL.visitSwitchCase(SwitchCases[i]);
3923 SDAG.setRoot(SDL.getRoot());
3924 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00003925
3926 // Handle any PHI nodes in successors of this chunk, as if we were coming
3927 // from the original BB before switch expansion. Note that PHI nodes can
3928 // occur multiple times in PHINodesToUpdate. We have to be very careful to
3929 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00003930 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00003931 for (MachineBasicBlock::iterator Phi = BB->begin();
3932 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
3933 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
3934 for (unsigned pn = 0; ; ++pn) {
3935 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
3936 if (PHINodesToUpdate[pn].first == Phi) {
3937 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
3938 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
3939 break;
3940 }
3941 }
Nate Begemaned728c12006-03-27 01:32:24 +00003942 }
Chris Lattner707339a52006-09-07 01:59:34 +00003943
3944 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00003945 if (BB == SwitchCases[i].FalseBB)
3946 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00003947
3948 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00003949 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00003950 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00003951 }
Chris Lattner963ddad2006-10-24 17:57:59 +00003952 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00003953 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003954}
Evan Cheng739a6a42006-01-21 02:32:06 +00003955
Jim Laskey95eda5b2006-08-01 14:21:23 +00003956
Evan Cheng739a6a42006-01-21 02:32:06 +00003957//===----------------------------------------------------------------------===//
3958/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3959/// target node in the graph.
3960void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3961 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00003962
Jim Laskey29e635d2006-08-02 12:30:23 +00003963 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00003964
3965 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00003966 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00003967 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00003968 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00003969
Jim Laskey03593f72006-08-01 18:29:48 +00003970 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00003971 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00003972 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00003973}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003974
Chris Lattner47639db2006-03-06 00:22:00 +00003975
Jim Laskey03593f72006-08-01 18:29:48 +00003976HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3977 return new HazardRecognizer();
3978}
3979
Chris Lattner6df34962006-10-11 03:58:02 +00003980//===----------------------------------------------------------------------===//
3981// Helper functions used by the generated instruction selector.
3982//===----------------------------------------------------------------------===//
3983// Calls to these methods are generated by tblgen.
3984
3985/// CheckAndMask - The isel is trying to match something like (and X, 255). If
3986/// the dag combiner simplified the 255, we still want to match. RHS is the
3987/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
3988/// specified in the .td file (e.g. 255).
3989bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
3990 int64_t DesiredMaskS) {
3991 uint64_t ActualMask = RHS->getValue();
3992 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3993
3994 // If the actual mask exactly matches, success!
3995 if (ActualMask == DesiredMask)
3996 return true;
3997
3998 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3999 if (ActualMask & ~DesiredMask)
4000 return false;
4001
4002 // Otherwise, the DAG Combiner may have proven that the value coming in is
4003 // either already zero or is not demanded. Check for known zero input bits.
4004 uint64_t NeededMask = DesiredMask & ~ActualMask;
4005 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4006 return true;
4007
4008 // TODO: check to see if missing bits are just not demanded.
4009
4010 // Otherwise, this pattern doesn't match.
4011 return false;
4012}
4013
4014/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4015/// the dag combiner simplified the 255, we still want to match. RHS is the
4016/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4017/// specified in the .td file (e.g. 255).
4018bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4019 int64_t DesiredMaskS) {
4020 uint64_t ActualMask = RHS->getValue();
4021 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4022
4023 // If the actual mask exactly matches, success!
4024 if (ActualMask == DesiredMask)
4025 return true;
4026
4027 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4028 if (ActualMask & ~DesiredMask)
4029 return false;
4030
4031 // Otherwise, the DAG Combiner may have proven that the value coming in is
4032 // either already zero or is not demanded. Check for known zero input bits.
4033 uint64_t NeededMask = DesiredMask & ~ActualMask;
4034
4035 uint64_t KnownZero, KnownOne;
4036 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4037
4038 // If all the missing bits in the or are already known to be set, match!
4039 if ((NeededMask & KnownOne) == NeededMask)
4040 return true;
4041
4042 // TODO: check to see if missing bits are just not demanded.
4043
4044 // Otherwise, this pattern doesn't match.
4045 return false;
4046}
4047
Jim Laskey03593f72006-08-01 18:29:48 +00004048
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004049/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4050/// by tblgen. Others should not call it.
4051void SelectionDAGISel::
4052SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4053 std::vector<SDOperand> InOps;
4054 std::swap(InOps, Ops);
4055
4056 Ops.push_back(InOps[0]); // input chain.
4057 Ops.push_back(InOps[1]); // input asm string.
4058
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004059 unsigned i = 2, e = InOps.size();
4060 if (InOps[e-1].getValueType() == MVT::Flag)
4061 --e; // Don't process a flag operand if it is here.
4062
4063 while (i != e) {
4064 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4065 if ((Flags & 7) != 4 /*MEM*/) {
4066 // Just skip over this operand, copying the operands verbatim.
4067 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4068 i += (Flags >> 3) + 1;
4069 } else {
4070 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4071 // Otherwise, this is a memory operand. Ask the target to select it.
4072 std::vector<SDOperand> SelOps;
4073 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4074 std::cerr << "Could not match memory address. Inline asm failure!\n";
4075 exit(1);
4076 }
4077
4078 // Add this to the output node.
4079 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4080 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4081 i += 2;
4082 }
4083 }
4084
4085 // Add the flag input back if present.
4086 if (e != InOps.size())
4087 Ops.push_back(InOps.back());
4088}