blob: d1e9365274a0b652eec5cc64787c3264d488da19 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2//
3// 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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/ADT/BitVector.h"
16#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/CodeGen/SelectionDAGISel.h"
18#include "llvm/CodeGen/ScheduleDAG.h"
19#include "llvm/Constants.h"
20#include "llvm/CallingConv.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/InlineAsm.h"
25#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/IntrinsicInst.h"
28#include "llvm/ParameterAttributes.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineJumpTableInfo.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
34#include "llvm/CodeGen/SchedulerRegistry.h"
35#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SSARegMap.h"
37#include "llvm/Target/MRegisterInfo.h"
38#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetFrameInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetLowering.h"
42#include "llvm/Target/TargetMachine.h"
43#include "llvm/Target/TargetOptions.h"
44#include "llvm/Support/MathExtras.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/Compiler.h"
47#include <algorithm>
48using namespace llvm;
49
50#ifndef NDEBUG
51static cl::opt<bool>
52ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman134c5b62007-08-28 20:32:58 +000057static cl::opt<bool>
58ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
59 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060#else
Dan Gohman134c5b62007-08-28 20:32:58 +000061static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#endif
63
64//===---------------------------------------------------------------------===//
65///
66/// RegisterScheduler class - Track the registration of instruction schedulers.
67///
68//===---------------------------------------------------------------------===//
69MachinePassRegistry RegisterScheduler::Registry;
70
71//===---------------------------------------------------------------------===//
72///
73/// ISHeuristic command line option for instruction schedulers.
74///
75//===---------------------------------------------------------------------===//
76namespace {
77 cl::opt<RegisterScheduler::FunctionPassCtor, false,
78 RegisterPassParser<RegisterScheduler> >
79 ISHeuristic("pre-RA-sched",
80 cl::init(&createDefaultScheduler),
81 cl::desc("Instruction schedulers available (before register allocation):"));
82
83 static RegisterScheduler
84 defaultListDAGScheduler("default", " Best scheduler for the target",
85 createDefaultScheduler);
86} // namespace
87
88namespace { struct AsmOperandInfo; }
89
90namespace {
91 /// RegsForValue - This struct represents the physical registers that a
92 /// particular value is assigned and the type information about the value.
93 /// This is needed because values can be promoted into larger registers and
94 /// expanded into multiple smaller registers than the value.
95 struct VISIBILITY_HIDDEN RegsForValue {
96 /// Regs - This list holds the register (for legal and promoted values)
97 /// or register set (for expanded values) that the value should be assigned
98 /// to.
99 std::vector<unsigned> Regs;
100
101 /// RegVT - The value type of each register.
102 ///
103 MVT::ValueType RegVT;
104
105 /// ValueVT - The value type of the LLVM value, which may be promoted from
106 /// RegVT or made from merging the two expanded parts.
107 MVT::ValueType ValueVT;
108
109 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
110
111 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
112 : RegVT(regvt), ValueVT(valuevt) {
113 Regs.push_back(Reg);
114 }
115 RegsForValue(const std::vector<unsigned> &regs,
116 MVT::ValueType regvt, MVT::ValueType valuevt)
117 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
118 }
119
120 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
121 /// this value and returns the result as a ValueVT value. This uses
122 /// Chain/Flag as the input and updates them for the output Chain/Flag.
123 /// If the Flag pointer is NULL, no flag is used.
124 SDOperand getCopyFromRegs(SelectionDAG &DAG,
125 SDOperand &Chain, SDOperand *Flag) const;
126
127 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
128 /// specified value into the registers specified by this object. This uses
129 /// Chain/Flag as the input and updates them for the output Chain/Flag.
130 /// If the Flag pointer is NULL, no flag is used.
131 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
132 SDOperand &Chain, SDOperand *Flag) const;
133
134 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
135 /// operand list. This adds the code marker and includes the number of
136 /// values added into it.
137 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
138 std::vector<SDOperand> &Ops) const;
139 };
140}
141
142namespace llvm {
143 //===--------------------------------------------------------------------===//
144 /// createDefaultScheduler - This creates an instruction scheduler appropriate
145 /// for the target.
146 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
147 SelectionDAG *DAG,
148 MachineBasicBlock *BB) {
149 TargetLowering &TLI = IS->getTargetLowering();
150
151 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
152 return createTDListDAGScheduler(IS, DAG, BB);
153 } else {
154 assert(TLI.getSchedulingPreference() ==
155 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
156 return createBURRListDAGScheduler(IS, DAG, BB);
157 }
158 }
159
160
161 //===--------------------------------------------------------------------===//
162 /// FunctionLoweringInfo - This contains information that is global to a
163 /// function that is used when lowering a region of the function.
164 class FunctionLoweringInfo {
165 public:
166 TargetLowering &TLI;
167 Function &Fn;
168 MachineFunction &MF;
169 SSARegMap *RegMap;
170
171 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
172
173 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
174 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
175
176 /// ValueMap - Since we emit code for the function a basic block at a time,
177 /// we must remember which virtual registers hold the values for
178 /// cross-basic-block values.
179 DenseMap<const Value*, unsigned> ValueMap;
180
181 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
182 /// the entry block. This allows the allocas to be efficiently referenced
183 /// anywhere in the function.
184 std::map<const AllocaInst*, int> StaticAllocaMap;
185
186#ifndef NDEBUG
187 SmallSet<Instruction*, 8> CatchInfoLost;
188 SmallSet<Instruction*, 8> CatchInfoFound;
189#endif
190
191 unsigned MakeReg(MVT::ValueType VT) {
192 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
193 }
194
195 /// isExportedInst - Return true if the specified value is an instruction
196 /// exported from its block.
197 bool isExportedInst(const Value *V) {
198 return ValueMap.count(V);
199 }
200
201 unsigned CreateRegForValue(const Value *V);
202
203 unsigned InitializeRegForValue(const Value *V) {
204 unsigned &R = ValueMap[V];
205 assert(R == 0 && "Already initialized this value register!");
206 return R = CreateRegForValue(V);
207 }
208 };
209}
210
211/// isSelector - Return true if this instruction is a call to the
212/// eh.selector intrinsic.
213static bool isSelector(Instruction *I) {
214 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
215 return II->getIntrinsicID() == Intrinsic::eh_selector;
216 return false;
217}
218
219/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
220/// PHI nodes or outside of the basic block that defines it, or used by a
221/// switch instruction, which may expand to multiple basic blocks.
222static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
223 if (isa<PHINode>(I)) return true;
224 BasicBlock *BB = I->getParent();
225 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
226 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
227 // FIXME: Remove switchinst special case.
228 isa<SwitchInst>(*UI))
229 return true;
230 return false;
231}
232
233/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
234/// entry block, return true. This includes arguments used by switches, since
235/// the switch may expand into multiple basic blocks.
236static bool isOnlyUsedInEntryBlock(Argument *A) {
237 BasicBlock *Entry = A->getParent()->begin();
238 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
239 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
240 return false; // Use not in entry block.
241 return true;
242}
243
244FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
245 Function &fn, MachineFunction &mf)
246 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
247
248 // Create a vreg for each argument register that is not dead and is used
249 // outside of the entry block for the function.
250 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
251 AI != E; ++AI)
252 if (!isOnlyUsedInEntryBlock(AI))
253 InitializeRegForValue(AI);
254
255 // Initialize the mapping of values to registers. This is only set up for
256 // instruction values that are used outside of the block that defines
257 // them.
258 Function::iterator BB = Fn.begin(), EB = Fn.end();
259 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
260 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
261 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
262 const Type *Ty = AI->getAllocatedType();
263 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
264 unsigned Align =
265 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
266 AI->getAlignment());
267
268 TySize *= CUI->getZExtValue(); // Get total allocated size.
269 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
270 StaticAllocaMap[AI] =
271 MF.getFrameInfo()->CreateStackObject(TySize, Align);
272 }
273
274 for (; BB != EB; ++BB)
275 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
276 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
277 if (!isa<AllocaInst>(I) ||
278 !StaticAllocaMap.count(cast<AllocaInst>(I)))
279 InitializeRegForValue(I);
280
281 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
282 // also creates the initial PHI MachineInstrs, though none of the input
283 // operands are populated.
284 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
285 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
286 MBBMap[BB] = MBB;
287 MF.getBasicBlockList().push_back(MBB);
288
289 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
290 // appropriate.
291 PHINode *PN;
292 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
293 if (PN->use_empty()) continue;
294
295 MVT::ValueType VT = TLI.getValueType(PN->getType());
296 unsigned NumRegisters = TLI.getNumRegisters(VT);
297 unsigned PHIReg = ValueMap[PN];
298 assert(PHIReg && "PHI node does not have an assigned virtual register!");
299 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
300 for (unsigned i = 0; i != NumRegisters; ++i)
301 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
302 }
303 }
304}
305
306/// 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 unsigned NumRegisters = TLI.getNumRegisters(VT);
313 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
314
315 unsigned R = MakeReg(RegisterVT);
316 for (unsigned i = 1; i != NumRegisters; ++i)
317 MakeReg(RegisterVT);
318
319 return R;
320}
321
322//===----------------------------------------------------------------------===//
323/// SelectionDAGLowering - This is the common target-independent lowering
324/// implementation that is parameterized by a TargetLowering object.
325/// Also, targets can overload any lowering method.
326///
327namespace llvm {
328class SelectionDAGLowering {
329 MachineBasicBlock *CurMBB;
330
331 DenseMap<const Value*, SDOperand> NodeMap;
332
333 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
334 /// them up and then emit token factor nodes when possible. This allows us to
335 /// get simple disambiguation between loads without worrying about alias
336 /// analysis.
337 std::vector<SDOperand> PendingLoads;
338
339 /// Case - A struct to record the Value for a switch case, and the
340 /// case's target basic block.
341 struct Case {
342 Constant* Low;
343 Constant* High;
344 MachineBasicBlock* BB;
345
346 Case() : Low(0), High(0), BB(0) { }
347 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
348 Low(low), High(high), BB(bb) { }
349 uint64_t size() const {
350 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
351 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
352 return (rHigh - rLow + 1ULL);
353 }
354 };
355
356 struct CaseBits {
357 uint64_t Mask;
358 MachineBasicBlock* BB;
359 unsigned Bits;
360
361 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
362 Mask(mask), BB(bb), Bits(bits) { }
363 };
364
365 typedef std::vector<Case> CaseVector;
366 typedef std::vector<CaseBits> CaseBitsVector;
367 typedef CaseVector::iterator CaseItr;
368 typedef std::pair<CaseItr, CaseItr> CaseRange;
369
370 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
371 /// of conditional branches.
372 struct CaseRec {
373 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
374 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
375
376 /// CaseBB - The MBB in which to emit the compare and branch
377 MachineBasicBlock *CaseBB;
378 /// LT, GE - If nonzero, we know the current case value must be less-than or
379 /// greater-than-or-equal-to these Constants.
380 Constant *LT;
381 Constant *GE;
382 /// Range - A pair of iterators representing the range of case values to be
383 /// processed at this point in the binary search tree.
384 CaseRange Range;
385 };
386
387 typedef std::vector<CaseRec> CaseRecVector;
388
389 /// The comparison function for sorting the switch case values in the vector.
390 /// WARNING: Case ranges should be disjoint!
391 struct CaseCmp {
392 bool operator () (const Case& C1, const Case& C2) {
393 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
394 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
395 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
396 return CI1->getValue().slt(CI2->getValue());
397 }
398 };
399
400 struct CaseBitsCmp {
401 bool operator () (const CaseBits& C1, const CaseBits& C2) {
402 return C1.Bits > C2.Bits;
403 }
404 };
405
406 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
407
408public:
409 // TLI - This is information that describes the available target features we
410 // need for lowering. This indicates when operations are unavailable,
411 // implemented with a libcall, etc.
412 TargetLowering &TLI;
413 SelectionDAG &DAG;
414 const TargetData *TD;
Dan Gohmancc863aa2007-08-27 16:26:13 +0000415 AliasAnalysis &AA;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416
417 /// SwitchCases - Vector of CaseBlock structures used to communicate
418 /// SwitchInst code generation information.
419 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
420 /// JTCases - Vector of JumpTable structures used to communicate
421 /// SwitchInst code generation information.
422 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
423 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
424
425 /// FuncInfo - Information about the function as a whole.
426 ///
427 FunctionLoweringInfo &FuncInfo;
428
429 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohmancc863aa2007-08-27 16:26:13 +0000430 AliasAnalysis &aa,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 FunctionLoweringInfo &funcinfo)
Dan Gohmancc863aa2007-08-27 16:26:13 +0000432 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 FuncInfo(funcinfo) {
434 }
435
436 /// getRoot - Return the current virtual root of the Selection DAG.
437 ///
438 SDOperand getRoot() {
439 if (PendingLoads.empty())
440 return DAG.getRoot();
441
442 if (PendingLoads.size() == 1) {
443 SDOperand Root = PendingLoads[0];
444 DAG.setRoot(Root);
445 PendingLoads.clear();
446 return Root;
447 }
448
449 // Otherwise, we have to make a token factor node.
450 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
451 &PendingLoads[0], PendingLoads.size());
452 PendingLoads.clear();
453 DAG.setRoot(Root);
454 return Root;
455 }
456
457 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
458
459 void visit(Instruction &I) { visit(I.getOpcode(), I); }
460
461 void visit(unsigned Opcode, User &I) {
462 // Note: this doesn't use InstVisitor, because it has to work with
463 // ConstantExpr's in addition to instructions.
464 switch (Opcode) {
465 default: assert(0 && "Unknown instruction type encountered!");
466 abort();
467 // Build the switch statement using the Instruction.def file.
468#define HANDLE_INST(NUM, OPCODE, CLASS) \
469 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
470#include "llvm/Instruction.def"
471 }
472 }
473
474 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
475
476 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
477 const Value *SV, SDOperand Root,
478 bool isVolatile, unsigned Alignment);
479
480 SDOperand getIntPtrConstant(uint64_t Val) {
481 return DAG.getConstant(Val, TLI.getPointerTy());
482 }
483
484 SDOperand getValue(const Value *V);
485
486 void setValue(const Value *V, SDOperand NewN) {
487 SDOperand &N = NodeMap[V];
488 assert(N.Val == 0 && "Already set a value for this node!");
489 N = NewN;
490 }
491
492 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
493 std::set<unsigned> &OutputRegs,
494 std::set<unsigned> &InputRegs);
495
496 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
497 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
498 unsigned Opc);
499 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
500 void ExportFromCurrentBlock(Value *V);
501 void LowerCallTo(Instruction &I,
502 const Type *CalledValueTy, unsigned CallingConv,
503 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
504 MachineBasicBlock *LandingPad = NULL);
505
506 // Terminator instructions.
507 void visitRet(ReturnInst &I);
508 void visitBr(BranchInst &I);
509 void visitSwitch(SwitchInst &I);
510 void visitUnreachable(UnreachableInst &I) { /* noop */ }
511
512 // Helpers for visitSwitch
513 bool handleSmallSwitchRange(CaseRec& CR,
514 CaseRecVector& WorkList,
515 Value* SV,
516 MachineBasicBlock* Default);
517 bool handleJTSwitchCase(CaseRec& CR,
518 CaseRecVector& WorkList,
519 Value* SV,
520 MachineBasicBlock* Default);
521 bool handleBTSplitSwitchCase(CaseRec& CR,
522 CaseRecVector& WorkList,
523 Value* SV,
524 MachineBasicBlock* Default);
525 bool handleBitTestsSwitchCase(CaseRec& CR,
526 CaseRecVector& WorkList,
527 Value* SV,
528 MachineBasicBlock* Default);
529 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
530 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
531 void visitBitTestCase(MachineBasicBlock* NextMBB,
532 unsigned Reg,
533 SelectionDAGISel::BitTestCase &B);
534 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
535 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
536 SelectionDAGISel::JumpTableHeader &JTH);
537
538 // These all get lowered before this pass.
539 void visitInvoke(InvokeInst &I);
540 void visitUnwind(UnwindInst &I);
541
542 void visitBinary(User &I, unsigned OpCode);
543 void visitShift(User &I, unsigned Opcode);
544 void visitAdd(User &I) {
545 if (I.getType()->isFPOrFPVector())
546 visitBinary(I, ISD::FADD);
547 else
548 visitBinary(I, ISD::ADD);
549 }
550 void visitSub(User &I);
551 void visitMul(User &I) {
552 if (I.getType()->isFPOrFPVector())
553 visitBinary(I, ISD::FMUL);
554 else
555 visitBinary(I, ISD::MUL);
556 }
557 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
558 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
559 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
560 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
561 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
562 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
563 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
564 void visitOr (User &I) { visitBinary(I, ISD::OR); }
565 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
566 void visitShl (User &I) { visitShift(I, ISD::SHL); }
567 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
568 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
569 void visitICmp(User &I);
570 void visitFCmp(User &I);
571 // Visit the conversion instructions
572 void visitTrunc(User &I);
573 void visitZExt(User &I);
574 void visitSExt(User &I);
575 void visitFPTrunc(User &I);
576 void visitFPExt(User &I);
577 void visitFPToUI(User &I);
578 void visitFPToSI(User &I);
579 void visitUIToFP(User &I);
580 void visitSIToFP(User &I);
581 void visitPtrToInt(User &I);
582 void visitIntToPtr(User &I);
583 void visitBitCast(User &I);
584
585 void visitExtractElement(User &I);
586 void visitInsertElement(User &I);
587 void visitShuffleVector(User &I);
588
589 void visitGetElementPtr(User &I);
590 void visitSelect(User &I);
591
592 void visitMalloc(MallocInst &I);
593 void visitFree(FreeInst &I);
594 void visitAlloca(AllocaInst &I);
595 void visitLoad(LoadInst &I);
596 void visitStore(StoreInst &I);
597 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
598 void visitCall(CallInst &I);
599 void visitInlineAsm(CallInst &I);
600 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
601 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
602
603 void visitVAStart(CallInst &I);
604 void visitVAArg(VAArgInst &I);
605 void visitVAEnd(CallInst &I);
606 void visitVACopy(CallInst &I);
607
608 void visitMemIntrinsic(CallInst &I, unsigned Op);
609
610 void visitUserOp1(Instruction &I) {
611 assert(0 && "UserOp1 should not exist at instruction selection time!");
612 abort();
613 }
614 void visitUserOp2(Instruction &I) {
615 assert(0 && "UserOp2 should not exist at instruction selection time!");
616 abort();
617 }
618};
619} // end namespace llvm
620
621
622/// getCopyFromParts - Create a value that contains the
623/// specified legal parts combined into the value they represent.
624static SDOperand getCopyFromParts(SelectionDAG &DAG,
625 const SDOperand *Parts,
626 unsigned NumParts,
627 MVT::ValueType PartVT,
628 MVT::ValueType ValueVT,
629 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
630 if (!MVT::isVector(ValueVT) || NumParts == 1) {
631 SDOperand Val = Parts[0];
632
633 // If the value was expanded, copy from the top part.
634 if (NumParts > 1) {
635 assert(NumParts == 2 &&
636 "Cannot expand to more than 2 elts yet!");
637 SDOperand Hi = Parts[1];
638 if (!DAG.getTargetLoweringInfo().isLittleEndian())
639 std::swap(Val, Hi);
640 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
641 }
642
643 // Otherwise, if the value was promoted or extended, truncate it to the
644 // appropriate type.
645 if (PartVT == ValueVT)
646 return Val;
647
648 if (MVT::isVector(PartVT)) {
649 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
650 return DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
651 }
652
653 if (MVT::isInteger(PartVT) &&
654 MVT::isInteger(ValueVT)) {
655 if (ValueVT < PartVT) {
656 // For a truncate, see if we have any information to
657 // indicate whether the truncated bits will always be
658 // zero or sign-extension.
659 if (AssertOp != ISD::DELETED_NODE)
660 Val = DAG.getNode(AssertOp, PartVT, Val,
661 DAG.getValueType(ValueVT));
662 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
663 } else {
664 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
665 }
666 }
667
668 if (MVT::isFloatingPoint(PartVT) &&
669 MVT::isFloatingPoint(ValueVT))
670 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
671
672 if (MVT::getSizeInBits(PartVT) ==
673 MVT::getSizeInBits(ValueVT))
674 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
675
676 assert(0 && "Unknown mismatch!");
677 }
678
679 // Handle a multi-element vector.
680 MVT::ValueType IntermediateVT, RegisterVT;
681 unsigned NumIntermediates;
682 unsigned NumRegs =
683 DAG.getTargetLoweringInfo()
684 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
685 RegisterVT);
686
687 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
688 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
689 assert(RegisterVT == Parts[0].getValueType() &&
690 "Part type doesn't match part!");
691
692 // Assemble the parts into intermediate operands.
693 SmallVector<SDOperand, 8> Ops(NumIntermediates);
694 if (NumIntermediates == NumParts) {
695 // If the register was not expanded, truncate or copy the value,
696 // as appropriate.
697 for (unsigned i = 0; i != NumParts; ++i)
698 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
699 PartVT, IntermediateVT);
700 } else if (NumParts > 0) {
701 // If the intermediate type was expanded, build the intermediate operands
702 // from the parts.
Dan Gohman90cfc9d2007-07-30 19:09:17 +0000703 assert(NumParts % NumIntermediates == 0 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704 "Must expand into a divisible number of parts!");
Dan Gohman90cfc9d2007-07-30 19:09:17 +0000705 unsigned Factor = NumParts / NumIntermediates;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 for (unsigned i = 0; i != NumIntermediates; ++i)
707 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
708 PartVT, IntermediateVT);
709 }
710
711 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
712 // operands.
713 return DAG.getNode(MVT::isVector(IntermediateVT) ?
714 ISD::CONCAT_VECTORS :
715 ISD::BUILD_VECTOR,
Dan Gohman90cfc9d2007-07-30 19:09:17 +0000716 ValueVT, &Ops[0], NumIntermediates);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717}
718
719/// getCopyToParts - Create a series of nodes that contain the
720/// specified value split into legal parts.
721static void getCopyToParts(SelectionDAG &DAG,
722 SDOperand Val,
723 SDOperand *Parts,
724 unsigned NumParts,
725 MVT::ValueType PartVT) {
Dan Gohmanf7b05132007-08-10 14:59:38 +0000726 TargetLowering &TLI = DAG.getTargetLoweringInfo();
727 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000728 MVT::ValueType ValueVT = Val.getValueType();
729
730 if (!MVT::isVector(ValueVT) || NumParts == 1) {
731 // If the value was expanded, copy from the parts.
732 if (NumParts > 1) {
733 for (unsigned i = 0; i != NumParts; ++i)
734 Parts[i] = DAG.getNode(ISD::EXTRACT_ELEMENT, PartVT, Val,
Dan Gohmanf7b05132007-08-10 14:59:38 +0000735 DAG.getConstant(i, PtrVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 if (!DAG.getTargetLoweringInfo().isLittleEndian())
737 std::reverse(Parts, Parts + NumParts);
738 return;
739 }
740
741 // If there is a single part and the types differ, this must be
742 // a promotion.
743 if (PartVT != ValueVT) {
744 if (MVT::isVector(PartVT)) {
745 assert(MVT::isVector(ValueVT) &&
746 "Not a vector-vector cast?");
747 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
748 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
749 if (PartVT < ValueVT)
750 Val = DAG.getNode(ISD::TRUNCATE, PartVT, Val);
751 else
752 Val = DAG.getNode(ISD::ANY_EXTEND, PartVT, Val);
753 } else if (MVT::isFloatingPoint(PartVT) &&
754 MVT::isFloatingPoint(ValueVT)) {
755 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
756 } else if (MVT::getSizeInBits(PartVT) ==
757 MVT::getSizeInBits(ValueVT)) {
758 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
759 } else {
760 assert(0 && "Unknown mismatch!");
761 }
762 }
763 Parts[0] = Val;
764 return;
765 }
766
767 // Handle a multi-element vector.
768 MVT::ValueType IntermediateVT, RegisterVT;
769 unsigned NumIntermediates;
770 unsigned NumRegs =
771 DAG.getTargetLoweringInfo()
772 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
773 RegisterVT);
774 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
775
776 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
777 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
778
779 // Split the vector into intermediate operands.
780 SmallVector<SDOperand, 8> Ops(NumIntermediates);
781 for (unsigned i = 0; i != NumIntermediates; ++i)
782 if (MVT::isVector(IntermediateVT))
783 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
784 IntermediateVT, Val,
785 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohmanf7b05132007-08-10 14:59:38 +0000786 PtrVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 else
788 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
789 IntermediateVT, Val,
Dan Gohmanf7b05132007-08-10 14:59:38 +0000790 DAG.getConstant(i, PtrVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000791
792 // Split the intermediate operands into legal parts.
793 if (NumParts == NumIntermediates) {
794 // If the register was not expanded, promote or copy the value,
795 // as appropriate.
796 for (unsigned i = 0; i != NumParts; ++i)
797 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
798 } else if (NumParts > 0) {
799 // If the intermediate type was expanded, split each the value into
800 // legal parts.
801 assert(NumParts % NumIntermediates == 0 &&
802 "Must expand into a divisible number of parts!");
803 unsigned Factor = NumParts / NumIntermediates;
804 for (unsigned i = 0; i != NumIntermediates; ++i)
805 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
806 }
807}
808
809
810SDOperand SelectionDAGLowering::getValue(const Value *V) {
811 SDOperand &N = NodeMap[V];
812 if (N.Val) return N;
813
814 const Type *VTy = V->getType();
815 MVT::ValueType VT = TLI.getValueType(VTy);
816 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
817 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
818 visit(CE->getOpcode(), *CE);
819 SDOperand N1 = NodeMap[V];
820 assert(N1.Val && "visit didn't populate the ValueMap!");
821 return N1;
822 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
823 return N = DAG.getGlobalAddress(GV, VT);
824 } else if (isa<ConstantPointerNull>(C)) {
825 return N = DAG.getConstant(0, TLI.getPointerTy());
826 } else if (isa<UndefValue>(C)) {
827 if (!isa<VectorType>(VTy))
828 return N = DAG.getNode(ISD::UNDEF, VT);
829
830 // Create a BUILD_VECTOR of undef nodes.
831 const VectorType *PTy = cast<VectorType>(VTy);
832 unsigned NumElements = PTy->getNumElements();
833 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
834
835 SmallVector<SDOperand, 8> Ops;
836 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
837
838 // Create a VConstant node with generic Vector type.
839 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
840 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
841 &Ops[0], Ops.size());
842 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000843 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
845 unsigned NumElements = PTy->getNumElements();
846 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
847
848 // Now that we know the number and type of the elements, push a
849 // Constant or ConstantFP node onto the ops list for each element of
850 // the vector constant.
851 SmallVector<SDOperand, 8> Ops;
852 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
853 for (unsigned i = 0; i != NumElements; ++i)
854 Ops.push_back(getValue(CP->getOperand(i)));
855 } else {
856 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
857 SDOperand Op;
858 if (MVT::isFloatingPoint(PVT))
859 Op = DAG.getConstantFP(0, PVT);
860 else
861 Op = DAG.getConstant(0, PVT);
862 Ops.assign(NumElements, Op);
863 }
864
865 // Create a BUILD_VECTOR node.
866 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
867 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
868 Ops.size());
869 } else {
870 // Canonicalize all constant ints to be unsigned.
871 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
872 }
873 }
874
875 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
876 std::map<const AllocaInst*, int>::iterator SI =
877 FuncInfo.StaticAllocaMap.find(AI);
878 if (SI != FuncInfo.StaticAllocaMap.end())
879 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
880 }
881
882 unsigned InReg = FuncInfo.ValueMap[V];
883 assert(InReg && "Value not in map!");
884
885 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
886 unsigned NumRegs = TLI.getNumRegisters(VT);
887
888 std::vector<unsigned> Regs(NumRegs);
889 for (unsigned i = 0; i != NumRegs; ++i)
890 Regs[i] = InReg + i;
891
892 RegsForValue RFV(Regs, RegisterVT, VT);
893 SDOperand Chain = DAG.getEntryNode();
894
895 return RFV.getCopyFromRegs(DAG, Chain, NULL);
896}
897
898
899void SelectionDAGLowering::visitRet(ReturnInst &I) {
900 if (I.getNumOperands() == 0) {
901 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
902 return;
903 }
904 SmallVector<SDOperand, 8> NewValues;
905 NewValues.push_back(getRoot());
906 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
907 SDOperand RetOp = getValue(I.getOperand(i));
908
909 // If this is an integer return value, we need to promote it ourselves to
910 // the full width of a register, since getCopyToParts and Legalize will use
911 // ANY_EXTEND rather than sign/zero.
912 // FIXME: C calling convention requires the return type to be promoted to
913 // at least 32-bit. But this is not necessary for non-C calling conventions.
914 if (MVT::isInteger(RetOp.getValueType()) &&
915 RetOp.getValueType() < MVT::i64) {
916 MVT::ValueType TmpVT;
917 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
918 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
919 else
920 TmpVT = MVT::i32;
921 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
922 const ParamAttrsList *Attrs = FTy->getParamAttrs();
923 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
924 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
925 ExtendKind = ISD::SIGN_EXTEND;
926 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
927 ExtendKind = ISD::ZERO_EXTEND;
928 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
929 NewValues.push_back(RetOp);
930 NewValues.push_back(DAG.getConstant(false, MVT::i32));
931 } else {
932 MVT::ValueType VT = RetOp.getValueType();
933 unsigned NumParts = TLI.getNumRegisters(VT);
934 MVT::ValueType PartVT = TLI.getRegisterType(VT);
935 SmallVector<SDOperand, 4> Parts(NumParts);
936 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT);
937 for (unsigned i = 0; i < NumParts; ++i) {
938 NewValues.push_back(Parts[i]);
939 NewValues.push_back(DAG.getConstant(false, MVT::i32));
940 }
941 }
942 }
943 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
944 &NewValues[0], NewValues.size()));
945}
946
947/// ExportFromCurrentBlock - If this condition isn't known to be exported from
948/// the current basic block, add it to ValueMap now so that we'll get a
949/// CopyTo/FromReg.
950void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
951 // No need to export constants.
952 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
953
954 // Already exported?
955 if (FuncInfo.isExportedInst(V)) return;
956
957 unsigned Reg = FuncInfo.InitializeRegForValue(V);
958 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
959}
960
961bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
962 const BasicBlock *FromBB) {
963 // The operands of the setcc have to be in this block. We don't know
964 // how to export them from some other block.
965 if (Instruction *VI = dyn_cast<Instruction>(V)) {
966 // Can export from current BB.
967 if (VI->getParent() == FromBB)
968 return true;
969
970 // Is already exported, noop.
971 return FuncInfo.isExportedInst(V);
972 }
973
974 // If this is an argument, we can export it if the BB is the entry block or
975 // if it is already exported.
976 if (isa<Argument>(V)) {
977 if (FromBB == &FromBB->getParent()->getEntryBlock())
978 return true;
979
980 // Otherwise, can only export this if it is already exported.
981 return FuncInfo.isExportedInst(V);
982 }
983
984 // Otherwise, constants can always be exported.
985 return true;
986}
987
988static bool InBlock(const Value *V, const BasicBlock *BB) {
989 if (const Instruction *I = dyn_cast<Instruction>(V))
990 return I->getParent() == BB;
991 return true;
992}
993
994/// FindMergedConditions - If Cond is an expression like
995void SelectionDAGLowering::FindMergedConditions(Value *Cond,
996 MachineBasicBlock *TBB,
997 MachineBasicBlock *FBB,
998 MachineBasicBlock *CurBB,
999 unsigned Opc) {
1000 // If this node is not part of the or/and tree, emit it as a branch.
1001 Instruction *BOp = dyn_cast<Instruction>(Cond);
1002
1003 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1004 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1005 BOp->getParent() != CurBB->getBasicBlock() ||
1006 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1007 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1008 const BasicBlock *BB = CurBB->getBasicBlock();
1009
1010 // If the leaf of the tree is a comparison, merge the condition into
1011 // the caseblock.
1012 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1013 // The operands of the cmp have to be in this block. We don't know
1014 // how to export them from some other block. If this is the first block
1015 // of the sequence, no exporting is needed.
1016 (CurBB == CurMBB ||
1017 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1018 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1019 BOp = cast<Instruction>(Cond);
1020 ISD::CondCode Condition;
1021 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1022 switch (IC->getPredicate()) {
1023 default: assert(0 && "Unknown icmp predicate opcode!");
1024 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1025 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1026 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1027 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1028 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1029 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1030 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1031 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1032 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1033 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1034 }
1035 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1036 ISD::CondCode FPC, FOC;
1037 switch (FC->getPredicate()) {
1038 default: assert(0 && "Unknown fcmp predicate opcode!");
1039 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1040 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1041 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1042 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1043 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1044 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1045 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1046 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1047 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1048 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1049 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1050 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1051 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1052 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1053 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1054 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1055 }
1056 if (FiniteOnlyFPMath())
1057 Condition = FOC;
1058 else
1059 Condition = FPC;
1060 } else {
1061 Condition = ISD::SETEQ; // silence warning.
1062 assert(0 && "Unknown compare instruction");
1063 }
1064
1065 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1066 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1067 SwitchCases.push_back(CB);
1068 return;
1069 }
1070
1071 // Create a CaseBlock record representing this branch.
1072 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1073 NULL, TBB, FBB, CurBB);
1074 SwitchCases.push_back(CB);
1075 return;
1076 }
1077
1078
1079 // Create TmpBB after CurBB.
1080 MachineFunction::iterator BBI = CurBB;
1081 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1082 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1083
1084 if (Opc == Instruction::Or) {
1085 // Codegen X | Y as:
1086 // jmp_if_X TBB
1087 // jmp TmpBB
1088 // TmpBB:
1089 // jmp_if_Y TBB
1090 // jmp FBB
1091 //
1092
1093 // Emit the LHS condition.
1094 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1095
1096 // Emit the RHS condition into TmpBB.
1097 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1098 } else {
1099 assert(Opc == Instruction::And && "Unknown merge op!");
1100 // Codegen X & Y as:
1101 // jmp_if_X TmpBB
1102 // jmp FBB
1103 // TmpBB:
1104 // jmp_if_Y TBB
1105 // jmp FBB
1106 //
1107 // This requires creation of TmpBB after CurBB.
1108
1109 // Emit the LHS condition.
1110 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1111
1112 // Emit the RHS condition into TmpBB.
1113 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1114 }
1115}
1116
1117/// If the set of cases should be emitted as a series of branches, return true.
1118/// If we should emit this as a bunch of and/or'd together conditions, return
1119/// false.
1120static bool
1121ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1122 if (Cases.size() != 2) return true;
1123
1124 // If this is two comparisons of the same values or'd or and'd together, they
1125 // will get folded into a single comparison, so don't emit two blocks.
1126 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1127 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1128 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1129 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1130 return false;
1131 }
1132
1133 return true;
1134}
1135
1136void SelectionDAGLowering::visitBr(BranchInst &I) {
1137 // Update machine-CFG edges.
1138 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1139
1140 // Figure out which block is immediately after the current one.
1141 MachineBasicBlock *NextBlock = 0;
1142 MachineFunction::iterator BBI = CurMBB;
1143 if (++BBI != CurMBB->getParent()->end())
1144 NextBlock = BBI;
1145
1146 if (I.isUnconditional()) {
1147 // If this is not a fall-through branch, emit the branch.
1148 if (Succ0MBB != NextBlock)
1149 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1150 DAG.getBasicBlock(Succ0MBB)));
1151
1152 // Update machine-CFG edges.
1153 CurMBB->addSuccessor(Succ0MBB);
1154
1155 return;
1156 }
1157
1158 // If this condition is one of the special cases we handle, do special stuff
1159 // now.
1160 Value *CondVal = I.getCondition();
1161 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1162
1163 // If this is a series of conditions that are or'd or and'd together, emit
1164 // this as a sequence of branches instead of setcc's with and/or operations.
1165 // For example, instead of something like:
1166 // cmp A, B
1167 // C = seteq
1168 // cmp D, E
1169 // F = setle
1170 // or C, F
1171 // jnz foo
1172 // Emit:
1173 // cmp A, B
1174 // je foo
1175 // cmp D, E
1176 // jle foo
1177 //
1178 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1179 if (BOp->hasOneUse() &&
1180 (BOp->getOpcode() == Instruction::And ||
1181 BOp->getOpcode() == Instruction::Or)) {
1182 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1183 // If the compares in later blocks need to use values not currently
1184 // exported from this block, export them now. This block should always
1185 // be the first entry.
1186 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1187
1188 // Allow some cases to be rejected.
1189 if (ShouldEmitAsBranches(SwitchCases)) {
1190 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1191 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1192 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1193 }
1194
1195 // Emit the branch for this block.
1196 visitSwitchCase(SwitchCases[0]);
1197 SwitchCases.erase(SwitchCases.begin());
1198 return;
1199 }
1200
1201 // Okay, we decided not to do this, remove any inserted MBB's and clear
1202 // SwitchCases.
1203 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1204 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1205
1206 SwitchCases.clear();
1207 }
1208 }
1209
1210 // Create a CaseBlock record representing this branch.
1211 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1212 NULL, Succ0MBB, Succ1MBB, CurMBB);
1213 // Use visitSwitchCase to actually insert the fast branch sequence for this
1214 // cond branch.
1215 visitSwitchCase(CB);
1216}
1217
1218/// visitSwitchCase - Emits the necessary code to represent a single node in
1219/// the binary search tree resulting from lowering a switch instruction.
1220void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1221 SDOperand Cond;
1222 SDOperand CondLHS = getValue(CB.CmpLHS);
1223
1224 // Build the setcc now.
1225 if (CB.CmpMHS == NULL) {
1226 // Fold "(X == true)" to X and "(X == false)" to !X to
1227 // handle common cases produced by branch lowering.
1228 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1229 Cond = CondLHS;
1230 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1231 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1232 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1233 } else
1234 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1235 } else {
1236 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1237
1238 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1239 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1240
1241 SDOperand CmpOp = getValue(CB.CmpMHS);
1242 MVT::ValueType VT = CmpOp.getValueType();
1243
1244 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1245 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1246 } else {
1247 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1248 Cond = DAG.getSetCC(MVT::i1, SUB,
1249 DAG.getConstant(High-Low, VT), ISD::SETULE);
1250 }
1251
1252 }
1253
1254 // Set NextBlock to be the MBB immediately after the current one, if any.
1255 // This is used to avoid emitting unnecessary branches to the next block.
1256 MachineBasicBlock *NextBlock = 0;
1257 MachineFunction::iterator BBI = CurMBB;
1258 if (++BBI != CurMBB->getParent()->end())
1259 NextBlock = BBI;
1260
1261 // If the lhs block is the next block, invert the condition so that we can
1262 // fall through to the lhs instead of the rhs block.
1263 if (CB.TrueBB == NextBlock) {
1264 std::swap(CB.TrueBB, CB.FalseBB);
1265 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1266 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1267 }
1268 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1269 DAG.getBasicBlock(CB.TrueBB));
1270 if (CB.FalseBB == NextBlock)
1271 DAG.setRoot(BrCond);
1272 else
1273 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1274 DAG.getBasicBlock(CB.FalseBB)));
1275 // Update successor info
1276 CurMBB->addSuccessor(CB.TrueBB);
1277 CurMBB->addSuccessor(CB.FalseBB);
1278}
1279
1280/// visitJumpTable - Emit JumpTable node in the current MBB
1281void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1282 // Emit the code for the jump table
1283 assert(JT.Reg != -1U && "Should lower JT Header first!");
1284 MVT::ValueType PTy = TLI.getPointerTy();
1285 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1286 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1287 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1288 Table, Index));
1289 return;
1290}
1291
1292/// visitJumpTableHeader - This function emits necessary code to produce index
1293/// in the JumpTable from switch case.
1294void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1295 SelectionDAGISel::JumpTableHeader &JTH) {
1296 // Subtract the lowest switch case value from the value being switched on
1297 // and conditional branch to default mbb if the result is greater than the
1298 // difference between smallest and largest cases.
1299 SDOperand SwitchOp = getValue(JTH.SValue);
1300 MVT::ValueType VT = SwitchOp.getValueType();
1301 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1302 DAG.getConstant(JTH.First, VT));
1303
1304 // The SDNode we just created, which holds the value being switched on
1305 // minus the the smallest case value, needs to be copied to a virtual
1306 // register so it can be used as an index into the jump table in a
1307 // subsequent basic block. This value may be smaller or larger than the
1308 // target's pointer type, and therefore require extension or truncating.
1309 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
1310 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1311 else
1312 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1313
1314 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1315 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1316 JT.Reg = JumpTableReg;
1317
1318 // Emit the range check for the jump table, and branch to the default
1319 // block for the switch statement if the value being switched on exceeds
1320 // the largest case in the switch.
1321 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1322 DAG.getConstant(JTH.Last-JTH.First,VT),
1323 ISD::SETUGT);
1324
1325 // Set NextBlock to be the MBB immediately after the current one, if any.
1326 // This is used to avoid emitting unnecessary branches to the next block.
1327 MachineBasicBlock *NextBlock = 0;
1328 MachineFunction::iterator BBI = CurMBB;
1329 if (++BBI != CurMBB->getParent()->end())
1330 NextBlock = BBI;
1331
1332 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1333 DAG.getBasicBlock(JT.Default));
1334
1335 if (JT.MBB == NextBlock)
1336 DAG.setRoot(BrCond);
1337 else
1338 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1339 DAG.getBasicBlock(JT.MBB)));
1340
1341 return;
1342}
1343
1344/// visitBitTestHeader - This function emits necessary code to produce value
1345/// suitable for "bit tests"
1346void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1347 // Subtract the minimum value
1348 SDOperand SwitchOp = getValue(B.SValue);
1349 MVT::ValueType VT = SwitchOp.getValueType();
1350 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1351 DAG.getConstant(B.First, VT));
1352
1353 // Check range
1354 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1355 DAG.getConstant(B.Range, VT),
1356 ISD::SETUGT);
1357
1358 SDOperand ShiftOp;
1359 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
1360 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1361 else
1362 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1363
1364 // Make desired shift
1365 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1366 DAG.getConstant(1, TLI.getPointerTy()),
1367 ShiftOp);
1368
1369 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1370 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1371 B.Reg = SwitchReg;
1372
1373 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1374 DAG.getBasicBlock(B.Default));
1375
1376 // Set NextBlock to be the MBB immediately after the current one, if any.
1377 // This is used to avoid emitting unnecessary branches to the next block.
1378 MachineBasicBlock *NextBlock = 0;
1379 MachineFunction::iterator BBI = CurMBB;
1380 if (++BBI != CurMBB->getParent()->end())
1381 NextBlock = BBI;
1382
1383 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1384 if (MBB == NextBlock)
1385 DAG.setRoot(BrRange);
1386 else
1387 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1388 DAG.getBasicBlock(MBB)));
1389
1390 CurMBB->addSuccessor(B.Default);
1391 CurMBB->addSuccessor(MBB);
1392
1393 return;
1394}
1395
1396/// visitBitTestCase - this function produces one "bit test"
1397void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1398 unsigned Reg,
1399 SelectionDAGISel::BitTestCase &B) {
1400 // Emit bit tests and jumps
1401 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1402
1403 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1404 SwitchVal,
1405 DAG.getConstant(B.Mask,
1406 TLI.getPointerTy()));
1407 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1408 DAG.getConstant(0, TLI.getPointerTy()),
1409 ISD::SETNE);
1410 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1411 AndCmp, DAG.getBasicBlock(B.TargetBB));
1412
1413 // Set NextBlock to be the MBB immediately after the current one, if any.
1414 // This is used to avoid emitting unnecessary branches to the next block.
1415 MachineBasicBlock *NextBlock = 0;
1416 MachineFunction::iterator BBI = CurMBB;
1417 if (++BBI != CurMBB->getParent()->end())
1418 NextBlock = BBI;
1419
1420 if (NextMBB == NextBlock)
1421 DAG.setRoot(BrAnd);
1422 else
1423 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1424 DAG.getBasicBlock(NextMBB)));
1425
1426 CurMBB->addSuccessor(B.TargetBB);
1427 CurMBB->addSuccessor(NextMBB);
1428
1429 return;
1430}
1431
1432void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1433 // Retrieve successors.
1434 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1435 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1436
1437 LowerCallTo(I, I.getCalledValue()->getType(),
1438 I.getCallingConv(),
1439 false,
1440 getValue(I.getOperand(0)),
1441 3, LandingPad);
1442
1443 // If the value of the invoke is used outside of its defining block, make it
1444 // available as a virtual register.
1445 if (!I.use_empty()) {
1446 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1447 if (VMI != FuncInfo.ValueMap.end())
1448 DAG.setRoot(CopyValueToVirtualRegister(&I, VMI->second));
1449 }
1450
1451 // Drop into normal successor.
1452 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1453 DAG.getBasicBlock(Return)));
1454
1455 // Update successor info
1456 CurMBB->addSuccessor(Return);
1457 CurMBB->addSuccessor(LandingPad);
1458}
1459
1460void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1461}
1462
1463/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1464/// small case ranges).
1465bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1466 CaseRecVector& WorkList,
1467 Value* SV,
1468 MachineBasicBlock* Default) {
1469 Case& BackCase = *(CR.Range.second-1);
1470
1471 // Size is the number of Cases represented by this range.
1472 unsigned Size = CR.Range.second - CR.Range.first;
1473 if (Size > 3)
1474 return false;
1475
1476 // Get the MachineFunction which holds the current MBB. This is used when
1477 // inserting any additional MBBs necessary to represent the switch.
1478 MachineFunction *CurMF = CurMBB->getParent();
1479
1480 // Figure out which block is immediately after the current one.
1481 MachineBasicBlock *NextBlock = 0;
1482 MachineFunction::iterator BBI = CR.CaseBB;
1483
1484 if (++BBI != CurMBB->getParent()->end())
1485 NextBlock = BBI;
1486
1487 // TODO: If any two of the cases has the same destination, and if one value
1488 // is the same as the other, but has one bit unset that the other has set,
1489 // use bit manipulation to do two compares at once. For example:
1490 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1491
1492 // Rearrange the case blocks so that the last one falls through if possible.
1493 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1494 // The last case block won't fall through into 'NextBlock' if we emit the
1495 // branches in this order. See if rearranging a case value would help.
1496 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1497 if (I->BB == NextBlock) {
1498 std::swap(*I, BackCase);
1499 break;
1500 }
1501 }
1502 }
1503
1504 // Create a CaseBlock record representing a conditional branch to
1505 // the Case's target mbb if the value being switched on SV is equal
1506 // to C.
1507 MachineBasicBlock *CurBlock = CR.CaseBB;
1508 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1509 MachineBasicBlock *FallThrough;
1510 if (I != E-1) {
1511 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1512 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1513 } else {
1514 // If the last case doesn't match, go to the default block.
1515 FallThrough = Default;
1516 }
1517
1518 Value *RHS, *LHS, *MHS;
1519 ISD::CondCode CC;
1520 if (I->High == I->Low) {
1521 // This is just small small case range :) containing exactly 1 case
1522 CC = ISD::SETEQ;
1523 LHS = SV; RHS = I->High; MHS = NULL;
1524 } else {
1525 CC = ISD::SETLE;
1526 LHS = I->Low; MHS = SV; RHS = I->High;
1527 }
1528 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1529 I->BB, FallThrough, CurBlock);
1530
1531 // If emitting the first comparison, just call visitSwitchCase to emit the
1532 // code into the current block. Otherwise, push the CaseBlock onto the
1533 // vector to be later processed by SDISel, and insert the node's MBB
1534 // before the next MBB.
1535 if (CurBlock == CurMBB)
1536 visitSwitchCase(CB);
1537 else
1538 SwitchCases.push_back(CB);
1539
1540 CurBlock = FallThrough;
1541 }
1542
1543 return true;
1544}
1545
1546static inline bool areJTsAllowed(const TargetLowering &TLI) {
1547 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1548 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1549}
1550
1551/// handleJTSwitchCase - Emit jumptable for current switch case range
1552bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1553 CaseRecVector& WorkList,
1554 Value* SV,
1555 MachineBasicBlock* Default) {
1556 Case& FrontCase = *CR.Range.first;
1557 Case& BackCase = *(CR.Range.second-1);
1558
1559 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1560 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1561
1562 uint64_t TSize = 0;
1563 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1564 I!=E; ++I)
1565 TSize += I->size();
1566
1567 if (!areJTsAllowed(TLI) || TSize <= 3)
1568 return false;
1569
1570 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1571 if (Density < 0.4)
1572 return false;
1573
1574 DOUT << "Lowering jump table\n"
1575 << "First entry: " << First << ". Last entry: " << Last << "\n"
1576 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1577
1578 // Get the MachineFunction which holds the current MBB. This is used when
1579 // inserting any additional MBBs necessary to represent the switch.
1580 MachineFunction *CurMF = CurMBB->getParent();
1581
1582 // Figure out which block is immediately after the current one.
1583 MachineBasicBlock *NextBlock = 0;
1584 MachineFunction::iterator BBI = CR.CaseBB;
1585
1586 if (++BBI != CurMBB->getParent()->end())
1587 NextBlock = BBI;
1588
1589 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1590
1591 // Create a new basic block to hold the code for loading the address
1592 // of the jump table, and jumping to it. Update successor information;
1593 // we will either branch to the default case for the switch, or the jump
1594 // table.
1595 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1596 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1597 CR.CaseBB->addSuccessor(Default);
1598 CR.CaseBB->addSuccessor(JumpTableBB);
1599
1600 // Build a vector of destination BBs, corresponding to each target
1601 // of the jump table. If the value of the jump table slot corresponds to
1602 // a case statement, push the case's BB onto the vector, otherwise, push
1603 // the default BB.
1604 std::vector<MachineBasicBlock*> DestBBs;
1605 int64_t TEI = First;
1606 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1607 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1608 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1609
1610 if ((Low <= TEI) && (TEI <= High)) {
1611 DestBBs.push_back(I->BB);
1612 if (TEI==High)
1613 ++I;
1614 } else {
1615 DestBBs.push_back(Default);
1616 }
1617 }
1618
1619 // Update successor info. Add one edge to each unique successor.
1620 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1621 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1622 E = DestBBs.end(); I != E; ++I) {
1623 if (!SuccsHandled[(*I)->getNumber()]) {
1624 SuccsHandled[(*I)->getNumber()] = true;
1625 JumpTableBB->addSuccessor(*I);
1626 }
1627 }
1628
1629 // Create a jump table index for this jump table, or return an existing
1630 // one.
1631 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1632
1633 // Set the jump table information so that we can codegen it as a second
1634 // MachineBasicBlock
1635 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1636 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1637 (CR.CaseBB == CurMBB));
1638 if (CR.CaseBB == CurMBB)
1639 visitJumpTableHeader(JT, JTH);
1640
1641 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1642
1643 return true;
1644}
1645
1646/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1647/// 2 subtrees.
1648bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1649 CaseRecVector& WorkList,
1650 Value* SV,
1651 MachineBasicBlock* Default) {
1652 // Get the MachineFunction which holds the current MBB. This is used when
1653 // inserting any additional MBBs necessary to represent the switch.
1654 MachineFunction *CurMF = CurMBB->getParent();
1655
1656 // Figure out which block is immediately after the current one.
1657 MachineBasicBlock *NextBlock = 0;
1658 MachineFunction::iterator BBI = CR.CaseBB;
1659
1660 if (++BBI != CurMBB->getParent()->end())
1661 NextBlock = BBI;
1662
1663 Case& FrontCase = *CR.Range.first;
1664 Case& BackCase = *(CR.Range.second-1);
1665 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1666
1667 // Size is the number of Cases represented by this range.
1668 unsigned Size = CR.Range.second - CR.Range.first;
1669
1670 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1671 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1672 double FMetric = 0;
1673 CaseItr Pivot = CR.Range.first + Size/2;
1674
1675 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1676 // (heuristically) allow us to emit JumpTable's later.
1677 uint64_t TSize = 0;
1678 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1679 I!=E; ++I)
1680 TSize += I->size();
1681
1682 uint64_t LSize = FrontCase.size();
1683 uint64_t RSize = TSize-LSize;
1684 DOUT << "Selecting best pivot: \n"
1685 << "First: " << First << ", Last: " << Last <<"\n"
1686 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1687 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1688 J!=E; ++I, ++J) {
1689 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1690 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1691 assert((RBegin-LEnd>=1) && "Invalid case distance");
1692 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1693 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1694 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1695 // Should always split in some non-trivial place
1696 DOUT <<"=>Step\n"
1697 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1698 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1699 << "Metric: " << Metric << "\n";
1700 if (FMetric < Metric) {
1701 Pivot = J;
1702 FMetric = Metric;
1703 DOUT << "Current metric set to: " << FMetric << "\n";
1704 }
1705
1706 LSize += J->size();
1707 RSize -= J->size();
1708 }
1709 if (areJTsAllowed(TLI)) {
1710 // If our case is dense we *really* should handle it earlier!
1711 assert((FMetric > 0) && "Should handle dense range earlier!");
1712 } else {
1713 Pivot = CR.Range.first + Size/2;
1714 }
1715
1716 CaseRange LHSR(CR.Range.first, Pivot);
1717 CaseRange RHSR(Pivot, CR.Range.second);
1718 Constant *C = Pivot->Low;
1719 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1720
1721 // We know that we branch to the LHS if the Value being switched on is
1722 // less than the Pivot value, C. We use this to optimize our binary
1723 // tree a bit, by recognizing that if SV is greater than or equal to the
1724 // LHS's Case Value, and that Case Value is exactly one less than the
1725 // Pivot's Value, then we can branch directly to the LHS's Target,
1726 // rather than creating a leaf node for it.
1727 if ((LHSR.second - LHSR.first) == 1 &&
1728 LHSR.first->High == CR.GE &&
1729 cast<ConstantInt>(C)->getSExtValue() ==
1730 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1731 TrueBB = LHSR.first->BB;
1732 } else {
1733 TrueBB = new MachineBasicBlock(LLVMBB);
1734 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1735 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1736 }
1737
1738 // Similar to the optimization above, if the Value being switched on is
1739 // known to be less than the Constant CR.LT, and the current Case Value
1740 // is CR.LT - 1, then we can branch directly to the target block for
1741 // the current Case Value, rather than emitting a RHS leaf node for it.
1742 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1743 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1744 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1745 FalseBB = RHSR.first->BB;
1746 } else {
1747 FalseBB = new MachineBasicBlock(LLVMBB);
1748 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1749 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1750 }
1751
1752 // Create a CaseBlock record representing a conditional branch to
1753 // the LHS node if the value being switched on SV is less than C.
1754 // Otherwise, branch to LHS.
1755 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1756 TrueBB, FalseBB, CR.CaseBB);
1757
1758 if (CR.CaseBB == CurMBB)
1759 visitSwitchCase(CB);
1760 else
1761 SwitchCases.push_back(CB);
1762
1763 return true;
1764}
1765
1766/// handleBitTestsSwitchCase - if current case range has few destination and
1767/// range span less, than machine word bitwidth, encode case range into series
1768/// of masks and emit bit tests with these masks.
1769bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1770 CaseRecVector& WorkList,
1771 Value* SV,
1772 MachineBasicBlock* Default){
1773 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
1774
1775 Case& FrontCase = *CR.Range.first;
1776 Case& BackCase = *(CR.Range.second-1);
1777
1778 // Get the MachineFunction which holds the current MBB. This is used when
1779 // inserting any additional MBBs necessary to represent the switch.
1780 MachineFunction *CurMF = CurMBB->getParent();
1781
1782 unsigned numCmps = 0;
1783 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1784 I!=E; ++I) {
1785 // Single case counts one, case range - two.
1786 if (I->Low == I->High)
1787 numCmps +=1;
1788 else
1789 numCmps +=2;
1790 }
1791
1792 // Count unique destinations
1793 SmallSet<MachineBasicBlock*, 4> Dests;
1794 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1795 Dests.insert(I->BB);
1796 if (Dests.size() > 3)
1797 // Don't bother the code below, if there are too much unique destinations
1798 return false;
1799 }
1800 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1801 << "Total number of comparisons: " << numCmps << "\n";
1802
1803 // Compute span of values.
1804 Constant* minValue = FrontCase.Low;
1805 Constant* maxValue = BackCase.High;
1806 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1807 cast<ConstantInt>(minValue)->getSExtValue();
1808 DOUT << "Compare range: " << range << "\n"
1809 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1810 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1811
1812 if (range>=IntPtrBits ||
1813 (!(Dests.size() == 1 && numCmps >= 3) &&
1814 !(Dests.size() == 2 && numCmps >= 5) &&
1815 !(Dests.size() >= 3 && numCmps >= 6)))
1816 return false;
1817
1818 DOUT << "Emitting bit tests\n";
1819 int64_t lowBound = 0;
1820
1821 // Optimize the case where all the case values fit in a
1822 // word without having to subtract minValue. In this case,
1823 // we can optimize away the subtraction.
1824 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1825 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1826 range = cast<ConstantInt>(maxValue)->getSExtValue();
1827 } else {
1828 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1829 }
1830
1831 CaseBitsVector CasesBits;
1832 unsigned i, count = 0;
1833
1834 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1835 MachineBasicBlock* Dest = I->BB;
1836 for (i = 0; i < count; ++i)
1837 if (Dest == CasesBits[i].BB)
1838 break;
1839
1840 if (i == count) {
1841 assert((count < 3) && "Too much destinations to test!");
1842 CasesBits.push_back(CaseBits(0, Dest, 0));
1843 count++;
1844 }
1845
1846 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1847 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1848
1849 for (uint64_t j = lo; j <= hi; j++) {
1850 CasesBits[i].Mask |= 1ULL << j;
1851 CasesBits[i].Bits++;
1852 }
1853
1854 }
1855 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1856
1857 SelectionDAGISel::BitTestInfo BTC;
1858
1859 // Figure out which block is immediately after the current one.
1860 MachineFunction::iterator BBI = CR.CaseBB;
1861 ++BBI;
1862
1863 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1864
1865 DOUT << "Cases:\n";
1866 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1867 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1868 << ", BB: " << CasesBits[i].BB << "\n";
1869
1870 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1871 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1872 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1873 CaseBB,
1874 CasesBits[i].BB));
1875 }
1876
1877 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
1878 -1U, (CR.CaseBB == CurMBB),
1879 CR.CaseBB, Default, BTC);
1880
1881 if (CR.CaseBB == CurMBB)
1882 visitBitTestHeader(BTB);
1883
1884 BitTestCases.push_back(BTB);
1885
1886 return true;
1887}
1888
1889
1890// Clusterify - Transform simple list of Cases into list of CaseRange's
1891unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1892 const SwitchInst& SI) {
1893 unsigned numCmps = 0;
1894
1895 // Start with "simple" cases
1896 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1897 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1898 Cases.push_back(Case(SI.getSuccessorValue(i),
1899 SI.getSuccessorValue(i),
1900 SMBB));
1901 }
1902 sort(Cases.begin(), Cases.end(), CaseCmp());
1903
1904 // Merge case into clusters
1905 if (Cases.size()>=2)
1906 // Must recompute end() each iteration because it may be
1907 // invalidated by erase if we hold on to it
1908 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1909 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1910 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1911 MachineBasicBlock* nextBB = J->BB;
1912 MachineBasicBlock* currentBB = I->BB;
1913
1914 // If the two neighboring cases go to the same destination, merge them
1915 // into a single case.
1916 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1917 I->High = J->High;
1918 J = Cases.erase(J);
1919 } else {
1920 I = J++;
1921 }
1922 }
1923
1924 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1925 if (I->Low != I->High)
1926 // A range counts double, since it requires two compares.
1927 ++numCmps;
1928 }
1929
1930 return numCmps;
1931}
1932
1933void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1934 // Figure out which block is immediately after the current one.
1935 MachineBasicBlock *NextBlock = 0;
1936 MachineFunction::iterator BBI = CurMBB;
1937
1938 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1939
1940 // If there is only the default destination, branch to it if it is not the
1941 // next basic block. Otherwise, just fall through.
1942 if (SI.getNumOperands() == 2) {
1943 // Update machine-CFG edges.
1944
1945 // If this is not a fall-through branch, emit the branch.
1946 if (Default != NextBlock)
1947 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1948 DAG.getBasicBlock(Default)));
1949
1950 CurMBB->addSuccessor(Default);
1951 return;
1952 }
1953
1954 // If there are any non-default case statements, create a vector of Cases
1955 // representing each one, and sort the vector so that we can efficiently
1956 // create a binary search tree from them.
1957 CaseVector Cases;
1958 unsigned numCmps = Clusterify(Cases, SI);
1959 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1960 << ". Total compares: " << numCmps << "\n";
1961
1962 // Get the Value to be switched on and default basic blocks, which will be
1963 // inserted into CaseBlock records, representing basic blocks in the binary
1964 // search tree.
1965 Value *SV = SI.getOperand(0);
1966
1967 // Push the initial CaseRec onto the worklist
1968 CaseRecVector WorkList;
1969 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1970
1971 while (!WorkList.empty()) {
1972 // Grab a record representing a case range to process off the worklist
1973 CaseRec CR = WorkList.back();
1974 WorkList.pop_back();
1975
1976 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1977 continue;
1978
1979 // If the range has few cases (two or less) emit a series of specific
1980 // tests.
1981 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1982 continue;
1983
1984 // If the switch has more than 5 blocks, and at least 40% dense, and the
1985 // target supports indirect branches, then emit a jump table rather than
1986 // lowering the switch to a binary tree of conditional branches.
1987 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1988 continue;
1989
1990 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1991 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1992 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
1993 }
1994}
1995
1996
1997void SelectionDAGLowering::visitSub(User &I) {
1998 // -0.0 - X --> fneg
1999 const Type *Ty = I.getType();
2000 if (isa<VectorType>(Ty)) {
2001 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2002 const VectorType *DestTy = cast<VectorType>(I.getType());
2003 const Type *ElTy = DestTy->getElementType();
2004 if (ElTy->isFloatingPoint()) {
2005 unsigned VL = DestTy->getNumElements();
Dale Johannesenb9de9f02007-09-06 18:13:44 +00002006 std::vector<Constant*> NZ(VL, ConstantFP::get(ElTy,
2007 ElTy==Type::FloatTy ? APFloat(-0.0f) : APFloat(-0.0)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002008 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2009 if (CV == CNZ) {
2010 SDOperand Op2 = getValue(I.getOperand(1));
2011 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2012 return;
2013 }
2014 }
2015 }
2016 }
2017 if (Ty->isFloatingPoint()) {
2018 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2019 if (CFP->isExactlyValue(-0.0)) {
2020 SDOperand Op2 = getValue(I.getOperand(1));
2021 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2022 return;
2023 }
2024 }
2025
2026 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2027}
2028
2029void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2030 SDOperand Op1 = getValue(I.getOperand(0));
2031 SDOperand Op2 = getValue(I.getOperand(1));
2032
2033 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2034}
2035
2036void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2037 SDOperand Op1 = getValue(I.getOperand(0));
2038 SDOperand Op2 = getValue(I.getOperand(1));
2039
2040 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2041 MVT::getSizeInBits(Op2.getValueType()))
2042 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2043 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2044 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2045
2046 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2047}
2048
2049void SelectionDAGLowering::visitICmp(User &I) {
2050 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2051 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2052 predicate = IC->getPredicate();
2053 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2054 predicate = ICmpInst::Predicate(IC->getPredicate());
2055 SDOperand Op1 = getValue(I.getOperand(0));
2056 SDOperand Op2 = getValue(I.getOperand(1));
2057 ISD::CondCode Opcode;
2058 switch (predicate) {
2059 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2060 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2061 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2062 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2063 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2064 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2065 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2066 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2067 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2068 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2069 default:
2070 assert(!"Invalid ICmp predicate value");
2071 Opcode = ISD::SETEQ;
2072 break;
2073 }
2074 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2075}
2076
2077void SelectionDAGLowering::visitFCmp(User &I) {
2078 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2079 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2080 predicate = FC->getPredicate();
2081 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2082 predicate = FCmpInst::Predicate(FC->getPredicate());
2083 SDOperand Op1 = getValue(I.getOperand(0));
2084 SDOperand Op2 = getValue(I.getOperand(1));
2085 ISD::CondCode Condition, FOC, FPC;
2086 switch (predicate) {
2087 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2088 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2089 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2090 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2091 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2092 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2093 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2094 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2095 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2096 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2097 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2098 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2099 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2100 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2101 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2102 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2103 default:
2104 assert(!"Invalid FCmp predicate value");
2105 FOC = FPC = ISD::SETFALSE;
2106 break;
2107 }
2108 if (FiniteOnlyFPMath())
2109 Condition = FOC;
2110 else
2111 Condition = FPC;
2112 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2113}
2114
2115void SelectionDAGLowering::visitSelect(User &I) {
2116 SDOperand Cond = getValue(I.getOperand(0));
2117 SDOperand TrueVal = getValue(I.getOperand(1));
2118 SDOperand FalseVal = getValue(I.getOperand(2));
2119 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2120 TrueVal, FalseVal));
2121}
2122
2123
2124void SelectionDAGLowering::visitTrunc(User &I) {
2125 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2126 SDOperand N = getValue(I.getOperand(0));
2127 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2128 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2129}
2130
2131void SelectionDAGLowering::visitZExt(User &I) {
2132 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2133 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2134 SDOperand N = getValue(I.getOperand(0));
2135 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2136 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2137}
2138
2139void SelectionDAGLowering::visitSExt(User &I) {
2140 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2141 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2142 SDOperand N = getValue(I.getOperand(0));
2143 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2144 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2145}
2146
2147void SelectionDAGLowering::visitFPTrunc(User &I) {
2148 // FPTrunc is never a no-op cast, no need to check
2149 SDOperand N = getValue(I.getOperand(0));
2150 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2151 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2152}
2153
2154void SelectionDAGLowering::visitFPExt(User &I){
2155 // FPTrunc is never a no-op cast, no need to check
2156 SDOperand N = getValue(I.getOperand(0));
2157 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2158 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2159}
2160
2161void SelectionDAGLowering::visitFPToUI(User &I) {
2162 // FPToUI is never a no-op cast, no need to check
2163 SDOperand N = getValue(I.getOperand(0));
2164 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2165 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2166}
2167
2168void SelectionDAGLowering::visitFPToSI(User &I) {
2169 // FPToSI is never a no-op cast, no need to check
2170 SDOperand N = getValue(I.getOperand(0));
2171 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2172 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2173}
2174
2175void SelectionDAGLowering::visitUIToFP(User &I) {
2176 // UIToFP is never a no-op cast, no need to check
2177 SDOperand N = getValue(I.getOperand(0));
2178 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2179 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2180}
2181
2182void SelectionDAGLowering::visitSIToFP(User &I){
2183 // UIToFP is never a no-op cast, no need to check
2184 SDOperand N = getValue(I.getOperand(0));
2185 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2186 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2187}
2188
2189void SelectionDAGLowering::visitPtrToInt(User &I) {
2190 // What to do depends on the size of the integer and the size of the pointer.
2191 // We can either truncate, zero extend, or no-op, accordingly.
2192 SDOperand N = getValue(I.getOperand(0));
2193 MVT::ValueType SrcVT = N.getValueType();
2194 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2195 SDOperand Result;
2196 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2197 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2198 else
2199 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2200 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2201 setValue(&I, Result);
2202}
2203
2204void SelectionDAGLowering::visitIntToPtr(User &I) {
2205 // What to do depends on the size of the integer and the size of the pointer.
2206 // We can either truncate, zero extend, or no-op, accordingly.
2207 SDOperand N = getValue(I.getOperand(0));
2208 MVT::ValueType SrcVT = N.getValueType();
2209 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2210 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2211 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2212 else
2213 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2214 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2215}
2216
2217void SelectionDAGLowering::visitBitCast(User &I) {
2218 SDOperand N = getValue(I.getOperand(0));
2219 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2220
2221 // BitCast assures us that source and destination are the same size so this
2222 // is either a BIT_CONVERT or a no-op.
2223 if (DestVT != N.getValueType())
2224 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2225 else
2226 setValue(&I, N); // noop cast.
2227}
2228
2229void SelectionDAGLowering::visitInsertElement(User &I) {
2230 SDOperand InVec = getValue(I.getOperand(0));
2231 SDOperand InVal = getValue(I.getOperand(1));
2232 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2233 getValue(I.getOperand(2)));
2234
2235 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2236 TLI.getValueType(I.getType()),
2237 InVec, InVal, InIdx));
2238}
2239
2240void SelectionDAGLowering::visitExtractElement(User &I) {
2241 SDOperand InVec = getValue(I.getOperand(0));
2242 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2243 getValue(I.getOperand(1)));
2244 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2245 TLI.getValueType(I.getType()), InVec, InIdx));
2246}
2247
2248void SelectionDAGLowering::visitShuffleVector(User &I) {
2249 SDOperand V1 = getValue(I.getOperand(0));
2250 SDOperand V2 = getValue(I.getOperand(1));
2251 SDOperand Mask = getValue(I.getOperand(2));
2252
2253 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2254 TLI.getValueType(I.getType()),
2255 V1, V2, Mask));
2256}
2257
2258
2259void SelectionDAGLowering::visitGetElementPtr(User &I) {
2260 SDOperand N = getValue(I.getOperand(0));
2261 const Type *Ty = I.getOperand(0)->getType();
2262
2263 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2264 OI != E; ++OI) {
2265 Value *Idx = *OI;
2266 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2267 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2268 if (Field) {
2269 // N = N + Offset
2270 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2271 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2272 getIntPtrConstant(Offset));
2273 }
2274 Ty = StTy->getElementType(Field);
2275 } else {
2276 Ty = cast<SequentialType>(Ty)->getElementType();
2277
2278 // If this is a constant subscript, handle it quickly.
2279 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2280 if (CI->getZExtValue() == 0) continue;
2281 uint64_t Offs =
2282 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2283 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2284 continue;
2285 }
2286
2287 // N = N + Idx * ElementSize;
2288 uint64_t ElementSize = TD->getTypeSize(Ty);
2289 SDOperand IdxN = getValue(Idx);
2290
2291 // If the index is smaller or larger than intptr_t, truncate or extend
2292 // it.
2293 if (IdxN.getValueType() < N.getValueType()) {
2294 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2295 } else if (IdxN.getValueType() > N.getValueType())
2296 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2297
2298 // If this is a multiply by a power of two, turn it into a shl
2299 // immediately. This is a very common case.
2300 if (isPowerOf2_64(ElementSize)) {
2301 unsigned Amt = Log2_64(ElementSize);
2302 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2303 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2304 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2305 continue;
2306 }
2307
2308 SDOperand Scale = getIntPtrConstant(ElementSize);
2309 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2310 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2311 }
2312 }
2313 setValue(&I, N);
2314}
2315
2316void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2317 // If this is a fixed sized alloca in the entry block of the function,
2318 // allocate it statically on the stack.
2319 if (FuncInfo.StaticAllocaMap.count(&I))
2320 return; // getValue will auto-populate this.
2321
2322 const Type *Ty = I.getAllocatedType();
2323 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
2324 unsigned Align =
2325 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2326 I.getAlignment());
2327
2328 SDOperand AllocSize = getValue(I.getArraySize());
2329 MVT::ValueType IntPtr = TLI.getPointerTy();
2330 if (IntPtr < AllocSize.getValueType())
2331 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2332 else if (IntPtr > AllocSize.getValueType())
2333 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2334
2335 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2336 getIntPtrConstant(TySize));
2337
Evan Chenga31dc752007-08-16 23:46:29 +00002338 // Handle alignment. If the requested alignment is less than or equal to
2339 // the stack alignment, ignore it. If the size is greater than or equal to
2340 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002341 unsigned StackAlign =
2342 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Chenga31dc752007-08-16 23:46:29 +00002343 if (Align <= StackAlign)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002344 Align = 0;
Evan Chenga31dc752007-08-16 23:46:29 +00002345
2346 // Round the size of the allocation up to the stack alignment size
2347 // by add SA-1 to the size.
2348 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2349 getIntPtrConstant(StackAlign-1));
2350 // Mask out the low bits for alignment purposes.
2351 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2352 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002353
2354 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
2355 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2356 MVT::Other);
2357 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2358 setValue(&I, DSA);
2359 DAG.setRoot(DSA.getValue(1));
2360
2361 // Inform the Frame Information that we have just allocated a variable-sized
2362 // object.
2363 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2364}
2365
2366void SelectionDAGLowering::visitLoad(LoadInst &I) {
2367 SDOperand Ptr = getValue(I.getOperand(0));
2368
2369 SDOperand Root;
2370 if (I.isVolatile())
2371 Root = getRoot();
2372 else {
2373 // Do not serialize non-volatile loads against each other.
2374 Root = DAG.getRoot();
2375 }
2376
2377 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2378 Root, I.isVolatile(), I.getAlignment()));
2379}
2380
2381SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2382 const Value *SV, SDOperand Root,
2383 bool isVolatile,
2384 unsigned Alignment) {
2385 SDOperand L =
2386 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2387 isVolatile, Alignment);
2388
2389 if (isVolatile)
2390 DAG.setRoot(L.getValue(1));
2391 else
2392 PendingLoads.push_back(L.getValue(1));
2393
2394 return L;
2395}
2396
2397
2398void SelectionDAGLowering::visitStore(StoreInst &I) {
2399 Value *SrcV = I.getOperand(0);
2400 SDOperand Src = getValue(SrcV);
2401 SDOperand Ptr = getValue(I.getOperand(1));
2402 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2403 I.isVolatile(), I.getAlignment()));
2404}
2405
2406/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2407/// access memory and has no other side effects at all.
2408static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2409#define GET_NO_MEMORY_INTRINSICS
2410#include "llvm/Intrinsics.gen"
2411#undef GET_NO_MEMORY_INTRINSICS
2412 return false;
2413}
2414
2415// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2416// have any side-effects or if it only reads memory.
2417static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2418#define GET_SIDE_EFFECT_INFO
2419#include "llvm/Intrinsics.gen"
2420#undef GET_SIDE_EFFECT_INFO
2421 return false;
2422}
2423
2424/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2425/// node.
2426void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2427 unsigned Intrinsic) {
2428 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
2429 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
2430
2431 // Build the operand list.
2432 SmallVector<SDOperand, 8> Ops;
2433 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2434 if (OnlyLoad) {
2435 // We don't need to serialize loads against other loads.
2436 Ops.push_back(DAG.getRoot());
2437 } else {
2438 Ops.push_back(getRoot());
2439 }
2440 }
2441
2442 // Add the intrinsic ID as an integer operand.
2443 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2444
2445 // Add all operands of the call to the operand list.
2446 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2447 SDOperand Op = getValue(I.getOperand(i));
2448 assert(TLI.isTypeLegal(Op.getValueType()) &&
2449 "Intrinsic uses a non-legal type?");
2450 Ops.push_back(Op);
2451 }
2452
2453 std::vector<MVT::ValueType> VTs;
2454 if (I.getType() != Type::VoidTy) {
2455 MVT::ValueType VT = TLI.getValueType(I.getType());
2456 if (MVT::isVector(VT)) {
2457 const VectorType *DestTy = cast<VectorType>(I.getType());
2458 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2459
2460 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2461 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2462 }
2463
2464 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2465 VTs.push_back(VT);
2466 }
2467 if (HasChain)
2468 VTs.push_back(MVT::Other);
2469
2470 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2471
2472 // Create the node.
2473 SDOperand Result;
2474 if (!HasChain)
2475 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2476 &Ops[0], Ops.size());
2477 else if (I.getType() != Type::VoidTy)
2478 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2479 &Ops[0], Ops.size());
2480 else
2481 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2482 &Ops[0], Ops.size());
2483
2484 if (HasChain) {
2485 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2486 if (OnlyLoad)
2487 PendingLoads.push_back(Chain);
2488 else
2489 DAG.setRoot(Chain);
2490 }
2491 if (I.getType() != Type::VoidTy) {
2492 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2493 MVT::ValueType VT = TLI.getValueType(PTy);
2494 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2495 }
2496 setValue(&I, Result);
2497 }
2498}
2499
2500/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2501static GlobalVariable *ExtractTypeInfo (Value *V) {
2502 V = IntrinsicInst::StripPointerCasts(V);
2503 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2504 assert (GV || isa<ConstantPointerNull>(V) &&
2505 "TypeInfo must be a global variable or NULL");
2506 return GV;
2507}
2508
2509/// addCatchInfo - Extract the personality and type infos from an eh.selector
2510/// call, and add them to the specified machine basic block.
2511static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2512 MachineBasicBlock *MBB) {
2513 // Inform the MachineModuleInfo of the personality for this landing pad.
2514 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2515 assert(CE->getOpcode() == Instruction::BitCast &&
2516 isa<Function>(CE->getOperand(0)) &&
2517 "Personality should be a function");
2518 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2519
2520 // Gather all the type infos for this landing pad and pass them along to
2521 // MachineModuleInfo.
2522 std::vector<GlobalVariable *> TyInfo;
2523 unsigned N = I.getNumOperands();
2524
2525 for (unsigned i = N - 1; i > 2; --i) {
2526 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2527 unsigned FilterLength = CI->getZExtValue();
Duncan Sands923fdb12007-08-27 15:47:50 +00002528 unsigned FirstCatch = i + FilterLength + !FilterLength;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002529 assert (FirstCatch <= N && "Invalid filter length");
2530
2531 if (FirstCatch < N) {
2532 TyInfo.reserve(N - FirstCatch);
2533 for (unsigned j = FirstCatch; j < N; ++j)
2534 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2535 MMI->addCatchTypeInfo(MBB, TyInfo);
2536 TyInfo.clear();
2537 }
2538
Duncan Sands923fdb12007-08-27 15:47:50 +00002539 if (!FilterLength) {
2540 // Cleanup.
2541 MMI->addCleanup(MBB);
2542 } else {
2543 // Filter.
2544 TyInfo.reserve(FilterLength - 1);
2545 for (unsigned j = i + 1; j < FirstCatch; ++j)
2546 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2547 MMI->addFilterTypeInfo(MBB, TyInfo);
2548 TyInfo.clear();
2549 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550
2551 N = i;
2552 }
2553 }
2554
2555 if (N > 3) {
2556 TyInfo.reserve(N - 3);
2557 for (unsigned j = 3; j < N; ++j)
2558 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2559 MMI->addCatchTypeInfo(MBB, TyInfo);
2560 }
2561}
2562
2563/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2564/// we want to emit this as a call to a named external function, return the name
2565/// otherwise lower it and return null.
2566const char *
2567SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2568 switch (Intrinsic) {
2569 default:
2570 // By default, turn this into a target intrinsic node.
2571 visitTargetIntrinsic(I, Intrinsic);
2572 return 0;
2573 case Intrinsic::vastart: visitVAStart(I); return 0;
2574 case Intrinsic::vaend: visitVAEnd(I); return 0;
2575 case Intrinsic::vacopy: visitVACopy(I); return 0;
2576 case Intrinsic::returnaddress:
2577 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2578 getValue(I.getOperand(1))));
2579 return 0;
2580 case Intrinsic::frameaddress:
2581 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2582 getValue(I.getOperand(1))));
2583 return 0;
2584 case Intrinsic::setjmp:
2585 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2586 break;
2587 case Intrinsic::longjmp:
2588 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2589 break;
2590 case Intrinsic::memcpy_i32:
2591 case Intrinsic::memcpy_i64:
2592 visitMemIntrinsic(I, ISD::MEMCPY);
2593 return 0;
2594 case Intrinsic::memset_i32:
2595 case Intrinsic::memset_i64:
2596 visitMemIntrinsic(I, ISD::MEMSET);
2597 return 0;
2598 case Intrinsic::memmove_i32:
2599 case Intrinsic::memmove_i64:
2600 visitMemIntrinsic(I, ISD::MEMMOVE);
2601 return 0;
2602
2603 case Intrinsic::dbg_stoppoint: {
2604 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2605 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2606 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2607 SDOperand Ops[5];
2608
2609 Ops[0] = getRoot();
2610 Ops[1] = getValue(SPI.getLineValue());
2611 Ops[2] = getValue(SPI.getColumnValue());
2612
2613 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2614 assert(DD && "Not a debug information descriptor");
2615 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2616
2617 Ops[3] = DAG.getString(CompileUnit->getFileName());
2618 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2619
2620 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2621 }
2622
2623 return 0;
2624 }
2625 case Intrinsic::dbg_region_start: {
2626 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2627 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2628 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2629 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2630 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2631 DAG.getConstant(LabelID, MVT::i32)));
2632 }
2633
2634 return 0;
2635 }
2636 case Intrinsic::dbg_region_end: {
2637 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2638 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2639 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2640 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2641 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2642 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2643 }
2644
2645 return 0;
2646 }
2647 case Intrinsic::dbg_func_start: {
2648 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2649 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2650 if (MMI && FSI.getSubprogram() &&
2651 MMI->Verify(FSI.getSubprogram())) {
2652 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
2653 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2654 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2655 }
2656
2657 return 0;
2658 }
2659 case Intrinsic::dbg_declare: {
2660 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2661 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2662 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
2663 SDOperand AddressOp = getValue(DI.getAddress());
2664 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2665 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
2666 }
2667
2668 return 0;
2669 }
2670
2671 case Intrinsic::eh_exception: {
2672 if (ExceptionHandling) {
2673 if (!CurMBB->isLandingPad()) {
2674 // FIXME: Mark exception register as live in. Hack for PR1508.
2675 unsigned Reg = TLI.getExceptionAddressRegister();
2676 if (Reg) CurMBB->addLiveIn(Reg);
2677 }
2678 // Insert the EXCEPTIONADDR instruction.
2679 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2680 SDOperand Ops[1];
2681 Ops[0] = DAG.getRoot();
2682 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2683 setValue(&I, Op);
2684 DAG.setRoot(Op.getValue(1));
2685 } else {
2686 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2687 }
2688 return 0;
2689 }
2690
2691 case Intrinsic::eh_selector:{
2692 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2693
2694 if (ExceptionHandling && MMI) {
2695 if (CurMBB->isLandingPad())
2696 addCatchInfo(I, MMI, CurMBB);
2697 else {
2698#ifndef NDEBUG
2699 FuncInfo.CatchInfoLost.insert(&I);
2700#endif
2701 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2702 unsigned Reg = TLI.getExceptionSelectorRegister();
2703 if (Reg) CurMBB->addLiveIn(Reg);
2704 }
2705
2706 // Insert the EHSELECTION instruction.
Evan Chenge8d1e2a2007-09-04 20:39:26 +00002707 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002708 SDOperand Ops[2];
2709 Ops[0] = getValue(I.getOperand(1));
2710 Ops[1] = getRoot();
2711 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2712 setValue(&I, Op);
2713 DAG.setRoot(Op.getValue(1));
2714 } else {
2715 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2716 }
2717
2718 return 0;
2719 }
2720
2721 case Intrinsic::eh_typeid_for: {
2722 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2723
2724 if (MMI) {
2725 // Find the type id for the given typeinfo.
2726 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
2727
2728 unsigned TypeID = MMI->getTypeIDFor(GV);
2729 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2730 } else {
2731 // Return something different to eh_selector.
2732 setValue(&I, DAG.getConstant(1, MVT::i32));
2733 }
2734
2735 return 0;
2736 }
2737
2738 case Intrinsic::eh_return: {
2739 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2740
2741 if (MMI && ExceptionHandling) {
2742 MMI->setCallsEHReturn(true);
2743 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2744 MVT::Other,
2745 getRoot(),
2746 getValue(I.getOperand(1)),
2747 getValue(I.getOperand(2))));
2748 } else {
2749 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2750 }
2751
2752 return 0;
2753 }
2754
2755 case Intrinsic::eh_unwind_init: {
2756 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2757 MMI->setCallsUnwindInit(true);
2758 }
2759
2760 return 0;
2761 }
2762
2763 case Intrinsic::eh_dwarf_cfa: {
2764 if (ExceptionHandling) {
2765 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
Anton Korobeynikovb5641a02007-08-23 07:21:06 +00002766 SDOperand CfaArg;
2767 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
2768 CfaArg = DAG.getNode(ISD::TRUNCATE,
2769 TLI.getPointerTy(), getValue(I.getOperand(1)));
2770 else
2771 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
2772 TLI.getPointerTy(), getValue(I.getOperand(1)));
2773
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002774 SDOperand Offset = DAG.getNode(ISD::ADD,
2775 TLI.getPointerTy(),
2776 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
Anton Korobeynikovb5641a02007-08-23 07:21:06 +00002777 TLI.getPointerTy()),
2778 CfaArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779 setValue(&I, DAG.getNode(ISD::ADD,
2780 TLI.getPointerTy(),
2781 DAG.getNode(ISD::FRAMEADDR,
2782 TLI.getPointerTy(),
2783 DAG.getConstant(0,
2784 TLI.getPointerTy())),
2785 Offset));
2786 } else {
2787 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2788 }
2789
2790 return 0;
2791 }
2792
2793 case Intrinsic::sqrt_f32:
2794 case Intrinsic::sqrt_f64:
2795 setValue(&I, DAG.getNode(ISD::FSQRT,
2796 getValue(I.getOperand(1)).getValueType(),
2797 getValue(I.getOperand(1))));
2798 return 0;
2799 case Intrinsic::powi_f32:
2800 case Intrinsic::powi_f64:
2801 setValue(&I, DAG.getNode(ISD::FPOWI,
2802 getValue(I.getOperand(1)).getValueType(),
2803 getValue(I.getOperand(1)),
2804 getValue(I.getOperand(2))));
2805 return 0;
2806 case Intrinsic::pcmarker: {
2807 SDOperand Tmp = getValue(I.getOperand(1));
2808 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2809 return 0;
2810 }
2811 case Intrinsic::readcyclecounter: {
2812 SDOperand Op = getRoot();
2813 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2814 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2815 &Op, 1);
2816 setValue(&I, Tmp);
2817 DAG.setRoot(Tmp.getValue(1));
2818 return 0;
2819 }
2820 case Intrinsic::part_select: {
2821 // Currently not implemented: just abort
2822 assert(0 && "part_select intrinsic not implemented");
2823 abort();
2824 }
2825 case Intrinsic::part_set: {
2826 // Currently not implemented: just abort
2827 assert(0 && "part_set intrinsic not implemented");
2828 abort();
2829 }
2830 case Intrinsic::bswap:
2831 setValue(&I, DAG.getNode(ISD::BSWAP,
2832 getValue(I.getOperand(1)).getValueType(),
2833 getValue(I.getOperand(1))));
2834 return 0;
2835 case Intrinsic::cttz: {
2836 SDOperand Arg = getValue(I.getOperand(1));
2837 MVT::ValueType Ty = Arg.getValueType();
2838 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002839 setValue(&I, result);
2840 return 0;
2841 }
2842 case Intrinsic::ctlz: {
2843 SDOperand Arg = getValue(I.getOperand(1));
2844 MVT::ValueType Ty = Arg.getValueType();
2845 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002846 setValue(&I, result);
2847 return 0;
2848 }
2849 case Intrinsic::ctpop: {
2850 SDOperand Arg = getValue(I.getOperand(1));
2851 MVT::ValueType Ty = Arg.getValueType();
2852 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002853 setValue(&I, result);
2854 return 0;
2855 }
2856 case Intrinsic::stacksave: {
2857 SDOperand Op = getRoot();
2858 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2859 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2860 setValue(&I, Tmp);
2861 DAG.setRoot(Tmp.getValue(1));
2862 return 0;
2863 }
2864 case Intrinsic::stackrestore: {
2865 SDOperand Tmp = getValue(I.getOperand(1));
2866 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2867 return 0;
2868 }
2869 case Intrinsic::prefetch:
2870 // FIXME: Currently discarding prefetches.
2871 return 0;
2872
2873 case Intrinsic::var_annotation:
2874 // Discard annotate attributes
2875 return 0;
Duncan Sands38947cd2007-07-27 12:58:54 +00002876
2877 case Intrinsic::adjust_trampoline: {
2878 SDOperand Arg = getValue(I.getOperand(1));
2879 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMP, TLI.getPointerTy(), Arg));
2880 return 0;
2881 }
2882
2883 case Intrinsic::init_trampoline: {
2884 const Function *F =
2885 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
2886
2887 SDOperand Ops[6];
2888 Ops[0] = getRoot();
2889 Ops[1] = getValue(I.getOperand(1));
2890 Ops[2] = getValue(I.getOperand(2));
2891 Ops[3] = getValue(I.getOperand(3));
2892 Ops[4] = DAG.getSrcValue(I.getOperand(1));
2893 Ops[5] = DAG.getSrcValue(F);
2894
2895 DAG.setRoot(DAG.getNode(ISD::TRAMPOLINE, MVT::Other, Ops, 6));
2896 return 0;
2897 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002898 }
2899}
2900
2901
2902void SelectionDAGLowering::LowerCallTo(Instruction &I,
2903 const Type *CalledValueTy,
2904 unsigned CallingConv,
2905 bool IsTailCall,
2906 SDOperand Callee, unsigned OpIdx,
2907 MachineBasicBlock *LandingPad) {
2908 const PointerType *PT = cast<PointerType>(CalledValueTy);
2909 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2910 const ParamAttrsList *Attrs = FTy->getParamAttrs();
2911 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2912 unsigned BeginLabel = 0, EndLabel = 0;
2913
2914 TargetLowering::ArgListTy Args;
2915 TargetLowering::ArgListEntry Entry;
2916 Args.reserve(I.getNumOperands());
2917 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2918 Value *Arg = I.getOperand(i);
2919 SDOperand ArgNode = getValue(Arg);
2920 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2921
2922 unsigned attrInd = i - OpIdx + 1;
2923 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2924 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2925 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2926 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
Duncan Sands38947cd2007-07-27 12:58:54 +00002927 Entry.isNest = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::Nest);
Rafael Espindolab8bcfcd2007-08-20 15:18:24 +00002928 Entry.isByVal = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ByVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002929 Args.push_back(Entry);
2930 }
2931
Duncan Sands241a0c92007-09-05 11:27:52 +00002932 if (ExceptionHandling && MMI && LandingPad) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002933 // Insert a label before the invoke call to mark the try range. This can be
2934 // used to detect deletion of the invoke via the MachineModuleInfo.
2935 BeginLabel = MMI->NextLabelID();
2936 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2937 DAG.getConstant(BeginLabel, MVT::i32)));
2938 }
2939
2940 std::pair<SDOperand,SDOperand> Result =
2941 TLI.LowerCallTo(getRoot(), I.getType(),
2942 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
2943 FTy->isVarArg(), CallingConv, IsTailCall,
2944 Callee, Args, DAG);
2945 if (I.getType() != Type::VoidTy)
2946 setValue(&I, Result.first);
2947 DAG.setRoot(Result.second);
2948
Duncan Sands241a0c92007-09-05 11:27:52 +00002949 if (ExceptionHandling && MMI && LandingPad) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002950 // Insert a label at the end of the invoke call to mark the try range. This
2951 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2952 EndLabel = MMI->NextLabelID();
2953 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2954 DAG.getConstant(EndLabel, MVT::i32)));
2955
2956 // Inform MachineModuleInfo of range.
2957 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2958 }
2959}
2960
2961
2962void SelectionDAGLowering::visitCall(CallInst &I) {
2963 const char *RenameFn = 0;
2964 if (Function *F = I.getCalledFunction()) {
2965 if (F->isDeclaration())
2966 if (unsigned IID = F->getIntrinsicID()) {
2967 RenameFn = visitIntrinsicCall(I, IID);
2968 if (!RenameFn)
2969 return;
2970 } else { // Not an LLVM intrinsic.
2971 const std::string &Name = F->getName();
2972 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2973 if (I.getNumOperands() == 3 && // Basic sanity checks.
2974 I.getOperand(1)->getType()->isFloatingPoint() &&
2975 I.getType() == I.getOperand(1)->getType() &&
2976 I.getType() == I.getOperand(2)->getType()) {
2977 SDOperand LHS = getValue(I.getOperand(1));
2978 SDOperand RHS = getValue(I.getOperand(2));
2979 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2980 LHS, RHS));
2981 return;
2982 }
2983 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2984 if (I.getNumOperands() == 2 && // Basic sanity checks.
2985 I.getOperand(1)->getType()->isFloatingPoint() &&
2986 I.getType() == I.getOperand(1)->getType()) {
2987 SDOperand Tmp = getValue(I.getOperand(1));
2988 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2989 return;
2990 }
2991 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2992 if (I.getNumOperands() == 2 && // Basic sanity checks.
2993 I.getOperand(1)->getType()->isFloatingPoint() &&
2994 I.getType() == I.getOperand(1)->getType()) {
2995 SDOperand Tmp = getValue(I.getOperand(1));
2996 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2997 return;
2998 }
2999 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
3000 if (I.getNumOperands() == 2 && // Basic sanity checks.
3001 I.getOperand(1)->getType()->isFloatingPoint() &&
3002 I.getType() == I.getOperand(1)->getType()) {
3003 SDOperand Tmp = getValue(I.getOperand(1));
3004 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3005 return;
3006 }
3007 }
3008 }
3009 } else if (isa<InlineAsm>(I.getOperand(0))) {
3010 visitInlineAsm(I);
3011 return;
3012 }
3013
3014 SDOperand Callee;
3015 if (!RenameFn)
3016 Callee = getValue(I.getOperand(0));
3017 else
3018 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3019
3020 LowerCallTo(I, I.getCalledValue()->getType(),
3021 I.getCallingConv(),
3022 I.isTailCall(),
3023 Callee,
3024 1);
3025}
3026
3027
3028/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3029/// this value and returns the result as a ValueVT value. This uses
3030/// Chain/Flag as the input and updates them for the output Chain/Flag.
3031/// If the Flag pointer is NULL, no flag is used.
3032SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3033 SDOperand &Chain, SDOperand *Flag)const{
3034 // Copy the legal parts from the registers.
3035 unsigned NumParts = Regs.size();
3036 SmallVector<SDOperand, 8> Parts(NumParts);
3037 for (unsigned i = 0; i != NumParts; ++i) {
3038 SDOperand Part = Flag ?
3039 DAG.getCopyFromReg(Chain, Regs[i], RegVT, *Flag) :
3040 DAG.getCopyFromReg(Chain, Regs[i], RegVT);
3041 Chain = Part.getValue(1);
3042 if (Flag)
3043 *Flag = Part.getValue(2);
3044 Parts[i] = Part;
3045 }
3046
3047 // Assemble the legal parts into the final value.
3048 return getCopyFromParts(DAG, &Parts[0], NumParts, RegVT, ValueVT);
3049}
3050
3051/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3052/// specified value into the registers specified by this object. This uses
3053/// Chain/Flag as the input and updates them for the output Chain/Flag.
3054/// If the Flag pointer is NULL, no flag is used.
3055void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3056 SDOperand &Chain, SDOperand *Flag) const {
3057 // Get the list of the values's legal parts.
3058 unsigned NumParts = Regs.size();
3059 SmallVector<SDOperand, 8> Parts(NumParts);
3060 getCopyToParts(DAG, Val, &Parts[0], NumParts, RegVT);
3061
3062 // Copy the parts into the registers.
3063 for (unsigned i = 0; i != NumParts; ++i) {
3064 SDOperand Part = Flag ?
3065 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) :
3066 DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3067 Chain = Part.getValue(0);
3068 if (Flag)
3069 *Flag = Part.getValue(1);
3070 }
3071}
3072
3073/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3074/// operand list. This adds the code marker and includes the number of
3075/// values added into it.
3076void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3077 std::vector<SDOperand> &Ops) const {
3078 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3079 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3080 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
3081 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
3082}
3083
3084/// isAllocatableRegister - If the specified register is safe to allocate,
3085/// i.e. it isn't a stack pointer or some other special register, return the
3086/// register class for the register. Otherwise, return null.
3087static const TargetRegisterClass *
3088isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3089 const TargetLowering &TLI, const MRegisterInfo *MRI) {
3090 MVT::ValueType FoundVT = MVT::Other;
3091 const TargetRegisterClass *FoundRC = 0;
3092 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
3093 E = MRI->regclass_end(); RCI != E; ++RCI) {
3094 MVT::ValueType ThisVT = MVT::Other;
3095
3096 const TargetRegisterClass *RC = *RCI;
3097 // If none of the the value types for this register class are valid, we
3098 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3099 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3100 I != E; ++I) {
3101 if (TLI.isTypeLegal(*I)) {
3102 // If we have already found this register in a different register class,
3103 // choose the one with the largest VT specified. For example, on
3104 // PowerPC, we favor f64 register classes over f32.
3105 if (FoundVT == MVT::Other ||
3106 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3107 ThisVT = *I;
3108 break;
3109 }
3110 }
3111 }
3112
3113 if (ThisVT == MVT::Other) continue;
3114
3115 // NOTE: This isn't ideal. In particular, this might allocate the
3116 // frame pointer in functions that need it (due to them not being taken
3117 // out of allocation, because a variable sized allocation hasn't been seen
3118 // yet). This is a slight code pessimization, but should still work.
3119 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3120 E = RC->allocation_order_end(MF); I != E; ++I)
3121 if (*I == Reg) {
3122 // We found a matching register class. Keep looking at others in case
3123 // we find one with larger registers that this physreg is also in.
3124 FoundRC = RC;
3125 FoundVT = ThisVT;
3126 break;
3127 }
3128 }
3129 return FoundRC;
3130}
3131
3132
3133namespace {
3134/// AsmOperandInfo - This contains information for each constraint that we are
3135/// lowering.
3136struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3137 /// ConstraintCode - This contains the actual string for the code, like "m".
3138 std::string ConstraintCode;
3139
3140 /// ConstraintType - Information about the constraint code, e.g. Register,
3141 /// RegisterClass, Memory, Other, Unknown.
3142 TargetLowering::ConstraintType ConstraintType;
3143
3144 /// CallOperand/CallOperandval - If this is the result output operand or a
3145 /// clobber, this is null, otherwise it is the incoming operand to the
3146 /// CallInst. This gets modified as the asm is processed.
3147 SDOperand CallOperand;
3148 Value *CallOperandVal;
3149
3150 /// ConstraintVT - The ValueType for the operand value.
3151 MVT::ValueType ConstraintVT;
3152
3153 /// AssignedRegs - If this is a register or register class operand, this
3154 /// contains the set of register corresponding to the operand.
3155 RegsForValue AssignedRegs;
3156
3157 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3158 : InlineAsm::ConstraintInfo(info),
3159 ConstraintType(TargetLowering::C_Unknown),
3160 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3161 }
3162
3163 void ComputeConstraintToUse(const TargetLowering &TLI);
3164
3165 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3166 /// busy in OutputRegs/InputRegs.
3167 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3168 std::set<unsigned> &OutputRegs,
3169 std::set<unsigned> &InputRegs) const {
3170 if (isOutReg)
3171 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3172 if (isInReg)
3173 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3174 }
3175};
3176} // end anon namespace.
3177
3178/// getConstraintGenerality - Return an integer indicating how general CT is.
3179static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3180 switch (CT) {
3181 default: assert(0 && "Unknown constraint type!");
3182 case TargetLowering::C_Other:
3183 case TargetLowering::C_Unknown:
3184 return 0;
3185 case TargetLowering::C_Register:
3186 return 1;
3187 case TargetLowering::C_RegisterClass:
3188 return 2;
3189 case TargetLowering::C_Memory:
3190 return 3;
3191 }
3192}
3193
3194void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3195 assert(!Codes.empty() && "Must have at least one constraint");
3196
3197 std::string *Current = &Codes[0];
3198 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3199 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3200 ConstraintCode = *Current;
3201 ConstraintType = CurType;
3202 return;
3203 }
3204
3205 unsigned CurGenerality = getConstraintGenerality(CurType);
3206
3207 // If we have multiple constraints, try to pick the most general one ahead
3208 // of time. This isn't a wonderful solution, but handles common cases.
3209 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3210 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3211 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3212 if (ThisGenerality > CurGenerality) {
3213 // This constraint letter is more general than the previous one,
3214 // use it.
3215 CurType = ThisType;
3216 Current = &Codes[j];
3217 CurGenerality = ThisGenerality;
3218 }
3219 }
3220
3221 ConstraintCode = *Current;
3222 ConstraintType = CurType;
3223}
3224
3225
3226void SelectionDAGLowering::
3227GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
3228 std::set<unsigned> &OutputRegs,
3229 std::set<unsigned> &InputRegs) {
3230 // Compute whether this value requires an input register, an output register,
3231 // or both.
3232 bool isOutReg = false;
3233 bool isInReg = false;
3234 switch (OpInfo.Type) {
3235 case InlineAsm::isOutput:
3236 isOutReg = true;
3237
3238 // If this is an early-clobber output, or if there is an input
3239 // constraint that matches this, we need to reserve the input register
3240 // so no other inputs allocate to it.
3241 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3242 break;
3243 case InlineAsm::isInput:
3244 isInReg = true;
3245 isOutReg = false;
3246 break;
3247 case InlineAsm::isClobber:
3248 isOutReg = true;
3249 isInReg = true;
3250 break;
3251 }
3252
3253
3254 MachineFunction &MF = DAG.getMachineFunction();
3255 std::vector<unsigned> Regs;
3256
3257 // If this is a constraint for a single physreg, or a constraint for a
3258 // register class, find it.
3259 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3260 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3261 OpInfo.ConstraintVT);
3262
3263 unsigned NumRegs = 1;
3264 if (OpInfo.ConstraintVT != MVT::Other)
3265 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3266 MVT::ValueType RegVT;
3267 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3268
3269
3270 // If this is a constraint for a specific physical register, like {r17},
3271 // assign it now.
3272 if (PhysReg.first) {
3273 if (OpInfo.ConstraintVT == MVT::Other)
3274 ValueVT = *PhysReg.second->vt_begin();
3275
3276 // Get the actual register value type. This is important, because the user
3277 // may have asked for (e.g.) the AX register in i32 type. We need to
3278 // remember that AX is actually i16 to get the right extension.
3279 RegVT = *PhysReg.second->vt_begin();
3280
3281 // This is a explicit reference to a physical register.
3282 Regs.push_back(PhysReg.first);
3283
3284 // If this is an expanded reference, add the rest of the regs to Regs.
3285 if (NumRegs != 1) {
3286 TargetRegisterClass::iterator I = PhysReg.second->begin();
3287 TargetRegisterClass::iterator E = PhysReg.second->end();
3288 for (; *I != PhysReg.first; ++I)
3289 assert(I != E && "Didn't find reg!");
3290
3291 // Already added the first reg.
3292 --NumRegs; ++I;
3293 for (; NumRegs; --NumRegs, ++I) {
3294 assert(I != E && "Ran out of registers to allocate!");
3295 Regs.push_back(*I);
3296 }
3297 }
3298 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3299 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3300 return;
3301 }
3302
3303 // Otherwise, if this was a reference to an LLVM register class, create vregs
3304 // for this reference.
3305 std::vector<unsigned> RegClassRegs;
3306 const TargetRegisterClass *RC = PhysReg.second;
3307 if (RC) {
3308 // If this is an early clobber or tied register, our regalloc doesn't know
3309 // how to maintain the constraint. If it isn't, go ahead and create vreg
3310 // and let the regalloc do the right thing.
3311 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3312 // If there is some other early clobber and this is an input register,
3313 // then we are forced to pre-allocate the input reg so it doesn't
3314 // conflict with the earlyclobber.
3315 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3316 RegVT = *PhysReg.second->vt_begin();
3317
3318 if (OpInfo.ConstraintVT == MVT::Other)
3319 ValueVT = RegVT;
3320
3321 // Create the appropriate number of virtual registers.
3322 SSARegMap *RegMap = MF.getSSARegMap();
3323 for (; NumRegs; --NumRegs)
3324 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3325
3326 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3327 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3328 return;
3329 }
3330
3331 // Otherwise, we can't allocate it. Let the code below figure out how to
3332 // maintain these constraints.
3333 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3334
3335 } else {
3336 // This is a reference to a register class that doesn't directly correspond
3337 // to an LLVM register class. Allocate NumRegs consecutive, available,
3338 // registers from the class.
3339 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3340 OpInfo.ConstraintVT);
3341 }
3342
3343 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3344 unsigned NumAllocated = 0;
3345 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3346 unsigned Reg = RegClassRegs[i];
3347 // See if this register is available.
3348 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3349 (isInReg && InputRegs.count(Reg))) { // Already used.
3350 // Make sure we find consecutive registers.
3351 NumAllocated = 0;
3352 continue;
3353 }
3354
3355 // Check to see if this register is allocatable (i.e. don't give out the
3356 // stack pointer).
3357 if (RC == 0) {
3358 RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3359 if (!RC) { // Couldn't allocate this register.
3360 // Reset NumAllocated to make sure we return consecutive registers.
3361 NumAllocated = 0;
3362 continue;
3363 }
3364 }
3365
3366 // Okay, this register is good, we can use it.
3367 ++NumAllocated;
3368
3369 // If we allocated enough consecutive registers, succeed.
3370 if (NumAllocated == NumRegs) {
3371 unsigned RegStart = (i-NumAllocated)+1;
3372 unsigned RegEnd = i+1;
3373 // Mark all of the allocated registers used.
3374 for (unsigned i = RegStart; i != RegEnd; ++i)
3375 Regs.push_back(RegClassRegs[i]);
3376
3377 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3378 OpInfo.ConstraintVT);
3379 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3380 return;
3381 }
3382 }
3383
3384 // Otherwise, we couldn't allocate enough registers for this.
3385 return;
3386}
3387
3388
3389/// visitInlineAsm - Handle a call to an InlineAsm object.
3390///
3391void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3392 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
3393
3394 /// ConstraintOperands - Information about all of the constraints.
3395 std::vector<AsmOperandInfo> ConstraintOperands;
3396
3397 SDOperand Chain = getRoot();
3398 SDOperand Flag;
3399
3400 std::set<unsigned> OutputRegs, InputRegs;
3401
3402 // Do a prepass over the constraints, canonicalizing them, and building up the
3403 // ConstraintOperands list.
3404 std::vector<InlineAsm::ConstraintInfo>
3405 ConstraintInfos = IA->ParseConstraints();
3406
3407 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3408 // constraint. If so, we can't let the register allocator allocate any input
3409 // registers, because it will not know to avoid the earlyclobbered output reg.
3410 bool SawEarlyClobber = false;
3411
3412 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
3413 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3414 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3415 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3416
3417 MVT::ValueType OpVT = MVT::Other;
3418
3419 // Compute the value type for each operand.
3420 switch (OpInfo.Type) {
3421 case InlineAsm::isOutput:
3422 if (!OpInfo.isIndirect) {
3423 // The return value of the call is this value. As such, there is no
3424 // corresponding argument.
3425 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3426 OpVT = TLI.getValueType(I.getType());
3427 } else {
3428 OpInfo.CallOperandVal = I.getOperand(OpNo++);
3429 }
3430 break;
3431 case InlineAsm::isInput:
3432 OpInfo.CallOperandVal = I.getOperand(OpNo++);
3433 break;
3434 case InlineAsm::isClobber:
3435 // Nothing to do.
3436 break;
3437 }
3438
3439 // If this is an input or an indirect output, process the call argument.
3440 if (OpInfo.CallOperandVal) {
3441 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3442 const Type *OpTy = OpInfo.CallOperandVal->getType();
3443 // If this is an indirect operand, the operand is a pointer to the
3444 // accessed type.
3445 if (OpInfo.isIndirect)
3446 OpTy = cast<PointerType>(OpTy)->getElementType();
3447
3448 // If OpTy is not a first-class value, it may be a struct/union that we
3449 // can tile with integers.
3450 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3451 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3452 switch (BitSize) {
3453 default: break;
3454 case 1:
3455 case 8:
3456 case 16:
3457 case 32:
3458 case 64:
3459 OpTy = IntegerType::get(BitSize);
3460 break;
3461 }
3462 }
3463
3464 OpVT = TLI.getValueType(OpTy, true);
3465 }
3466
3467 OpInfo.ConstraintVT = OpVT;
3468
3469 // Compute the constraint code and ConstraintType to use.
3470 OpInfo.ComputeConstraintToUse(TLI);
3471
3472 // Keep track of whether we see an earlyclobber.
3473 SawEarlyClobber |= OpInfo.isEarlyClobber;
3474
3475 // If this is a memory input, and if the operand is not indirect, do what we
3476 // need to to provide an address for the memory input.
3477 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3478 !OpInfo.isIndirect) {
3479 assert(OpInfo.Type == InlineAsm::isInput &&
3480 "Can only indirectify direct input operands!");
3481
3482 // Memory operands really want the address of the value. If we don't have
3483 // an indirect input, put it in the constpool if we can, otherwise spill
3484 // it to a stack slot.
3485
3486 // If the operand is a float, integer, or vector constant, spill to a
3487 // constant pool entry to get its address.
3488 Value *OpVal = OpInfo.CallOperandVal;
3489 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3490 isa<ConstantVector>(OpVal)) {
3491 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3492 TLI.getPointerTy());
3493 } else {
3494 // Otherwise, create a stack slot and emit a store to it before the
3495 // asm.
3496 const Type *Ty = OpVal->getType();
3497 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3498 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3499 MachineFunction &MF = DAG.getMachineFunction();
3500 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3501 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3502 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3503 OpInfo.CallOperand = StackSlot;
3504 }
3505
3506 // There is no longer a Value* corresponding to this operand.
3507 OpInfo.CallOperandVal = 0;
3508 // It is now an indirect operand.
3509 OpInfo.isIndirect = true;
3510 }
3511
3512 // If this constraint is for a specific register, allocate it before
3513 // anything else.
3514 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3515 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3516 }
3517 ConstraintInfos.clear();
3518
3519
3520 // Second pass - Loop over all of the operands, assigning virtual or physregs
3521 // to registerclass operands.
3522 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3523 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3524
3525 // C_Register operands have already been allocated, Other/Memory don't need
3526 // to be.
3527 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3528 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3529 }
3530
3531 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3532 std::vector<SDOperand> AsmNodeOperands;
3533 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3534 AsmNodeOperands.push_back(
3535 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3536
3537
3538 // Loop over all of the inputs, copying the operand values into the
3539 // appropriate registers and processing the output regs.
3540 RegsForValue RetValRegs;
3541
3542 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3543 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3544
3545 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3546 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3547
3548 switch (OpInfo.Type) {
3549 case InlineAsm::isOutput: {
3550 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3551 OpInfo.ConstraintType != TargetLowering::C_Register) {
3552 // Memory output, or 'other' output (e.g. 'X' constraint).
3553 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3554
3555 // Add information to the INLINEASM node to know about this output.
3556 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3557 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3558 TLI.getPointerTy()));
3559 AsmNodeOperands.push_back(OpInfo.CallOperand);
3560 break;
3561 }
3562
3563 // Otherwise, this is a register or register class output.
3564
3565 // Copy the output from the appropriate register. Find a register that
3566 // we can use.
3567 if (OpInfo.AssignedRegs.Regs.empty()) {
3568 cerr << "Couldn't allocate output reg for contraint '"
3569 << OpInfo.ConstraintCode << "'!\n";
3570 exit(1);
3571 }
3572
3573 if (!OpInfo.isIndirect) {
3574 // This is the result value of the call.
3575 assert(RetValRegs.Regs.empty() &&
3576 "Cannot have multiple output constraints yet!");
3577 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3578 RetValRegs = OpInfo.AssignedRegs;
3579 } else {
3580 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
3581 OpInfo.CallOperandVal));
3582 }
3583
3584 // Add information to the INLINEASM node to know that this register is
3585 // set.
3586 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3587 AsmNodeOperands);
3588 break;
3589 }
3590 case InlineAsm::isInput: {
3591 SDOperand InOperandVal = OpInfo.CallOperand;
3592
3593 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
3594 // If this is required to match an output register we have already set,
3595 // just use its register.
3596 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
3597
3598 // Scan until we find the definition we already emitted of this operand.
3599 // When we find it, create a RegsForValue operand.
3600 unsigned CurOp = 2; // The first operand.
3601 for (; OperandNo; --OperandNo) {
3602 // Advance to the next operand.
3603 unsigned NumOps =
3604 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3605 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3606 (NumOps & 7) == 4 /*MEM*/) &&
3607 "Skipped past definitions?");
3608 CurOp += (NumOps>>3)+1;
3609 }
3610
3611 unsigned NumOps =
3612 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3613 if ((NumOps & 7) == 2 /*REGDEF*/) {
3614 // Add NumOps>>3 registers to MatchedRegs.
3615 RegsForValue MatchedRegs;
3616 MatchedRegs.ValueVT = InOperandVal.getValueType();
3617 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3618 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3619 unsigned Reg =
3620 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3621 MatchedRegs.Regs.push_back(Reg);
3622 }
3623
3624 // Use the produced MatchedRegs object to
3625 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
3626 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3627 break;
3628 } else {
3629 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3630 assert(0 && "matching constraints for memory operands unimp");
3631 }
3632 }
3633
3634 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
3635 assert(!OpInfo.isIndirect &&
3636 "Don't know how to handle indirect other inputs yet!");
3637
Chris Lattnera531abc2007-08-25 00:47:38 +00003638 std::vector<SDOperand> Ops;
3639 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
3640 Ops, DAG);
3641 if (Ops.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003642 cerr << "Invalid operand for inline asm constraint '"
3643 << OpInfo.ConstraintCode << "'!\n";
3644 exit(1);
3645 }
3646
3647 // Add information to the INLINEASM node to know about this input.
Chris Lattnera531abc2007-08-25 00:47:38 +00003648 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003649 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3650 TLI.getPointerTy()));
Chris Lattnera531abc2007-08-25 00:47:38 +00003651 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003652 break;
3653 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
3654 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
3655 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3656 "Memory operands expect pointer values");
3657
3658 // Add information to the INLINEASM node to know about this input.
3659 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3660 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3661 TLI.getPointerTy()));
3662 AsmNodeOperands.push_back(InOperandVal);
3663 break;
3664 }
3665
3666 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3667 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3668 "Unknown constraint type!");
3669 assert(!OpInfo.isIndirect &&
3670 "Don't know how to handle indirect register inputs yet!");
3671
3672 // Copy the input into the appropriate registers.
3673 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3674 "Couldn't allocate input reg!");
3675
3676 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
3677
3678 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3679 AsmNodeOperands);
3680 break;
3681 }
3682 case InlineAsm::isClobber: {
3683 // Add the clobbered value to the operand list, so that the register
3684 // allocator is aware that the physreg got clobbered.
3685 if (!OpInfo.AssignedRegs.Regs.empty())
3686 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3687 AsmNodeOperands);
3688 break;
3689 }
3690 }
3691 }
3692
3693 // Finish up input operands.
3694 AsmNodeOperands[0] = Chain;
3695 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3696
3697 Chain = DAG.getNode(ISD::INLINEASM,
3698 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
3699 &AsmNodeOperands[0], AsmNodeOperands.size());
3700 Flag = Chain.getValue(1);
3701
3702 // If this asm returns a register value, copy the result from that register
3703 // and set it as the value of the call.
3704 if (!RetValRegs.Regs.empty()) {
3705 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
3706
3707 // If the result of the inline asm is a vector, it may have the wrong
3708 // width/num elts. Make sure to convert it to the right type with
3709 // bit_convert.
3710 if (MVT::isVector(Val.getValueType())) {
3711 const VectorType *VTy = cast<VectorType>(I.getType());
3712 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
3713
3714 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
3715 }
3716
3717 setValue(&I, Val);
3718 }
3719
3720 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3721
3722 // Process indirect outputs, first output all of the flagged copies out of
3723 // physregs.
3724 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
3725 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
3726 Value *Ptr = IndirectStoresToEmit[i].second;
3727 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
3728 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
3729 }
3730
3731 // Emit the non-flagged stores from the physregs.
3732 SmallVector<SDOperand, 8> OutChains;
3733 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
3734 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
3735 getValue(StoresToEmit[i].second),
3736 StoresToEmit[i].second, 0));
3737 if (!OutChains.empty())
3738 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3739 &OutChains[0], OutChains.size());
3740 DAG.setRoot(Chain);
3741}
3742
3743
3744void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3745 SDOperand Src = getValue(I.getOperand(0));
3746
3747 MVT::ValueType IntPtr = TLI.getPointerTy();
3748
3749 if (IntPtr < Src.getValueType())
3750 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3751 else if (IntPtr > Src.getValueType())
3752 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
3753
3754 // Scale the source by the type size.
3755 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
3756 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3757 Src, getIntPtrConstant(ElementSize));
3758
3759 TargetLowering::ArgListTy Args;
3760 TargetLowering::ArgListEntry Entry;
3761 Entry.Node = Src;
3762 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3763 Args.push_back(Entry);
3764
3765 std::pair<SDOperand,SDOperand> Result =
3766 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
3767 DAG.getExternalSymbol("malloc", IntPtr),
3768 Args, DAG);
3769 setValue(&I, Result.first); // Pointers always fit in registers
3770 DAG.setRoot(Result.second);
3771}
3772
3773void SelectionDAGLowering::visitFree(FreeInst &I) {
3774 TargetLowering::ArgListTy Args;
3775 TargetLowering::ArgListEntry Entry;
3776 Entry.Node = getValue(I.getOperand(0));
3777 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3778 Args.push_back(Entry);
3779 MVT::ValueType IntPtr = TLI.getPointerTy();
3780 std::pair<SDOperand,SDOperand> Result =
3781 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
3782 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3783 DAG.setRoot(Result.second);
3784}
3785
3786// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3787// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3788// instructions are special in various ways, which require special support to
3789// insert. The specified MachineInstr is created but not inserted into any
3790// basic blocks, and the scheduler passes ownership of it to this method.
3791MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3792 MachineBasicBlock *MBB) {
3793 cerr << "If a target marks an instruction with "
3794 << "'usesCustomDAGSchedInserter', it must implement "
3795 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
3796 abort();
3797 return 0;
3798}
3799
3800void SelectionDAGLowering::visitVAStart(CallInst &I) {
3801 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3802 getValue(I.getOperand(1)),
3803 DAG.getSrcValue(I.getOperand(1))));
3804}
3805
3806void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
3807 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3808 getValue(I.getOperand(0)),
3809 DAG.getSrcValue(I.getOperand(0)));
3810 setValue(&I, V);
3811 DAG.setRoot(V.getValue(1));
3812}
3813
3814void SelectionDAGLowering::visitVAEnd(CallInst &I) {
3815 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3816 getValue(I.getOperand(1)),
3817 DAG.getSrcValue(I.getOperand(1))));
3818}
3819
3820void SelectionDAGLowering::visitVACopy(CallInst &I) {
3821 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3822 getValue(I.getOperand(1)),
3823 getValue(I.getOperand(2)),
3824 DAG.getSrcValue(I.getOperand(1)),
3825 DAG.getSrcValue(I.getOperand(2))));
3826}
3827
3828/// TargetLowering::LowerArguments - This is the default LowerArguments
3829/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
3830/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3831/// integrated into SDISel.
3832std::vector<SDOperand>
3833TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
3834 const FunctionType *FTy = F.getFunctionType();
3835 const ParamAttrsList *Attrs = FTy->getParamAttrs();
3836 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3837 std::vector<SDOperand> Ops;
3838 Ops.push_back(DAG.getRoot());
3839 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3840 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3841
3842 // Add one result value for each formal argument.
3843 std::vector<MVT::ValueType> RetVals;
3844 unsigned j = 1;
3845 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3846 I != E; ++I, ++j) {
3847 MVT::ValueType VT = getValueType(I->getType());
3848 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3849 unsigned OriginalAlignment =
3850 getTargetData()->getABITypeAlignment(I->getType());
3851
3852 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3853 // that is zero extended!
3854 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
3855 Flags &= ~(ISD::ParamFlags::SExt);
3856 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
3857 Flags |= ISD::ParamFlags::SExt;
3858 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
3859 Flags |= ISD::ParamFlags::InReg;
3860 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
3861 Flags |= ISD::ParamFlags::StructReturn;
Rafael Espindolae4e4d3e2007-08-10 14:44:42 +00003862 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ByVal)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003863 Flags |= ISD::ParamFlags::ByVal;
Rafael Espindolae4e4d3e2007-08-10 14:44:42 +00003864 const PointerType *Ty = cast<PointerType>(I->getType());
3865 const StructType *STy = cast<StructType>(Ty->getElementType());
3866 unsigned StructAlign = Log2_32(getTargetData()->getABITypeAlignment(STy));
3867 unsigned StructSize = getTargetData()->getTypeSize(STy);
3868 Flags |= (StructAlign << ISD::ParamFlags::ByValAlignOffs);
3869 Flags |= (StructSize << ISD::ParamFlags::ByValSizeOffs);
3870 }
Duncan Sands38947cd2007-07-27 12:58:54 +00003871 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::Nest))
3872 Flags |= ISD::ParamFlags::Nest;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003873 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
3874
3875 switch (getTypeAction(VT)) {
3876 default: assert(0 && "Unknown type action!");
3877 case Legal:
3878 RetVals.push_back(VT);
3879 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3880 break;
3881 case Promote:
3882 RetVals.push_back(getTypeToTransformTo(VT));
3883 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3884 break;
3885 case Expand: {
3886 // If this is an illegal type, it needs to be broken up to fit into
3887 // registers.
3888 MVT::ValueType RegisterVT = getRegisterType(VT);
3889 unsigned NumRegs = getNumRegisters(VT);
3890 for (unsigned i = 0; i != NumRegs; ++i) {
3891 RetVals.push_back(RegisterVT);
3892 // if it isn't first piece, alignment must be 1
3893 if (i > 0)
3894 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3895 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3896 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3897 }
3898 break;
3899 }
3900 }
3901 }
3902
3903 RetVals.push_back(MVT::Other);
3904
3905 // Create the node.
3906 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3907 DAG.getNodeValueTypes(RetVals), RetVals.size(),
3908 &Ops[0], Ops.size()).Val;
3909 unsigned NumArgRegs = Result->getNumValues() - 1;
3910 DAG.setRoot(SDOperand(Result, NumArgRegs));
3911
3912 // Set up the return result vector.
3913 Ops.clear();
3914 unsigned i = 0;
3915 unsigned Idx = 1;
3916 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3917 ++I, ++Idx) {
3918 MVT::ValueType VT = getValueType(I->getType());
3919
3920 switch (getTypeAction(VT)) {
3921 default: assert(0 && "Unknown type action!");
3922 case Legal:
3923 Ops.push_back(SDOperand(Result, i++));
3924 break;
3925 case Promote: {
3926 SDOperand Op(Result, i++);
3927 if (MVT::isInteger(VT)) {
3928 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
3929 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3930 DAG.getValueType(VT));
3931 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
3932 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3933 DAG.getValueType(VT));
3934 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3935 } else {
3936 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3937 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3938 }
3939 Ops.push_back(Op);
3940 break;
3941 }
3942 case Expand: {
3943 MVT::ValueType PartVT = getRegisterType(VT);
3944 unsigned NumParts = getNumRegisters(VT);
3945 SmallVector<SDOperand, 4> Parts(NumParts);
3946 for (unsigned j = 0; j != NumParts; ++j)
3947 Parts[j] = SDOperand(Result, i++);
3948 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT));
3949 break;
3950 }
3951 }
3952 }
3953 assert(i == NumArgRegs && "Argument register count mismatch!");
3954 return Ops;
3955}
3956
3957
3958/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3959/// implementation, which just inserts an ISD::CALL node, which is later custom
3960/// lowered by the target to something concrete. FIXME: When all targets are
3961/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3962std::pair<SDOperand, SDOperand>
3963TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3964 bool RetTyIsSigned, bool isVarArg,
3965 unsigned CallingConv, bool isTailCall,
3966 SDOperand Callee,
3967 ArgListTy &Args, SelectionDAG &DAG) {
3968 SmallVector<SDOperand, 32> Ops;
3969 Ops.push_back(Chain); // Op#0 - Chain
3970 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3971 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3972 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3973 Ops.push_back(Callee);
3974
3975 // Handle all of the outgoing arguments.
3976 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3977 MVT::ValueType VT = getValueType(Args[i].Ty);
3978 SDOperand Op = Args[i].Node;
3979 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3980 unsigned OriginalAlignment =
3981 getTargetData()->getABITypeAlignment(Args[i].Ty);
3982
3983 if (Args[i].isSExt)
3984 Flags |= ISD::ParamFlags::SExt;
3985 if (Args[i].isZExt)
3986 Flags |= ISD::ParamFlags::ZExt;
3987 if (Args[i].isInReg)
3988 Flags |= ISD::ParamFlags::InReg;
3989 if (Args[i].isSRet)
3990 Flags |= ISD::ParamFlags::StructReturn;
Rafael Espindolab8bcfcd2007-08-20 15:18:24 +00003991 if (Args[i].isByVal) {
3992 Flags |= ISD::ParamFlags::ByVal;
3993 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
3994 const StructType *STy = cast<StructType>(Ty->getElementType());
3995 unsigned StructAlign = Log2_32(getTargetData()->getABITypeAlignment(STy));
3996 unsigned StructSize = getTargetData()->getTypeSize(STy);
3997 Flags |= (StructAlign << ISD::ParamFlags::ByValAlignOffs);
3998 Flags |= (StructSize << ISD::ParamFlags::ByValSizeOffs);
3999 }
Duncan Sands38947cd2007-07-27 12:58:54 +00004000 if (Args[i].isNest)
4001 Flags |= ISD::ParamFlags::Nest;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004002 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
4003
4004 switch (getTypeAction(VT)) {
4005 default: assert(0 && "Unknown type action!");
4006 case Legal:
4007 Ops.push_back(Op);
4008 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
4009 break;
4010 case Promote:
4011 if (MVT::isInteger(VT)) {
4012 unsigned ExtOp;
4013 if (Args[i].isSExt)
4014 ExtOp = ISD::SIGN_EXTEND;
4015 else if (Args[i].isZExt)
4016 ExtOp = ISD::ZERO_EXTEND;
4017 else
4018 ExtOp = ISD::ANY_EXTEND;
4019 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
4020 } else {
4021 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
4022 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
4023 }
4024 Ops.push_back(Op);
4025 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
4026 break;
4027 case Expand: {
4028 MVT::ValueType PartVT = getRegisterType(VT);
4029 unsigned NumParts = getNumRegisters(VT);
4030 SmallVector<SDOperand, 4> Parts(NumParts);
4031 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT);
4032 for (unsigned i = 0; i != NumParts; ++i) {
4033 // if it isn't first piece, alignment must be 1
4034 unsigned MyFlags = Flags;
4035 if (i != 0)
4036 MyFlags = (MyFlags & (~ISD::ParamFlags::OrigAlignment)) |
4037 (1 << ISD::ParamFlags::OrigAlignmentOffs);
4038
4039 Ops.push_back(Parts[i]);
4040 Ops.push_back(DAG.getConstant(MyFlags, MVT::i32));
4041 }
4042 break;
4043 }
4044 }
4045 }
4046
4047 // Figure out the result value types.
4048 MVT::ValueType VT = getValueType(RetTy);
4049 MVT::ValueType RegisterVT = getRegisterType(VT);
4050 unsigned NumRegs = getNumRegisters(VT);
4051 SmallVector<MVT::ValueType, 4> RetTys(NumRegs);
4052 for (unsigned i = 0; i != NumRegs; ++i)
4053 RetTys[i] = RegisterVT;
4054
4055 RetTys.push_back(MVT::Other); // Always has a chain.
4056
4057 // Create the CALL node.
4058 SDOperand Res = DAG.getNode(ISD::CALL,
4059 DAG.getVTList(&RetTys[0], NumRegs + 1),
4060 &Ops[0], Ops.size());
Chris Lattnerbc1200c2007-08-02 18:08:16 +00004061 Chain = Res.getValue(NumRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004062
4063 // Gather up the call result into a single value.
4064 if (RetTy != Type::VoidTy) {
4065 ISD::NodeType AssertOp = ISD::AssertSext;
4066 if (!RetTyIsSigned)
4067 AssertOp = ISD::AssertZext;
4068 SmallVector<SDOperand, 4> Results(NumRegs);
4069 for (unsigned i = 0; i != NumRegs; ++i)
4070 Results[i] = Res.getValue(i);
4071 Res = getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT, AssertOp);
4072 }
4073
4074 return std::make_pair(Res, Chain);
4075}
4076
4077SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4078 assert(0 && "LowerOperation not implemented for this target!");
4079 abort();
4080 return SDOperand();
4081}
4082
4083SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4084 SelectionDAG &DAG) {
4085 assert(0 && "CustomPromoteOperation not implemented for this target!");
4086 abort();
4087 return SDOperand();
4088}
4089
4090/// getMemsetValue - Vectorized representation of the memset value
4091/// operand.
4092static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
4093 SelectionDAG &DAG) {
4094 MVT::ValueType CurVT = VT;
4095 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4096 uint64_t Val = C->getValue() & 255;
4097 unsigned Shift = 8;
4098 while (CurVT != MVT::i8) {
4099 Val = (Val << Shift) | Val;
4100 Shift <<= 1;
4101 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4102 }
4103 return DAG.getConstant(Val, VT);
4104 } else {
4105 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4106 unsigned Shift = 8;
4107 while (CurVT != MVT::i8) {
4108 Value =
4109 DAG.getNode(ISD::OR, VT,
4110 DAG.getNode(ISD::SHL, VT, Value,
4111 DAG.getConstant(Shift, MVT::i8)), Value);
4112 Shift <<= 1;
4113 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4114 }
4115
4116 return Value;
4117 }
4118}
4119
4120/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4121/// used when a memcpy is turned into a memset when the source is a constant
4122/// string ptr.
4123static SDOperand getMemsetStringVal(MVT::ValueType VT,
4124 SelectionDAG &DAG, TargetLowering &TLI,
4125 std::string &Str, unsigned Offset) {
4126 uint64_t Val = 0;
4127 unsigned MSB = MVT::getSizeInBits(VT) / 8;
4128 if (TLI.isLittleEndian())
4129 Offset = Offset + MSB - 1;
4130 for (unsigned i = 0; i != MSB; ++i) {
4131 Val = (Val << 8) | (unsigned char)Str[Offset];
4132 Offset += TLI.isLittleEndian() ? -1 : 1;
4133 }
4134 return DAG.getConstant(Val, VT);
4135}
4136
4137/// getMemBasePlusOffset - Returns base and offset node for the
4138static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4139 SelectionDAG &DAG, TargetLowering &TLI) {
4140 MVT::ValueType VT = Base.getValueType();
4141 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4142}
4143
4144/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
4145/// to replace the memset / memcpy is below the threshold. It also returns the
4146/// types of the sequence of memory ops to perform memset / memcpy.
4147static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4148 unsigned Limit, uint64_t Size,
4149 unsigned Align, TargetLowering &TLI) {
4150 MVT::ValueType VT;
4151
4152 if (TLI.allowsUnalignedMemoryAccesses()) {
4153 VT = MVT::i64;
4154 } else {
4155 switch (Align & 7) {
4156 case 0:
4157 VT = MVT::i64;
4158 break;
4159 case 4:
4160 VT = MVT::i32;
4161 break;
4162 case 2:
4163 VT = MVT::i16;
4164 break;
4165 default:
4166 VT = MVT::i8;
4167 break;
4168 }
4169 }
4170
4171 MVT::ValueType LVT = MVT::i64;
4172 while (!TLI.isTypeLegal(LVT))
4173 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4174 assert(MVT::isInteger(LVT));
4175
4176 if (VT > LVT)
4177 VT = LVT;
4178
4179 unsigned NumMemOps = 0;
4180 while (Size != 0) {
4181 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4182 while (VTSize > Size) {
4183 VT = (MVT::ValueType)((unsigned)VT - 1);
4184 VTSize >>= 1;
4185 }
4186 assert(MVT::isInteger(VT));
4187
4188 if (++NumMemOps > Limit)
4189 return false;
4190 MemOps.push_back(VT);
4191 Size -= VTSize;
4192 }
4193
4194 return true;
4195}
4196
4197void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
4198 SDOperand Op1 = getValue(I.getOperand(1));
4199 SDOperand Op2 = getValue(I.getOperand(2));
4200 SDOperand Op3 = getValue(I.getOperand(3));
4201 SDOperand Op4 = getValue(I.getOperand(4));
4202 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4203 if (Align == 0) Align = 1;
4204
Dan Gohmancc863aa2007-08-27 16:26:13 +00004205 // If the source and destination are known to not be aliases, we can
4206 // lower memmove as memcpy.
4207 if (Op == ISD::MEMMOVE) {
4208 uint64_t Size = -1;
4209 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
4210 Size = C->getValue();
4211 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
4212 AliasAnalysis::NoAlias)
4213 Op = ISD::MEMCPY;
4214 }
4215
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004216 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4217 std::vector<MVT::ValueType> MemOps;
4218
4219 // Expand memset / memcpy to a series of load / store ops
4220 // if the size operand falls below a certain threshold.
4221 SmallVector<SDOperand, 8> OutChains;
4222 switch (Op) {
4223 default: break; // Do nothing for now.
4224 case ISD::MEMSET: {
4225 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4226 Size->getValue(), Align, TLI)) {
4227 unsigned NumMemOps = MemOps.size();
4228 unsigned Offset = 0;
4229 for (unsigned i = 0; i < NumMemOps; i++) {
4230 MVT::ValueType VT = MemOps[i];
4231 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4232 SDOperand Value = getMemsetValue(Op2, VT, DAG);
4233 SDOperand Store = DAG.getStore(getRoot(), Value,
4234 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
4235 I.getOperand(1), Offset);
4236 OutChains.push_back(Store);
4237 Offset += VTSize;
4238 }
4239 }
4240 break;
4241 }
4242 case ISD::MEMCPY: {
4243 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4244 Size->getValue(), Align, TLI)) {
4245 unsigned NumMemOps = MemOps.size();
4246 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
4247 GlobalAddressSDNode *G = NULL;
4248 std::string Str;
4249 bool CopyFromStr = false;
4250
4251 if (Op2.getOpcode() == ISD::GlobalAddress)
4252 G = cast<GlobalAddressSDNode>(Op2);
4253 else if (Op2.getOpcode() == ISD::ADD &&
4254 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4255 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4256 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
4257 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
4258 }
4259 if (G) {
4260 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
4261 if (GV && GV->isConstant()) {
4262 Str = GV->getStringValue(false);
4263 if (!Str.empty()) {
4264 CopyFromStr = true;
4265 SrcOff += SrcDelta;
4266 }
4267 }
4268 }
4269
4270 for (unsigned i = 0; i < NumMemOps; i++) {
4271 MVT::ValueType VT = MemOps[i];
4272 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4273 SDOperand Value, Chain, Store;
4274
4275 if (CopyFromStr) {
4276 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4277 Chain = getRoot();
4278 Store =
4279 DAG.getStore(Chain, Value,
4280 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4281 I.getOperand(1), DstOff);
4282 } else {
4283 Value = DAG.getLoad(VT, getRoot(),
4284 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
4285 I.getOperand(2), SrcOff);
4286 Chain = Value.getValue(1);
4287 Store =
4288 DAG.getStore(Chain, Value,
4289 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4290 I.getOperand(1), DstOff);
4291 }
4292 OutChains.push_back(Store);
4293 SrcOff += VTSize;
4294 DstOff += VTSize;
4295 }
4296 }
4297 break;
4298 }
4299 }
4300
4301 if (!OutChains.empty()) {
4302 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4303 &OutChains[0], OutChains.size()));
4304 return;
4305 }
4306 }
4307
4308 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
4309}
4310
4311//===----------------------------------------------------------------------===//
4312// SelectionDAGISel code
4313//===----------------------------------------------------------------------===//
4314
4315unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4316 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4317}
4318
4319void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4320 AU.addRequired<AliasAnalysis>();
4321 AU.setPreservesAll();
4322}
4323
4324
4325
4326bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohmancc863aa2007-08-27 16:26:13 +00004327 // Get alias analysis for load/store combining.
4328 AA = &getAnalysis<AliasAnalysis>();
4329
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004330 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4331 RegMap = MF.getSSARegMap();
4332 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4333
4334 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4335
4336 if (ExceptionHandling)
4337 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4338 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4339 // Mark landing pad.
4340 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4341
4342 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4343 SelectBasicBlock(I, MF, FuncInfo);
4344
4345 // Add function live-ins to entry block live-in set.
4346 BasicBlock *EntryBB = &Fn.getEntryBlock();
4347 BB = FuncInfo.MBBMap[EntryBB];
4348 if (!MF.livein_empty())
4349 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4350 E = MF.livein_end(); I != E; ++I)
4351 BB->addLiveIn(I->first);
4352
4353#ifndef NDEBUG
4354 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4355 "Not all catch info was assigned to a landing pad!");
4356#endif
4357
4358 return true;
4359}
4360
4361SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4362 unsigned Reg) {
4363 SDOperand Op = getValue(V);
4364 assert((Op.getOpcode() != ISD::CopyFromReg ||
4365 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4366 "Copy from a reg to the same reg!");
4367
4368 MVT::ValueType SrcVT = Op.getValueType();
4369 MVT::ValueType RegisterVT = TLI.getRegisterType(SrcVT);
4370 unsigned NumRegs = TLI.getNumRegisters(SrcVT);
4371 SmallVector<SDOperand, 8> Regs(NumRegs);
4372 SmallVector<SDOperand, 8> Chains(NumRegs);
4373
4374 // Copy the value by legal parts into sequential virtual registers.
4375 getCopyToParts(DAG, Op, &Regs[0], NumRegs, RegisterVT);
4376 for (unsigned i = 0; i != NumRegs; ++i)
4377 Chains[i] = DAG.getCopyToReg(getRoot(), Reg + i, Regs[i]);
4378 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4379}
4380
4381void SelectionDAGISel::
4382LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
4383 std::vector<SDOperand> &UnorderedChains) {
4384 // If this is the entry block, emit arguments.
4385 Function &F = *LLVMBB->getParent();
4386 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4387 SDOperand OldRoot = SDL.DAG.getRoot();
4388 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4389
4390 unsigned a = 0;
4391 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4392 AI != E; ++AI, ++a)
4393 if (!AI->use_empty()) {
4394 SDL.setValue(AI, Args[a]);
4395
4396 // If this argument is live outside of the entry block, insert a copy from
4397 // whereever we got it to the vreg that other BB's will reference it as.
4398 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4399 if (VMI != FuncInfo.ValueMap.end()) {
4400 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
4401 UnorderedChains.push_back(Copy);
4402 }
4403 }
4404
4405 // Finally, if the target has anything special to do, allow it to do so.
4406 // FIXME: this should insert code into the DAG!
4407 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4408}
4409
4410static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4411 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4412 assert(!FLI.MBBMap[SrcBB]->isLandingPad() &&
4413 "Copying catch info out of a landing pad!");
4414 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4415 if (isSelector(I)) {
4416 // Apply the catch info to DestBB.
4417 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4418#ifndef NDEBUG
4419 FLI.CatchInfoFound.insert(I);
4420#endif
4421 }
4422}
4423
4424void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4425 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4426 FunctionLoweringInfo &FuncInfo) {
Dan Gohmancc863aa2007-08-27 16:26:13 +00004427 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004428
4429 std::vector<SDOperand> UnorderedChains;
4430
4431 // Lower any arguments needed in this block if this is the entry block.
4432 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4433 LowerArguments(LLVMBB, SDL, UnorderedChains);
4434
4435 BB = FuncInfo.MBBMap[LLVMBB];
4436 SDL.setCurrentBasicBlock(BB);
4437
4438 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4439
4440 if (ExceptionHandling && MMI && BB->isLandingPad()) {
4441 // Add a label to mark the beginning of the landing pad. Deletion of the
4442 // landing pad can thus be detected via the MachineModuleInfo.
4443 unsigned LabelID = MMI->addLandingPad(BB);
4444 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4445 DAG.getConstant(LabelID, MVT::i32)));
4446
4447 // Mark exception register as live in.
4448 unsigned Reg = TLI.getExceptionAddressRegister();
4449 if (Reg) BB->addLiveIn(Reg);
4450
4451 // Mark exception selector register as live in.
4452 Reg = TLI.getExceptionSelectorRegister();
4453 if (Reg) BB->addLiveIn(Reg);
4454
4455 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4456 // function and list of typeids logically belong to the invoke (or, if you
4457 // like, the basic block containing the invoke), and need to be associated
4458 // with it in the dwarf exception handling tables. Currently however the
4459 // information is provided by an intrinsic (eh.selector) that can be moved
4460 // to unexpected places by the optimizers: if the unwind edge is critical,
4461 // then breaking it can result in the intrinsics being in the successor of
4462 // the landing pad, not the landing pad itself. This results in exceptions
4463 // not being caught because no typeids are associated with the invoke.
4464 // This may not be the only way things can go wrong, but it is the only way
4465 // we try to work around for the moment.
4466 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4467
4468 if (Br && Br->isUnconditional()) { // Critical edge?
4469 BasicBlock::iterator I, E;
4470 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4471 if (isSelector(I))
4472 break;
4473
4474 if (I == E)
4475 // No catch info found - try to extract some from the successor.
4476 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
4477 }
4478 }
4479
4480 // Lower all of the non-terminator instructions.
4481 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4482 I != E; ++I)
4483 SDL.visit(*I);
4484
4485 // Ensure that all instructions which are used outside of their defining
4486 // blocks are available as virtual registers. Invoke is handled elsewhere.
4487 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4488 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
4489 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4490 if (VMI != FuncInfo.ValueMap.end())
4491 UnorderedChains.push_back(
4492 SDL.CopyValueToVirtualRegister(I, VMI->second));
4493 }
4494
4495 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4496 // ensure constants are generated when needed. Remember the virtual registers
4497 // that need to be added to the Machine PHI nodes as input. We cannot just
4498 // directly add them, because expansion might result in multiple MBB's for one
4499 // BB. As such, the start of the BB might correspond to a different MBB than
4500 // the end.
4501 //
4502 TerminatorInst *TI = LLVMBB->getTerminator();
4503
4504 // Emit constants only once even if used by multiple PHI nodes.
4505 std::map<Constant*, unsigned> ConstantsOut;
4506
4507 // Vector bool would be better, but vector<bool> is really slow.
4508 std::vector<unsigned char> SuccsHandled;
4509 if (TI->getNumSuccessors())
4510 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4511
4512 // Check successor nodes' PHI nodes that expect a constant to be available
4513 // from this block.
4514 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4515 BasicBlock *SuccBB = TI->getSuccessor(succ);
4516 if (!isa<PHINode>(SuccBB->begin())) continue;
4517 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4518
4519 // If this terminator has multiple identical successors (common for
4520 // switches), only handle each succ once.
4521 unsigned SuccMBBNo = SuccMBB->getNumber();
4522 if (SuccsHandled[SuccMBBNo]) continue;
4523 SuccsHandled[SuccMBBNo] = true;
4524
4525 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4526 PHINode *PN;
4527
4528 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4529 // nodes and Machine PHI nodes, but the incoming operands have not been
4530 // emitted yet.
4531 for (BasicBlock::iterator I = SuccBB->begin();
4532 (PN = dyn_cast<PHINode>(I)); ++I) {
4533 // Ignore dead phi's.
4534 if (PN->use_empty()) continue;
4535
4536 unsigned Reg;
4537 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4538
4539 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4540 unsigned &RegOut = ConstantsOut[C];
4541 if (RegOut == 0) {
4542 RegOut = FuncInfo.CreateRegForValue(C);
4543 UnorderedChains.push_back(
4544 SDL.CopyValueToVirtualRegister(C, RegOut));
4545 }
4546 Reg = RegOut;
4547 } else {
4548 Reg = FuncInfo.ValueMap[PHIOp];
4549 if (Reg == 0) {
4550 assert(isa<AllocaInst>(PHIOp) &&
4551 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4552 "Didn't codegen value into a register!??");
4553 Reg = FuncInfo.CreateRegForValue(PHIOp);
4554 UnorderedChains.push_back(
4555 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4556 }
4557 }
4558
4559 // Remember that this register needs to added to the machine PHI node as
4560 // the input for this MBB.
4561 MVT::ValueType VT = TLI.getValueType(PN->getType());
4562 unsigned NumRegisters = TLI.getNumRegisters(VT);
4563 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4564 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4565 }
4566 }
4567 ConstantsOut.clear();
4568
4569 // Turn all of the unordered chains into one factored node.
4570 if (!UnorderedChains.empty()) {
4571 SDOperand Root = SDL.getRoot();
4572 if (Root.getOpcode() != ISD::EntryToken) {
4573 unsigned i = 0, e = UnorderedChains.size();
4574 for (; i != e; ++i) {
4575 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4576 if (UnorderedChains[i].Val->getOperand(0) == Root)
4577 break; // Don't add the root if we already indirectly depend on it.
4578 }
4579
4580 if (i == e)
4581 UnorderedChains.push_back(Root);
4582 }
4583 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4584 &UnorderedChains[0], UnorderedChains.size()));
4585 }
4586
4587 // Lower the terminator after the copies are emitted.
4588 SDL.visit(*LLVMBB->getTerminator());
4589
4590 // Copy over any CaseBlock records that may now exist due to SwitchInst
4591 // lowering, as well as any jump table information.
4592 SwitchCases.clear();
4593 SwitchCases = SDL.SwitchCases;
4594 JTCases.clear();
4595 JTCases = SDL.JTCases;
4596 BitTestCases.clear();
4597 BitTestCases = SDL.BitTestCases;
4598
4599 // Make sure the root of the DAG is up-to-date.
4600 DAG.setRoot(SDL.getRoot());
4601}
4602
4603void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004604 // Run the DAG combiner in pre-legalize mode.
Dan Gohmancc863aa2007-08-27 16:26:13 +00004605 DAG.Combine(false, *AA);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004606
4607 DOUT << "Lowered selection DAG:\n";
4608 DEBUG(DAG.dump());
4609
4610 // Second step, hack on the DAG until it only uses operations and types that
4611 // the target supports.
4612 DAG.Legalize();
4613
4614 DOUT << "Legalized selection DAG:\n";
4615 DEBUG(DAG.dump());
4616
4617 // Run the DAG combiner in post-legalize mode.
Dan Gohmancc863aa2007-08-27 16:26:13 +00004618 DAG.Combine(true, *AA);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004619
4620 if (ViewISelDAGs) DAG.viewGraph();
4621
4622 // Third, instruction select all of the operations to machine code, adding the
4623 // code to the MachineBasicBlock.
4624 InstructionSelectBasicBlock(DAG);
4625
4626 DOUT << "Selected machine code:\n";
4627 DEBUG(BB->dump());
4628}
4629
4630void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4631 FunctionLoweringInfo &FuncInfo) {
4632 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4633 {
4634 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4635 CurDAG = &DAG;
4636
4637 // First step, lower LLVM code to some DAG. This DAG may use operations and
4638 // types that are not supported by the target.
4639 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4640
4641 // Second step, emit the lowered DAG as machine code.
4642 CodeGenAndEmitDAG(DAG);
4643 }
4644
4645 DOUT << "Total amount of phi nodes to update: "
4646 << PHINodesToUpdate.size() << "\n";
4647 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4648 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4649 << ", " << PHINodesToUpdate[i].second << ")\n";);
4650
4651 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4652 // PHI nodes in successors.
4653 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4654 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4655 MachineInstr *PHI = PHINodesToUpdate[i].first;
4656 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4657 "This is not a machine PHI node that we are updating!");
4658 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4659 PHI->addMachineBasicBlockOperand(BB);
4660 }
4661 return;
4662 }
4663
4664 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4665 // Lower header first, if it wasn't already lowered
4666 if (!BitTestCases[i].Emitted) {
4667 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4668 CurDAG = &HSDAG;
Dan Gohmancc863aa2007-08-27 16:26:13 +00004669 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004670 // Set the current basic block to the mbb we wish to insert the code into
4671 BB = BitTestCases[i].Parent;
4672 HSDL.setCurrentBasicBlock(BB);
4673 // Emit the code
4674 HSDL.visitBitTestHeader(BitTestCases[i]);
4675 HSDAG.setRoot(HSDL.getRoot());
4676 CodeGenAndEmitDAG(HSDAG);
4677 }
4678
4679 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4680 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4681 CurDAG = &BSDAG;
Dan Gohmancc863aa2007-08-27 16:26:13 +00004682 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004683 // Set the current basic block to the mbb we wish to insert the code into
4684 BB = BitTestCases[i].Cases[j].ThisBB;
4685 BSDL.setCurrentBasicBlock(BB);
4686 // Emit the code
4687 if (j+1 != ej)
4688 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4689 BitTestCases[i].Reg,
4690 BitTestCases[i].Cases[j]);
4691 else
4692 BSDL.visitBitTestCase(BitTestCases[i].Default,
4693 BitTestCases[i].Reg,
4694 BitTestCases[i].Cases[j]);
4695
4696
4697 BSDAG.setRoot(BSDL.getRoot());
4698 CodeGenAndEmitDAG(BSDAG);
4699 }
4700
4701 // Update PHI Nodes
4702 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4703 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4704 MachineBasicBlock *PHIBB = PHI->getParent();
4705 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4706 "This is not a machine PHI node that we are updating!");
4707 // This is "default" BB. We have two jumps to it. From "header" BB and
4708 // from last "case" BB.
4709 if (PHIBB == BitTestCases[i].Default) {
4710 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4711 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
4712 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4713 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4714 }
4715 // One of "cases" BB.
4716 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4717 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4718 if (cBB->succ_end() !=
4719 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4720 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4721 PHI->addMachineBasicBlockOperand(cBB);
4722 }
4723 }
4724 }
4725 }
4726
4727 // If the JumpTable record is filled in, then we need to emit a jump table.
4728 // Updating the PHI nodes is tricky in this case, since we need to determine
4729 // whether the PHI is a successor of the range check MBB or the jump table MBB
4730 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4731 // Lower header first, if it wasn't already lowered
4732 if (!JTCases[i].first.Emitted) {
4733 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4734 CurDAG = &HSDAG;
Dan Gohmancc863aa2007-08-27 16:26:13 +00004735 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004736 // Set the current basic block to the mbb we wish to insert the code into
4737 BB = JTCases[i].first.HeaderBB;
4738 HSDL.setCurrentBasicBlock(BB);
4739 // Emit the code
4740 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4741 HSDAG.setRoot(HSDL.getRoot());
4742 CodeGenAndEmitDAG(HSDAG);
4743 }
4744
4745 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4746 CurDAG = &JSDAG;
Dan Gohmancc863aa2007-08-27 16:26:13 +00004747 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004748 // Set the current basic block to the mbb we wish to insert the code into
4749 BB = JTCases[i].second.MBB;
4750 JSDL.setCurrentBasicBlock(BB);
4751 // Emit the code
4752 JSDL.visitJumpTable(JTCases[i].second);
4753 JSDAG.setRoot(JSDL.getRoot());
4754 CodeGenAndEmitDAG(JSDAG);
4755
4756 // Update PHI Nodes
4757 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4758 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4759 MachineBasicBlock *PHIBB = PHI->getParent();
4760 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4761 "This is not a machine PHI node that we are updating!");
4762 // "default" BB. We can go there only from header BB.
4763 if (PHIBB == JTCases[i].second.Default) {
4764 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4765 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
4766 }
4767 // JT BB. Just iterate over successors here
4768 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4769 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4770 PHI->addMachineBasicBlockOperand(BB);
4771 }
4772 }
4773 }
4774
4775 // If the switch block involved a branch to one of the actual successors, we
4776 // need to update PHI nodes in that block.
4777 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4778 MachineInstr *PHI = PHINodesToUpdate[i].first;
4779 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4780 "This is not a machine PHI node that we are updating!");
4781 if (BB->isSuccessor(PHI->getParent())) {
4782 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4783 PHI->addMachineBasicBlockOperand(BB);
4784 }
4785 }
4786
4787 // If we generated any switch lowering information, build and codegen any
4788 // additional DAGs necessary.
4789 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4790 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4791 CurDAG = &SDAG;
Dan Gohmancc863aa2007-08-27 16:26:13 +00004792 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004793
4794 // Set the current basic block to the mbb we wish to insert the code into
4795 BB = SwitchCases[i].ThisBB;
4796 SDL.setCurrentBasicBlock(BB);
4797
4798 // Emit the code
4799 SDL.visitSwitchCase(SwitchCases[i]);
4800 SDAG.setRoot(SDL.getRoot());
4801 CodeGenAndEmitDAG(SDAG);
4802
4803 // Handle any PHI nodes in successors of this chunk, as if we were coming
4804 // from the original BB before switch expansion. Note that PHI nodes can
4805 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4806 // handle them the right number of times.
4807 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4808 for (MachineBasicBlock::iterator Phi = BB->begin();
4809 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4810 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4811 for (unsigned pn = 0; ; ++pn) {
4812 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4813 if (PHINodesToUpdate[pn].first == Phi) {
4814 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4815 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4816 break;
4817 }
4818 }
4819 }
4820
4821 // Don't process RHS if same block as LHS.
4822 if (BB == SwitchCases[i].FalseBB)
4823 SwitchCases[i].FalseBB = 0;
4824
4825 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4826 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4827 SwitchCases[i].FalseBB = 0;
4828 }
4829 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4830 }
4831}
4832
4833
4834//===----------------------------------------------------------------------===//
4835/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4836/// target node in the graph.
4837void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4838 if (ViewSchedDAGs) DAG.viewGraph();
4839
4840 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4841
4842 if (!Ctor) {
4843 Ctor = ISHeuristic;
4844 RegisterScheduler::setDefault(Ctor);
4845 }
4846
4847 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4848 BB = SL->Run();
Dan Gohman134c5b62007-08-28 20:32:58 +00004849
4850 if (ViewSUnitDAGs) SL->viewGraph();
4851
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004852 delete SL;
4853}
4854
4855
4856HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4857 return new HazardRecognizer();
4858}
4859
4860//===----------------------------------------------------------------------===//
4861// Helper functions used by the generated instruction selector.
4862//===----------------------------------------------------------------------===//
4863// Calls to these methods are generated by tblgen.
4864
4865/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4866/// the dag combiner simplified the 255, we still want to match. RHS is the
4867/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4868/// specified in the .td file (e.g. 255).
4869bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmand6098272007-07-24 23:00:27 +00004870 int64_t DesiredMaskS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004871 uint64_t ActualMask = RHS->getValue();
4872 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4873
4874 // If the actual mask exactly matches, success!
4875 if (ActualMask == DesiredMask)
4876 return true;
4877
4878 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4879 if (ActualMask & ~DesiredMask)
4880 return false;
4881
4882 // Otherwise, the DAG Combiner may have proven that the value coming in is
4883 // either already zero or is not demanded. Check for known zero input bits.
4884 uint64_t NeededMask = DesiredMask & ~ActualMask;
4885 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
4886 return true;
4887
4888 // TODO: check to see if missing bits are just not demanded.
4889
4890 // Otherwise, this pattern doesn't match.
4891 return false;
4892}
4893
4894/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4895/// the dag combiner simplified the 255, we still want to match. RHS is the
4896/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4897/// specified in the .td file (e.g. 255).
4898bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmand6098272007-07-24 23:00:27 +00004899 int64_t DesiredMaskS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004900 uint64_t ActualMask = RHS->getValue();
4901 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4902
4903 // If the actual mask exactly matches, success!
4904 if (ActualMask == DesiredMask)
4905 return true;
4906
4907 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4908 if (ActualMask & ~DesiredMask)
4909 return false;
4910
4911 // Otherwise, the DAG Combiner may have proven that the value coming in is
4912 // either already zero or is not demanded. Check for known zero input bits.
4913 uint64_t NeededMask = DesiredMask & ~ActualMask;
4914
4915 uint64_t KnownZero, KnownOne;
4916 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4917
4918 // If all the missing bits in the or are already known to be set, match!
4919 if ((NeededMask & KnownOne) == NeededMask)
4920 return true;
4921
4922 // TODO: check to see if missing bits are just not demanded.
4923
4924 // Otherwise, this pattern doesn't match.
4925 return false;
4926}
4927
4928
4929/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4930/// by tblgen. Others should not call it.
4931void SelectionDAGISel::
4932SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4933 std::vector<SDOperand> InOps;
4934 std::swap(InOps, Ops);
4935
4936 Ops.push_back(InOps[0]); // input chain.
4937 Ops.push_back(InOps[1]); // input asm string.
4938
4939 unsigned i = 2, e = InOps.size();
4940 if (InOps[e-1].getValueType() == MVT::Flag)
4941 --e; // Don't process a flag operand if it is here.
4942
4943 while (i != e) {
4944 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4945 if ((Flags & 7) != 4 /*MEM*/) {
4946 // Just skip over this operand, copying the operands verbatim.
4947 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4948 i += (Flags >> 3) + 1;
4949 } else {
4950 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4951 // Otherwise, this is a memory operand. Ask the target to select it.
4952 std::vector<SDOperand> SelOps;
4953 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4954 cerr << "Could not match memory address. Inline asm failure!\n";
4955 exit(1);
4956 }
4957
4958 // Add this to the output node.
4959 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4960 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4961 IntPtrTy));
4962 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4963 i += 2;
4964 }
4965 }
4966
4967 // Add the flag input back if present.
4968 if (e != InOps.size())
4969 Ops.push_back(InOps.back());
4970}
4971
4972char SelectionDAGISel::ID = 0;