1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
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"
52 ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
55 ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
58 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
61 //===---------------------------------------------------------------------===//
63 /// RegisterScheduler class - Track the registration of instruction schedulers.
65 //===---------------------------------------------------------------------===//
66 MachinePassRegistry RegisterScheduler::Registry;
68 //===---------------------------------------------------------------------===//
70 /// ISHeuristic command line option for instruction schedulers.
72 //===---------------------------------------------------------------------===//
74 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
77 cl::init(&createDefaultScheduler),
78 cl::desc("Instruction schedulers available:"));
80 static RegisterScheduler
81 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
86 /// RegsForValue - This struct represents the physical registers that a
87 /// particular value is assigned and the type information about the value.
88 /// This is needed because values can be promoted into larger registers and
89 /// expanded into multiple smaller registers than the value.
90 struct VISIBILITY_HIDDEN RegsForValue {
91 /// Regs - This list hold the register (for legal and promoted values)
92 /// or register set (for expanded values) that the value should be assigned
94 std::vector<unsigned> Regs;
96 /// RegVT - The value type of each register.
100 /// ValueVT - The value type of the LLVM value, which may be promoted from
101 /// RegVT or made from merging the two expanded parts.
102 MVT::ValueType ValueVT;
104 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
107 : RegVT(regvt), ValueVT(valuevt) {
110 RegsForValue(const std::vector<unsigned> ®s,
111 MVT::ValueType regvt, MVT::ValueType valuevt)
112 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
116 /// this value and returns the result as a ValueVT value. This uses
117 /// Chain/Flag as the input and updates them for the output Chain/Flag.
118 SDOperand getCopyFromRegs(SelectionDAG &DAG,
119 SDOperand &Chain, SDOperand &Flag) const;
121 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
122 /// specified value into the registers specified by this object. This uses
123 /// Chain/Flag as the input and updates them for the output Chain/Flag.
124 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
125 SDOperand &Chain, SDOperand &Flag,
126 MVT::ValueType PtrVT) const;
128 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
129 /// operand list. This adds the code marker and includes the number of
130 /// values added into it.
131 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
132 std::vector<SDOperand> &Ops) const;
137 //===--------------------------------------------------------------------===//
138 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 MachineBasicBlock *BB) {
143 TargetLowering &TLI = IS->getTargetLowering();
145 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
146 return createTDListDAGScheduler(IS, DAG, BB);
148 assert(TLI.getSchedulingPreference() ==
149 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
150 return createBURRListDAGScheduler(IS, DAG, BB);
155 //===--------------------------------------------------------------------===//
156 /// FunctionLoweringInfo - This contains information that is global to a
157 /// function that is used when lowering a region of the function.
158 class FunctionLoweringInfo {
165 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
168 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170 /// ValueMap - Since we emit code for the function a basic block at a time,
171 /// we must remember which virtual registers hold the values for
172 /// cross-basic-block values.
173 DenseMap<const Value*, unsigned> ValueMap;
175 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
176 /// the entry block. This allows the allocas to be efficiently referenced
177 /// anywhere in the function.
178 std::map<const AllocaInst*, int> StaticAllocaMap;
180 unsigned MakeReg(MVT::ValueType VT) {
181 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
184 /// isExportedInst - Return true if the specified value is an instruction
185 /// exported from its block.
186 bool isExportedInst(const Value *V) {
187 return ValueMap.count(V);
190 unsigned CreateRegForValue(const Value *V);
192 unsigned InitializeRegForValue(const Value *V) {
193 unsigned &R = ValueMap[V];
194 assert(R == 0 && "Already initialized this value register!");
195 return R = CreateRegForValue(V);
200 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
201 /// PHI nodes or outside of the basic block that defines it, or used by a
202 /// switch instruction, which may expand to multiple basic blocks.
203 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
204 if (isa<PHINode>(I)) return true;
205 BasicBlock *BB = I->getParent();
206 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
207 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
208 // FIXME: Remove switchinst special case.
209 isa<SwitchInst>(*UI))
214 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
215 /// entry block, return true. This includes arguments used by switches, since
216 /// the switch may expand into multiple basic blocks.
217 static bool isOnlyUsedInEntryBlock(Argument *A) {
218 BasicBlock *Entry = A->getParent()->begin();
219 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
220 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
221 return false; // Use not in entry block.
225 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
226 Function &fn, MachineFunction &mf)
227 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229 // Create a vreg for each argument register that is not dead and is used
230 // outside of the entry block for the function.
231 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 if (!isOnlyUsedInEntryBlock(AI))
234 InitializeRegForValue(AI);
236 // Initialize the mapping of values to registers. This is only set up for
237 // instruction values that are used outside of the block that defines
239 Function::iterator BB = Fn.begin(), EB = Fn.end();
240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
241 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
242 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
243 const Type *Ty = AI->getAllocatedType();
244 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
246 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
249 TySize *= CUI->getZExtValue(); // Get total allocated size.
250 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
251 StaticAllocaMap[AI] =
252 MF.getFrameInfo()->CreateStackObject(TySize, Align);
255 for (; BB != EB; ++BB)
256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
257 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
258 if (!isa<AllocaInst>(I) ||
259 !StaticAllocaMap.count(cast<AllocaInst>(I)))
260 InitializeRegForValue(I);
262 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
263 // also creates the initial PHI MachineInstrs, though none of the input
264 // operands are populated.
265 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
266 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268 MF.getBasicBlockList().push_back(MBB);
270 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
273 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
274 if (PN->use_empty()) continue;
276 MVT::ValueType VT = TLI.getValueType(PN->getType());
277 unsigned NumElements;
278 if (VT != MVT::Vector)
279 NumElements = TLI.getNumElements(VT);
281 MVT::ValueType VT1,VT2;
283 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
286 unsigned PHIReg = ValueMap[PN];
287 assert(PHIReg && "PHI node does not have an assigned virtual register!");
288 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
289 for (unsigned i = 0; i != NumElements; ++i)
290 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
295 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
296 /// the correctly promoted or expanded types. Assign these registers
297 /// consecutive vreg numbers and return the first assigned number.
298 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
299 MVT::ValueType VT = TLI.getValueType(V->getType());
301 // The number of multiples of registers that we need, to, e.g., split up
302 // a <2 x int64> -> 4 x i32 registers.
303 unsigned NumVectorRegs = 1;
305 // If this is a vector type, figure out what type it will decompose into
306 // and how many of the elements it will use.
307 if (VT == MVT::Vector) {
308 const VectorType *PTy = cast<VectorType>(V->getType());
309 unsigned NumElts = PTy->getNumElements();
310 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
311 MVT::ValueType VecTy = getVectorType(EltTy, NumElts);
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
315 while (NumElts > 1 && !TLI.isTypeLegal(VecTy)) {
318 VecTy = getVectorType(EltTy, NumElts);
321 // Check that VecTy isn't a 1-element vector.
322 if (NumElts == 1 && VecTy == MVT::Other)
328 // The common case is that we will only create one register for this
329 // value. If we have that case, create and return the virtual register.
330 unsigned NV = TLI.getNumElements(VT);
332 // If we are promoting this value, pick the next largest supported type.
333 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
334 unsigned Reg = MakeReg(PromotedType);
335 // If this is a vector of supported or promoted types (e.g. 4 x i16),
336 // create all of the registers.
337 for (unsigned i = 1; i != NumVectorRegs; ++i)
338 MakeReg(PromotedType);
342 // If this value is represented with multiple target registers, make sure
343 // to create enough consecutive registers of the right (smaller) type.
344 VT = TLI.getTypeToExpandTo(VT);
345 unsigned R = MakeReg(VT);
346 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
351 //===----------------------------------------------------------------------===//
352 /// SelectionDAGLowering - This is the common target-independent lowering
353 /// implementation that is parameterized by a TargetLowering object.
354 /// Also, targets can overload any lowering method.
357 class SelectionDAGLowering {
358 MachineBasicBlock *CurMBB;
360 DenseMap<const Value*, SDOperand> NodeMap;
362 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
363 /// them up and then emit token factor nodes when possible. This allows us to
364 /// get simple disambiguation between loads without worrying about alias
366 std::vector<SDOperand> PendingLoads;
368 /// Case - A struct to record the Value for a switch case, and the
369 /// case's target basic block.
373 MachineBasicBlock* BB;
375 Case() : Low(0), High(0), BB(0) { }
376 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
377 Low(low), High(high), BB(bb) { }
378 uint64_t size() const {
379 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
380 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
381 return (rHigh - rLow + 1ULL);
387 MachineBasicBlock* BB;
390 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
391 Mask(mask), BB(bb), Bits(bits) { }
394 typedef std::vector<Case> CaseVector;
395 typedef std::vector<CaseBits> CaseBitsVector;
396 typedef CaseVector::iterator CaseItr;
397 typedef std::pair<CaseItr, CaseItr> CaseRange;
399 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
400 /// of conditional branches.
402 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
403 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
405 /// CaseBB - The MBB in which to emit the compare and branch
406 MachineBasicBlock *CaseBB;
407 /// LT, GE - If nonzero, we know the current case value must be less-than or
408 /// greater-than-or-equal-to these Constants.
411 /// Range - A pair of iterators representing the range of case values to be
412 /// processed at this point in the binary search tree.
416 typedef std::vector<CaseRec> CaseRecVector;
418 /// The comparison function for sorting the switch case values in the vector.
419 /// WARNING: Case ranges should be disjoint!
421 bool operator () (const Case& C1, const Case& C2) {
422 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
423 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
424 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
425 return CI1->getValue().slt(CI2->getValue());
430 bool operator () (const CaseBits& C1, const CaseBits& C2) {
431 return C1.Bits > C2.Bits;
435 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
438 // TLI - This is information that describes the available target features we
439 // need for lowering. This indicates when operations are unavailable,
440 // implemented with a libcall, etc.
443 const TargetData *TD;
445 /// SwitchCases - Vector of CaseBlock structures used to communicate
446 /// SwitchInst code generation information.
447 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
448 /// JTCases - Vector of JumpTable structures used to communicate
449 /// SwitchInst code generation information.
450 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
451 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
453 /// FuncInfo - Information about the function as a whole.
455 FunctionLoweringInfo &FuncInfo;
457 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
458 FunctionLoweringInfo &funcinfo)
459 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
463 /// getRoot - Return the current virtual root of the Selection DAG.
465 SDOperand getRoot() {
466 if (PendingLoads.empty())
467 return DAG.getRoot();
469 if (PendingLoads.size() == 1) {
470 SDOperand Root = PendingLoads[0];
472 PendingLoads.clear();
476 // Otherwise, we have to make a token factor node.
477 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
478 &PendingLoads[0], PendingLoads.size());
479 PendingLoads.clear();
484 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
486 void visit(Instruction &I) { visit(I.getOpcode(), I); }
488 void visit(unsigned Opcode, User &I) {
489 // Note: this doesn't use InstVisitor, because it has to work with
490 // ConstantExpr's in addition to instructions.
492 default: assert(0 && "Unknown instruction type encountered!");
494 // Build the switch statement using the Instruction.def file.
495 #define HANDLE_INST(NUM, OPCODE, CLASS) \
496 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
497 #include "llvm/Instruction.def"
501 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
503 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
504 const Value *SV, SDOperand Root,
505 bool isVolatile, unsigned Alignment);
507 SDOperand getIntPtrConstant(uint64_t Val) {
508 return DAG.getConstant(Val, TLI.getPointerTy());
511 SDOperand getValue(const Value *V);
513 void setValue(const Value *V, SDOperand NewN) {
514 SDOperand &N = NodeMap[V];
515 assert(N.Val == 0 && "Already set a value for this node!");
519 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
521 bool OutReg, bool InReg,
522 std::set<unsigned> &OutputRegs,
523 std::set<unsigned> &InputRegs);
525 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
526 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
528 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
529 void ExportFromCurrentBlock(Value *V);
530 void LowerCallTo(Instruction &I,
531 const Type *CalledValueTy, unsigned CallingConv,
532 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
534 // Terminator instructions.
535 void visitRet(ReturnInst &I);
536 void visitBr(BranchInst &I);
537 void visitSwitch(SwitchInst &I);
538 void visitUnreachable(UnreachableInst &I) { /* noop */ }
540 // Helpers for visitSwitch
541 bool handleSmallSwitchRange(CaseRec& CR,
542 CaseRecVector& WorkList,
544 MachineBasicBlock* Default);
545 bool handleJTSwitchCase(CaseRec& CR,
546 CaseRecVector& WorkList,
548 MachineBasicBlock* Default);
549 bool handleBTSplitSwitchCase(CaseRec& CR,
550 CaseRecVector& WorkList,
552 MachineBasicBlock* Default);
553 bool handleBitTestsSwitchCase(CaseRec& CR,
554 CaseRecVector& WorkList,
556 MachineBasicBlock* Default);
557 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
558 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
559 void visitBitTestCase(MachineBasicBlock* NextMBB,
561 SelectionDAGISel::BitTestCase &B);
562 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
563 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
564 SelectionDAGISel::JumpTableHeader &JTH);
566 // These all get lowered before this pass.
567 void visitInvoke(InvokeInst &I);
568 void visitInvoke(InvokeInst &I, bool AsTerminator);
569 void visitUnwind(UnwindInst &I);
571 void visitScalarBinary(User &I, unsigned OpCode);
572 void visitVectorBinary(User &I, unsigned OpCode);
573 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
574 void visitShift(User &I, unsigned Opcode);
575 void visitAdd(User &I) {
576 if (isa<VectorType>(I.getType()))
577 visitVectorBinary(I, ISD::VADD);
578 else if (I.getType()->isFloatingPoint())
579 visitScalarBinary(I, ISD::FADD);
581 visitScalarBinary(I, ISD::ADD);
583 void visitSub(User &I);
584 void visitMul(User &I) {
585 if (isa<VectorType>(I.getType()))
586 visitVectorBinary(I, ISD::VMUL);
587 else if (I.getType()->isFloatingPoint())
588 visitScalarBinary(I, ISD::FMUL);
590 visitScalarBinary(I, ISD::MUL);
592 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
593 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
594 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
595 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
596 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
597 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
598 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
599 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
600 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
601 void visitShl (User &I) { visitShift(I, ISD::SHL); }
602 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
603 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
604 void visitICmp(User &I);
605 void visitFCmp(User &I);
606 // Visit the conversion instructions
607 void visitTrunc(User &I);
608 void visitZExt(User &I);
609 void visitSExt(User &I);
610 void visitFPTrunc(User &I);
611 void visitFPExt(User &I);
612 void visitFPToUI(User &I);
613 void visitFPToSI(User &I);
614 void visitUIToFP(User &I);
615 void visitSIToFP(User &I);
616 void visitPtrToInt(User &I);
617 void visitIntToPtr(User &I);
618 void visitBitCast(User &I);
620 void visitExtractElement(User &I);
621 void visitInsertElement(User &I);
622 void visitShuffleVector(User &I);
624 void visitGetElementPtr(User &I);
625 void visitSelect(User &I);
627 void visitMalloc(MallocInst &I);
628 void visitFree(FreeInst &I);
629 void visitAlloca(AllocaInst &I);
630 void visitLoad(LoadInst &I);
631 void visitStore(StoreInst &I);
632 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
633 void visitCall(CallInst &I);
634 void visitInlineAsm(CallInst &I);
635 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
636 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
638 void visitVAStart(CallInst &I);
639 void visitVAArg(VAArgInst &I);
640 void visitVAEnd(CallInst &I);
641 void visitVACopy(CallInst &I);
643 void visitMemIntrinsic(CallInst &I, unsigned Op);
645 void visitUserOp1(Instruction &I) {
646 assert(0 && "UserOp1 should not exist at instruction selection time!");
649 void visitUserOp2(Instruction &I) {
650 assert(0 && "UserOp2 should not exist at instruction selection time!");
654 } // end namespace llvm
656 SDOperand SelectionDAGLowering::getValue(const Value *V) {
657 SDOperand &N = NodeMap[V];
660 const Type *VTy = V->getType();
661 MVT::ValueType VT = TLI.getValueType(VTy);
662 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
663 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
664 visit(CE->getOpcode(), *CE);
665 SDOperand N1 = NodeMap[V];
666 assert(N1.Val && "visit didn't populate the ValueMap!");
668 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
669 return N = DAG.getGlobalAddress(GV, VT);
670 } else if (isa<ConstantPointerNull>(C)) {
671 return N = DAG.getConstant(0, TLI.getPointerTy());
672 } else if (isa<UndefValue>(C)) {
673 if (!isa<VectorType>(VTy))
674 return N = DAG.getNode(ISD::UNDEF, VT);
676 // Create a VBUILD_VECTOR of undef nodes.
677 const VectorType *PTy = cast<VectorType>(VTy);
678 unsigned NumElements = PTy->getNumElements();
679 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
681 SmallVector<SDOperand, 8> Ops;
682 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
684 // Create a VConstant node with generic Vector type.
685 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
686 Ops.push_back(DAG.getValueType(PVT));
687 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
688 &Ops[0], Ops.size());
689 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
690 return N = DAG.getConstantFP(CFP->getValue(), VT);
691 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
692 unsigned NumElements = PTy->getNumElements();
693 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
695 // Now that we know the number and type of the elements, push a
696 // Constant or ConstantFP node onto the ops list for each element of
697 // the packed constant.
698 SmallVector<SDOperand, 8> Ops;
699 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
700 for (unsigned i = 0; i != NumElements; ++i)
701 Ops.push_back(getValue(CP->getOperand(i)));
703 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
705 if (MVT::isFloatingPoint(PVT))
706 Op = DAG.getConstantFP(0, PVT);
708 Op = DAG.getConstant(0, PVT);
709 Ops.assign(NumElements, Op);
712 // Create a VBUILD_VECTOR node with generic Vector type.
713 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
714 Ops.push_back(DAG.getValueType(PVT));
715 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
718 // Canonicalize all constant ints to be unsigned.
719 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
723 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
724 std::map<const AllocaInst*, int>::iterator SI =
725 FuncInfo.StaticAllocaMap.find(AI);
726 if (SI != FuncInfo.StaticAllocaMap.end())
727 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
730 unsigned InReg = FuncInfo.ValueMap[V];
731 assert(InReg && "Value not in map!");
733 // If this type is not legal, make it so now.
734 if (VT != MVT::Vector) {
735 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
736 // Source must be expanded. This input value is actually coming from the
737 // register pair InReg and InReg+1.
738 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
739 unsigned NumVals = TLI.getNumElements(VT);
740 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
742 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
744 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
745 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
746 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
749 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
750 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
751 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
752 N = MVT::isFloatingPoint(VT)
753 ? DAG.getNode(ISD::FP_ROUND, VT, N)
754 : DAG.getNode(ISD::TRUNCATE, VT, N);
757 // Otherwise, if this is a vector, make it available as a generic vector
759 MVT::ValueType PTyElementVT, PTyLegalElementVT;
760 const VectorType *PTy = cast<VectorType>(VTy);
761 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
764 // Build a VBUILD_VECTOR with the input registers.
765 SmallVector<SDOperand, 8> Ops;
766 if (PTyElementVT == PTyLegalElementVT) {
767 // If the value types are legal, just VBUILD the CopyFromReg nodes.
768 for (unsigned i = 0; i != NE; ++i)
769 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
771 } else if (PTyElementVT < PTyLegalElementVT) {
772 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
773 for (unsigned i = 0; i != NE; ++i) {
774 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
776 if (MVT::isFloatingPoint(PTyElementVT))
777 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
779 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
783 // If the register was expanded, use BUILD_PAIR.
784 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
785 for (unsigned i = 0; i != NE/2; ++i) {
786 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
788 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
790 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
794 Ops.push_back(DAG.getConstant(NE, MVT::i32));
795 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
796 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
798 // Finally, use a VBIT_CONVERT to make this available as the appropriate
800 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
801 DAG.getConstant(PTy->getNumElements(),
803 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
810 void SelectionDAGLowering::visitRet(ReturnInst &I) {
811 if (I.getNumOperands() == 0) {
812 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
815 SmallVector<SDOperand, 8> NewValues;
816 NewValues.push_back(getRoot());
817 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
818 SDOperand RetOp = getValue(I.getOperand(i));
820 // If this is an integer return value, we need to promote it ourselves to
821 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
823 // FIXME: C calling convention requires the return type to be promoted to
824 // at least 32-bit. But this is not necessary for non-C calling conventions.
825 if (MVT::isInteger(RetOp.getValueType()) &&
826 RetOp.getValueType() < MVT::i64) {
827 MVT::ValueType TmpVT;
828 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
829 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
832 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
833 const ParamAttrsList *Attrs = FTy->getParamAttrs();
834 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
835 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
836 ExtendKind = ISD::SIGN_EXTEND;
837 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
838 ExtendKind = ISD::ZERO_EXTEND;
839 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
841 NewValues.push_back(RetOp);
842 NewValues.push_back(DAG.getConstant(false, MVT::i32));
844 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
845 &NewValues[0], NewValues.size()));
848 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
849 /// the current basic block, add it to ValueMap now so that we'll get a
851 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
852 // No need to export constants.
853 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
856 if (FuncInfo.isExportedInst(V)) return;
858 unsigned Reg = FuncInfo.InitializeRegForValue(V);
859 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
862 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
863 const BasicBlock *FromBB) {
864 // The operands of the setcc have to be in this block. We don't know
865 // how to export them from some other block.
866 if (Instruction *VI = dyn_cast<Instruction>(V)) {
867 // Can export from current BB.
868 if (VI->getParent() == FromBB)
871 // Is already exported, noop.
872 return FuncInfo.isExportedInst(V);
875 // If this is an argument, we can export it if the BB is the entry block or
876 // if it is already exported.
877 if (isa<Argument>(V)) {
878 if (FromBB == &FromBB->getParent()->getEntryBlock())
881 // Otherwise, can only export this if it is already exported.
882 return FuncInfo.isExportedInst(V);
885 // Otherwise, constants can always be exported.
889 static bool InBlock(const Value *V, const BasicBlock *BB) {
890 if (const Instruction *I = dyn_cast<Instruction>(V))
891 return I->getParent() == BB;
895 /// FindMergedConditions - If Cond is an expression like
896 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
897 MachineBasicBlock *TBB,
898 MachineBasicBlock *FBB,
899 MachineBasicBlock *CurBB,
901 // If this node is not part of the or/and tree, emit it as a branch.
902 Instruction *BOp = dyn_cast<Instruction>(Cond);
904 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
905 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
906 BOp->getParent() != CurBB->getBasicBlock() ||
907 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
908 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
909 const BasicBlock *BB = CurBB->getBasicBlock();
911 // If the leaf of the tree is a comparison, merge the condition into
913 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
914 // The operands of the cmp have to be in this block. We don't know
915 // how to export them from some other block. If this is the first block
916 // of the sequence, no exporting is needed.
918 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
919 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
920 BOp = cast<Instruction>(Cond);
921 ISD::CondCode Condition;
922 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
923 switch (IC->getPredicate()) {
924 default: assert(0 && "Unknown icmp predicate opcode!");
925 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
926 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
927 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
928 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
929 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
930 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
931 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
932 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
933 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
934 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
936 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
937 ISD::CondCode FPC, FOC;
938 switch (FC->getPredicate()) {
939 default: assert(0 && "Unknown fcmp predicate opcode!");
940 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
941 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
942 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
943 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
944 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
945 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
946 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
947 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
948 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
949 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
950 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
951 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
952 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
953 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
954 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
955 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
957 if (FiniteOnlyFPMath())
962 Condition = ISD::SETEQ; // silence warning.
963 assert(0 && "Unknown compare instruction");
966 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
967 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
968 SwitchCases.push_back(CB);
972 // Create a CaseBlock record representing this branch.
973 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
974 NULL, TBB, FBB, CurBB);
975 SwitchCases.push_back(CB);
980 // Create TmpBB after CurBB.
981 MachineFunction::iterator BBI = CurBB;
982 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
983 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
985 if (Opc == Instruction::Or) {
994 // Emit the LHS condition.
995 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
997 // Emit the RHS condition into TmpBB.
998 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1000 assert(Opc == Instruction::And && "Unknown merge op!");
1001 // Codegen X & Y as:
1008 // This requires creation of TmpBB after CurBB.
1010 // Emit the LHS condition.
1011 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1013 // Emit the RHS condition into TmpBB.
1014 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1018 /// If the set of cases should be emitted as a series of branches, return true.
1019 /// If we should emit this as a bunch of and/or'd together conditions, return
1022 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1023 if (Cases.size() != 2) return true;
1025 // If this is two comparisons of the same values or'd or and'd together, they
1026 // will get folded into a single comparison, so don't emit two blocks.
1027 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1028 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1029 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1030 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1037 void SelectionDAGLowering::visitBr(BranchInst &I) {
1038 // Update machine-CFG edges.
1039 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1041 // Figure out which block is immediately after the current one.
1042 MachineBasicBlock *NextBlock = 0;
1043 MachineFunction::iterator BBI = CurMBB;
1044 if (++BBI != CurMBB->getParent()->end())
1047 if (I.isUnconditional()) {
1048 // If this is not a fall-through branch, emit the branch.
1049 if (Succ0MBB != NextBlock)
1050 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1051 DAG.getBasicBlock(Succ0MBB)));
1053 // Update machine-CFG edges.
1054 CurMBB->addSuccessor(Succ0MBB);
1059 // If this condition is one of the special cases we handle, do special stuff
1061 Value *CondVal = I.getCondition();
1062 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1064 // If this is a series of conditions that are or'd or and'd together, emit
1065 // this as a sequence of branches instead of setcc's with and/or operations.
1066 // For example, instead of something like:
1079 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1080 if (BOp->hasOneUse() &&
1081 (BOp->getOpcode() == Instruction::And ||
1082 BOp->getOpcode() == Instruction::Or)) {
1083 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1084 // If the compares in later blocks need to use values not currently
1085 // exported from this block, export them now. This block should always
1086 // be the first entry.
1087 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1089 // Allow some cases to be rejected.
1090 if (ShouldEmitAsBranches(SwitchCases)) {
1091 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1092 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1093 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1096 // Emit the branch for this block.
1097 visitSwitchCase(SwitchCases[0]);
1098 SwitchCases.erase(SwitchCases.begin());
1102 // Okay, we decided not to do this, remove any inserted MBB's and clear
1104 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1105 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1107 SwitchCases.clear();
1111 // Create a CaseBlock record representing this branch.
1112 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1113 NULL, Succ0MBB, Succ1MBB, CurMBB);
1114 // Use visitSwitchCase to actually insert the fast branch sequence for this
1116 visitSwitchCase(CB);
1119 /// visitSwitchCase - Emits the necessary code to represent a single node in
1120 /// the binary search tree resulting from lowering a switch instruction.
1121 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1123 SDOperand CondLHS = getValue(CB.CmpLHS);
1125 // Build the setcc now.
1126 if (CB.CmpMHS == NULL) {
1127 // Fold "(X == true)" to X and "(X == false)" to !X to
1128 // handle common cases produced by branch lowering.
1129 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1131 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1132 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1133 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1135 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1137 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1139 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1140 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1142 SDOperand CmpOp = getValue(CB.CmpMHS);
1143 MVT::ValueType VT = CmpOp.getValueType();
1145 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1146 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1148 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1149 Cond = DAG.getSetCC(MVT::i1, SUB,
1150 DAG.getConstant(High-Low, VT), ISD::SETULE);
1155 // Set NextBlock to be the MBB immediately after the current one, if any.
1156 // This is used to avoid emitting unnecessary branches to the next block.
1157 MachineBasicBlock *NextBlock = 0;
1158 MachineFunction::iterator BBI = CurMBB;
1159 if (++BBI != CurMBB->getParent()->end())
1162 // If the lhs block is the next block, invert the condition so that we can
1163 // fall through to the lhs instead of the rhs block.
1164 if (CB.TrueBB == NextBlock) {
1165 std::swap(CB.TrueBB, CB.FalseBB);
1166 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1167 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1169 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1170 DAG.getBasicBlock(CB.TrueBB));
1171 if (CB.FalseBB == NextBlock)
1172 DAG.setRoot(BrCond);
1174 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1175 DAG.getBasicBlock(CB.FalseBB)));
1176 // Update successor info
1177 CurMBB->addSuccessor(CB.TrueBB);
1178 CurMBB->addSuccessor(CB.FalseBB);
1181 /// visitJumpTable - Emit JumpTable node in the current MBB
1182 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1183 // Emit the code for the jump table
1184 assert(JT.Reg != -1U && "Should lower JT Header first!");
1185 MVT::ValueType PTy = TLI.getPointerTy();
1186 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1187 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1188 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1193 /// visitJumpTableHeader - This function emits necessary code to produce index
1194 /// in the JumpTable from switch case.
1195 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1196 SelectionDAGISel::JumpTableHeader &JTH) {
1197 // Subtract the lowest switch case value from the value being switched on
1198 // and conditional branch to default mbb if the result is greater than the
1199 // difference between smallest and largest cases.
1200 SDOperand SwitchOp = getValue(JTH.SValue);
1201 MVT::ValueType VT = SwitchOp.getValueType();
1202 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1203 DAG.getConstant(JTH.First, VT));
1205 // The SDNode we just created, which holds the value being switched on
1206 // minus the the smallest case value, needs to be copied to a virtual
1207 // register so it can be used as an index into the jump table in a
1208 // subsequent basic block. This value may be smaller or larger than the
1209 // target's pointer type, and therefore require extension or truncating.
1210 if (VT > TLI.getPointerTy())
1211 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1213 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1215 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1216 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1217 JT.Reg = JumpTableReg;
1219 // Emit the range check for the jump table, and branch to the default
1220 // block for the switch statement if the value being switched on exceeds
1221 // the largest case in the switch.
1222 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1223 DAG.getConstant(JTH.Last-JTH.First,VT),
1226 // Set NextBlock to be the MBB immediately after the current one, if any.
1227 // This is used to avoid emitting unnecessary branches to the next block.
1228 MachineBasicBlock *NextBlock = 0;
1229 MachineFunction::iterator BBI = CurMBB;
1230 if (++BBI != CurMBB->getParent()->end())
1233 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1234 DAG.getBasicBlock(JT.Default));
1236 if (JT.MBB == NextBlock)
1237 DAG.setRoot(BrCond);
1239 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1240 DAG.getBasicBlock(JT.MBB)));
1245 /// visitBitTestHeader - This function emits necessary code to produce value
1246 /// suitable for "bit tests"
1247 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1248 // Subtract the minimum value
1249 SDOperand SwitchOp = getValue(B.SValue);
1250 MVT::ValueType VT = SwitchOp.getValueType();
1251 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1252 DAG.getConstant(B.First, VT));
1255 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1256 DAG.getConstant(B.Range, VT),
1260 if (VT > TLI.getShiftAmountTy())
1261 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1263 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1265 // Make desired shift
1266 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1267 DAG.getConstant(1, TLI.getPointerTy()),
1270 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1271 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1274 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1275 DAG.getBasicBlock(B.Default));
1277 // Set NextBlock to be the MBB immediately after the current one, if any.
1278 // This is used to avoid emitting unnecessary branches to the next block.
1279 MachineBasicBlock *NextBlock = 0;
1280 MachineFunction::iterator BBI = CurMBB;
1281 if (++BBI != CurMBB->getParent()->end())
1284 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1285 if (MBB == NextBlock)
1286 DAG.setRoot(BrRange);
1288 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1289 DAG.getBasicBlock(MBB)));
1291 CurMBB->addSuccessor(B.Default);
1292 CurMBB->addSuccessor(MBB);
1297 /// visitBitTestCase - this function produces one "bit test"
1298 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1300 SelectionDAGISel::BitTestCase &B) {
1301 // Emit bit tests and jumps
1302 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1304 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1306 DAG.getConstant(B.Mask,
1307 TLI.getPointerTy()));
1308 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1309 DAG.getConstant(0, TLI.getPointerTy()),
1311 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1312 AndCmp, DAG.getBasicBlock(B.TargetBB));
1314 // Set NextBlock to be the MBB immediately after the current one, if any.
1315 // This is used to avoid emitting unnecessary branches to the next block.
1316 MachineBasicBlock *NextBlock = 0;
1317 MachineFunction::iterator BBI = CurMBB;
1318 if (++BBI != CurMBB->getParent()->end())
1321 if (NextMBB == NextBlock)
1324 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1325 DAG.getBasicBlock(NextMBB)));
1327 CurMBB->addSuccessor(B.TargetBB);
1328 CurMBB->addSuccessor(NextMBB);
1333 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1334 assert(0 && "Should never be visited directly");
1336 void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
1337 // Retrieve successors.
1338 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1339 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1341 if (!AsTerminator) {
1342 // Mark landing pad so that it doesn't get deleted in branch folding.
1343 LandingPad->setIsLandingPad();
1345 // Insert a label before the invoke call to mark the try range.
1346 // This can be used to detect deletion of the invoke via the
1347 // MachineModuleInfo.
1348 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1349 unsigned BeginLabel = MMI->NextLabelID();
1350 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1351 DAG.getConstant(BeginLabel, MVT::i32)));
1353 LowerCallTo(I, I.getCalledValue()->getType(),
1356 getValue(I.getOperand(0)),
1359 // Insert a label before the invoke call to mark the try range.
1360 // This can be used to detect deletion of the invoke via the
1361 // MachineModuleInfo.
1362 unsigned EndLabel = MMI->NextLabelID();
1363 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1364 DAG.getConstant(EndLabel, MVT::i32)));
1366 // Inform MachineModuleInfo of range.
1367 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1369 // Update successor info
1370 CurMBB->addSuccessor(Return);
1371 CurMBB->addSuccessor(LandingPad);
1373 // Drop into normal successor.
1374 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1375 DAG.getBasicBlock(Return)));
1379 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1382 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1383 /// small case ranges).
1384 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1385 CaseRecVector& WorkList,
1387 MachineBasicBlock* Default) {
1388 Case& BackCase = *(CR.Range.second-1);
1390 // Size is the number of Cases represented by this range.
1391 unsigned Size = CR.Range.second - CR.Range.first;
1395 // Get the MachineFunction which holds the current MBB. This is used when
1396 // inserting any additional MBBs necessary to represent the switch.
1397 MachineFunction *CurMF = CurMBB->getParent();
1399 // Figure out which block is immediately after the current one.
1400 MachineBasicBlock *NextBlock = 0;
1401 MachineFunction::iterator BBI = CR.CaseBB;
1403 if (++BBI != CurMBB->getParent()->end())
1406 // TODO: If any two of the cases has the same destination, and if one value
1407 // is the same as the other, but has one bit unset that the other has set,
1408 // use bit manipulation to do two compares at once. For example:
1409 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1411 // Rearrange the case blocks so that the last one falls through if possible.
1412 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1413 // The last case block won't fall through into 'NextBlock' if we emit the
1414 // branches in this order. See if rearranging a case value would help.
1415 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1416 if (I->BB == NextBlock) {
1417 std::swap(*I, BackCase);
1423 // Create a CaseBlock record representing a conditional branch to
1424 // the Case's target mbb if the value being switched on SV is equal
1426 MachineBasicBlock *CurBlock = CR.CaseBB;
1427 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1428 MachineBasicBlock *FallThrough;
1430 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1431 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1433 // If the last case doesn't match, go to the default block.
1434 FallThrough = Default;
1437 Value *RHS, *LHS, *MHS;
1439 if (I->High == I->Low) {
1440 // This is just small small case range :) containing exactly 1 case
1442 LHS = SV; RHS = I->High; MHS = NULL;
1445 LHS = I->Low; MHS = SV; RHS = I->High;
1447 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1448 I->BB, FallThrough, CurBlock);
1450 // If emitting the first comparison, just call visitSwitchCase to emit the
1451 // code into the current block. Otherwise, push the CaseBlock onto the
1452 // vector to be later processed by SDISel, and insert the node's MBB
1453 // before the next MBB.
1454 if (CurBlock == CurMBB)
1455 visitSwitchCase(CB);
1457 SwitchCases.push_back(CB);
1459 CurBlock = FallThrough;
1465 /// handleJTSwitchCase - Emit jumptable for current switch case range
1466 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1467 CaseRecVector& WorkList,
1469 MachineBasicBlock* Default) {
1470 Case& FrontCase = *CR.Range.first;
1471 Case& BackCase = *(CR.Range.second-1);
1473 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1474 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1477 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1481 if ((!TLI.isOperationLegal(ISD::BR_JT, MVT::Other) &&
1482 !TLI.isOperationLegal(ISD::BRIND, MVT::Other)) ||
1486 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1490 DOUT << "Lowering jump table\n"
1491 << "First entry: " << First << ". Last entry: " << Last << "\n"
1492 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1494 // Get the MachineFunction which holds the current MBB. This is used when
1495 // inserting any additional MBBs necessary to represent the switch.
1496 MachineFunction *CurMF = CurMBB->getParent();
1498 // Figure out which block is immediately after the current one.
1499 MachineBasicBlock *NextBlock = 0;
1500 MachineFunction::iterator BBI = CR.CaseBB;
1502 if (++BBI != CurMBB->getParent()->end())
1505 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1507 // Create a new basic block to hold the code for loading the address
1508 // of the jump table, and jumping to it. Update successor information;
1509 // we will either branch to the default case for the switch, or the jump
1511 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1512 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1513 CR.CaseBB->addSuccessor(Default);
1514 CR.CaseBB->addSuccessor(JumpTableBB);
1516 // Build a vector of destination BBs, corresponding to each target
1517 // of the jump table. If the value of the jump table slot corresponds to
1518 // a case statement, push the case's BB onto the vector, otherwise, push
1520 std::vector<MachineBasicBlock*> DestBBs;
1521 int64_t TEI = First;
1522 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1523 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1524 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1526 if ((Low <= TEI) && (TEI <= High)) {
1527 DestBBs.push_back(I->BB);
1531 DestBBs.push_back(Default);
1535 // Update successor info. Add one edge to each unique successor.
1536 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1537 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1538 E = DestBBs.end(); I != E; ++I) {
1539 if (!SuccsHandled[(*I)->getNumber()]) {
1540 SuccsHandled[(*I)->getNumber()] = true;
1541 JumpTableBB->addSuccessor(*I);
1545 // Create a jump table index for this jump table, or return an existing
1547 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1549 // Set the jump table information so that we can codegen it as a second
1550 // MachineBasicBlock
1551 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1552 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1553 (CR.CaseBB == CurMBB));
1554 if (CR.CaseBB == CurMBB)
1555 visitJumpTableHeader(JT, JTH);
1557 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1562 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1564 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1565 CaseRecVector& WorkList,
1567 MachineBasicBlock* Default) {
1568 // Get the MachineFunction which holds the current MBB. This is used when
1569 // inserting any additional MBBs necessary to represent the switch.
1570 MachineFunction *CurMF = CurMBB->getParent();
1572 // Figure out which block is immediately after the current one.
1573 MachineBasicBlock *NextBlock = 0;
1574 MachineFunction::iterator BBI = CR.CaseBB;
1576 if (++BBI != CurMBB->getParent()->end())
1579 Case& FrontCase = *CR.Range.first;
1580 Case& BackCase = *(CR.Range.second-1);
1581 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1583 // Size is the number of Cases represented by this range.
1584 unsigned Size = CR.Range.second - CR.Range.first;
1586 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1587 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1589 CaseItr Pivot = CR.Range.first + Size/2;
1591 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1592 // (heuristically) allow us to emit JumpTable's later.
1594 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1598 uint64_t LSize = FrontCase.size();
1599 uint64_t RSize = TSize-LSize;
1600 DOUT << "Selecting best pivot: \n"
1601 << "First: " << First << ", Last: " << Last <<"\n"
1602 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1603 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1605 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1606 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1607 assert((RBegin-LEnd>=1) && "Invalid case distance");
1608 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1609 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1610 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1611 // Should always split in some non-trivial place
1613 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1614 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1615 << "Metric: " << Metric << "\n";
1616 if (FMetric < Metric) {
1619 DOUT << "Current metric set to: " << FMetric << "\n";
1625 // If our case is dense we *really* should handle it earlier!
1626 assert((FMetric > 0) && "Should handle dense range earlier!");
1628 CaseRange LHSR(CR.Range.first, Pivot);
1629 CaseRange RHSR(Pivot, CR.Range.second);
1630 Constant *C = Pivot->Low;
1631 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1633 // We know that we branch to the LHS if the Value being switched on is
1634 // less than the Pivot value, C. We use this to optimize our binary
1635 // tree a bit, by recognizing that if SV is greater than or equal to the
1636 // LHS's Case Value, and that Case Value is exactly one less than the
1637 // Pivot's Value, then we can branch directly to the LHS's Target,
1638 // rather than creating a leaf node for it.
1639 if ((LHSR.second - LHSR.first) == 1 &&
1640 LHSR.first->High == CR.GE &&
1641 cast<ConstantInt>(C)->getSExtValue() ==
1642 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1643 TrueBB = LHSR.first->BB;
1645 TrueBB = new MachineBasicBlock(LLVMBB);
1646 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1647 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1650 // Similar to the optimization above, if the Value being switched on is
1651 // known to be less than the Constant CR.LT, and the current Case Value
1652 // is CR.LT - 1, then we can branch directly to the target block for
1653 // the current Case Value, rather than emitting a RHS leaf node for it.
1654 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1655 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1656 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1657 FalseBB = RHSR.first->BB;
1659 FalseBB = new MachineBasicBlock(LLVMBB);
1660 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1661 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1664 // Create a CaseBlock record representing a conditional branch to
1665 // the LHS node if the value being switched on SV is less than C.
1666 // Otherwise, branch to LHS.
1667 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1668 TrueBB, FalseBB, CR.CaseBB);
1670 if (CR.CaseBB == CurMBB)
1671 visitSwitchCase(CB);
1673 SwitchCases.push_back(CB);
1678 /// handleBitTestsSwitchCase - if current case range has few destination and
1679 /// range span less, than machine word bitwidth, encode case range into series
1680 /// of masks and emit bit tests with these masks.
1681 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1682 CaseRecVector& WorkList,
1684 MachineBasicBlock* Default){
1686 unsigned IntPtrBits = getSizeInBits(TLI.getPointerTy());
1688 Case& FrontCase = *CR.Range.first;
1689 Case& BackCase = *(CR.Range.second-1);
1691 // Get the MachineFunction which holds the current MBB. This is used when
1692 // inserting any additional MBBs necessary to represent the switch.
1693 MachineFunction *CurMF = CurMBB->getParent();
1695 unsigned numCmps = 0;
1696 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1698 // Single case counts one, case range - two.
1699 if (I->Low == I->High)
1705 // Count unique destinations
1706 SmallSet<MachineBasicBlock*, 4> Dests;
1707 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1708 Dests.insert(I->BB);
1709 if (Dests.size() > 3)
1710 // Don't bother the code below, if there are too much unique destinations
1713 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1714 << "Total number of comparisons: " << numCmps << "\n";
1716 // Compute span of values.
1717 Constant* minValue = FrontCase.Low;
1718 Constant* maxValue = BackCase.High;
1719 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1720 cast<ConstantInt>(minValue)->getSExtValue();
1721 DOUT << "Compare range: " << range << "\n"
1722 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1723 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1725 if (range>IntPtrBits ||
1726 (!(Dests.size() == 1 && numCmps >= 3) &&
1727 !(Dests.size() == 2 && numCmps >= 5) &&
1728 !(Dests.size() >= 3 && numCmps >= 6)))
1731 DOUT << "Emitting bit tests\n";
1732 int64_t lowBound = 0;
1734 // Optimize the case where all the case values fit in a
1735 // word without having to subtract minValue. In this case,
1736 // we can optimize away the subtraction.
1737 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1738 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1739 range = cast<ConstantInt>(maxValue)->getSExtValue();
1741 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1744 CaseBitsVector CasesBits;
1745 unsigned i, count = 0;
1747 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1748 MachineBasicBlock* Dest = I->BB;
1749 for (i = 0; i < count; ++i)
1750 if (Dest == CasesBits[i].BB)
1754 assert((count < 3) && "Too much destinations to test!");
1755 CasesBits.push_back(CaseBits(0, Dest, 0));
1759 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1760 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1762 for (uint64_t j = lo; j <= hi; j++) {
1763 CasesBits[i].Mask |= 1ULL << j;
1764 CasesBits[i].Bits++;
1768 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1770 SelectionDAGISel::BitTestInfo BTC;
1772 // Figure out which block is immediately after the current one.
1773 MachineFunction::iterator BBI = CR.CaseBB;
1776 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1779 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1780 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1781 << ", BB: " << CasesBits[i].BB << "\n";
1783 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1784 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1785 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1790 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
1791 -1U, (CR.CaseBB == CurMBB),
1792 CR.CaseBB, Default, BTC);
1794 if (CR.CaseBB == CurMBB)
1795 visitBitTestHeader(BTB);
1797 BitTestCases.push_back(BTB);
1803 // Clusterify - Transform simple list of Cases into list of CaseRange's
1804 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1805 const SwitchInst& SI) {
1806 unsigned numCmps = 0;
1808 // Start with "simple" cases
1809 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1810 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1811 Cases.push_back(Case(SI.getSuccessorValue(i),
1812 SI.getSuccessorValue(i),
1815 sort(Cases.begin(), Cases.end(), CaseCmp());
1817 // Merge case into clusters
1818 if (Cases.size()>=2)
1819 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1820 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1821 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1822 MachineBasicBlock* nextBB = J->BB;
1823 MachineBasicBlock* currentBB = I->BB;
1825 // If the two neighboring cases go to the same destination, merge them
1826 // into a single case.
1827 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1835 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1836 if (I->Low != I->High)
1837 // A range counts double, since it requires two compares.
1844 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1845 // Figure out which block is immediately after the current one.
1846 MachineBasicBlock *NextBlock = 0;
1847 MachineFunction::iterator BBI = CurMBB;
1849 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1851 // If there is only the default destination, branch to it if it is not the
1852 // next basic block. Otherwise, just fall through.
1853 if (SI.getNumOperands() == 2) {
1854 // Update machine-CFG edges.
1856 // If this is not a fall-through branch, emit the branch.
1857 if (Default != NextBlock)
1858 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1859 DAG.getBasicBlock(Default)));
1861 CurMBB->addSuccessor(Default);
1865 // If there are any non-default case statements, create a vector of Cases
1866 // representing each one, and sort the vector so that we can efficiently
1867 // create a binary search tree from them.
1869 unsigned numCmps = Clusterify(Cases, SI);
1870 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1871 << ". Total compares: " << numCmps << "\n";
1873 // Get the Value to be switched on and default basic blocks, which will be
1874 // inserted into CaseBlock records, representing basic blocks in the binary
1876 Value *SV = SI.getOperand(0);
1878 // Push the initial CaseRec onto the worklist
1879 CaseRecVector WorkList;
1880 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1882 while (!WorkList.empty()) {
1883 // Grab a record representing a case range to process off the worklist
1884 CaseRec CR = WorkList.back();
1885 WorkList.pop_back();
1887 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1890 // If the range has few cases (two or less) emit a series of specific
1892 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1895 // If the switch has more than 5 blocks, and at least 40% dense, and the
1896 // target supports indirect branches, then emit a jump table rather than
1897 // lowering the switch to a binary tree of conditional branches.
1898 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1901 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1902 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1903 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
1908 void SelectionDAGLowering::visitSub(User &I) {
1909 // -0.0 - X --> fneg
1910 const Type *Ty = I.getType();
1911 if (isa<VectorType>(Ty)) {
1912 visitVectorBinary(I, ISD::VSUB);
1913 } else if (Ty->isFloatingPoint()) {
1914 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1915 if (CFP->isExactlyValue(-0.0)) {
1916 SDOperand Op2 = getValue(I.getOperand(1));
1917 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1920 visitScalarBinary(I, ISD::FSUB);
1922 visitScalarBinary(I, ISD::SUB);
1925 void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
1926 SDOperand Op1 = getValue(I.getOperand(0));
1927 SDOperand Op2 = getValue(I.getOperand(1));
1929 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
1933 SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
1934 assert(isa<VectorType>(I.getType()));
1935 const VectorType *Ty = cast<VectorType>(I.getType());
1936 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
1938 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1939 getValue(I.getOperand(0)),
1940 getValue(I.getOperand(1)),
1941 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1945 void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1946 unsigned VectorOp) {
1947 if (isa<VectorType>(I.getType()))
1948 visitVectorBinary(I, VectorOp);
1950 visitScalarBinary(I, ScalarOp);
1953 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1954 SDOperand Op1 = getValue(I.getOperand(0));
1955 SDOperand Op2 = getValue(I.getOperand(1));
1957 if (TLI.getShiftAmountTy() < Op2.getValueType())
1958 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1959 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1960 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1962 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1965 void SelectionDAGLowering::visitICmp(User &I) {
1966 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1967 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1968 predicate = IC->getPredicate();
1969 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1970 predicate = ICmpInst::Predicate(IC->getPredicate());
1971 SDOperand Op1 = getValue(I.getOperand(0));
1972 SDOperand Op2 = getValue(I.getOperand(1));
1973 ISD::CondCode Opcode;
1974 switch (predicate) {
1975 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1976 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1977 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1978 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1979 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1980 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1981 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1982 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1983 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1984 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1986 assert(!"Invalid ICmp predicate value");
1987 Opcode = ISD::SETEQ;
1990 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1993 void SelectionDAGLowering::visitFCmp(User &I) {
1994 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1995 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1996 predicate = FC->getPredicate();
1997 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1998 predicate = FCmpInst::Predicate(FC->getPredicate());
1999 SDOperand Op1 = getValue(I.getOperand(0));
2000 SDOperand Op2 = getValue(I.getOperand(1));
2001 ISD::CondCode Condition, FOC, FPC;
2002 switch (predicate) {
2003 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2004 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2005 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2006 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2007 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2008 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2009 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2010 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2011 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2012 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2013 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2014 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2015 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2016 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2017 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2018 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2020 assert(!"Invalid FCmp predicate value");
2021 FOC = FPC = ISD::SETFALSE;
2024 if (FiniteOnlyFPMath())
2028 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2031 void SelectionDAGLowering::visitSelect(User &I) {
2032 SDOperand Cond = getValue(I.getOperand(0));
2033 SDOperand TrueVal = getValue(I.getOperand(1));
2034 SDOperand FalseVal = getValue(I.getOperand(2));
2035 if (!isa<VectorType>(I.getType())) {
2036 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2037 TrueVal, FalseVal));
2039 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2040 *(TrueVal.Val->op_end()-2),
2041 *(TrueVal.Val->op_end()-1)));
2046 void SelectionDAGLowering::visitTrunc(User &I) {
2047 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2048 SDOperand N = getValue(I.getOperand(0));
2049 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2050 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2053 void SelectionDAGLowering::visitZExt(User &I) {
2054 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2055 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2056 SDOperand N = getValue(I.getOperand(0));
2057 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2058 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2061 void SelectionDAGLowering::visitSExt(User &I) {
2062 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2063 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2064 SDOperand N = getValue(I.getOperand(0));
2065 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2066 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2069 void SelectionDAGLowering::visitFPTrunc(User &I) {
2070 // FPTrunc is never a no-op cast, no need to check
2071 SDOperand N = getValue(I.getOperand(0));
2072 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2073 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2076 void SelectionDAGLowering::visitFPExt(User &I){
2077 // FPTrunc is never a no-op cast, no need to check
2078 SDOperand N = getValue(I.getOperand(0));
2079 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2080 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2083 void SelectionDAGLowering::visitFPToUI(User &I) {
2084 // FPToUI is never a no-op cast, no need to check
2085 SDOperand N = getValue(I.getOperand(0));
2086 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2087 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2090 void SelectionDAGLowering::visitFPToSI(User &I) {
2091 // FPToSI is never a no-op cast, no need to check
2092 SDOperand N = getValue(I.getOperand(0));
2093 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2094 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2097 void SelectionDAGLowering::visitUIToFP(User &I) {
2098 // UIToFP is never a no-op cast, no need to check
2099 SDOperand N = getValue(I.getOperand(0));
2100 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2101 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2104 void SelectionDAGLowering::visitSIToFP(User &I){
2105 // UIToFP is never a no-op cast, no need to check
2106 SDOperand N = getValue(I.getOperand(0));
2107 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2108 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2111 void SelectionDAGLowering::visitPtrToInt(User &I) {
2112 // What to do depends on the size of the integer and the size of the pointer.
2113 // We can either truncate, zero extend, or no-op, accordingly.
2114 SDOperand N = getValue(I.getOperand(0));
2115 MVT::ValueType SrcVT = N.getValueType();
2116 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2118 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2119 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2121 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2122 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2123 setValue(&I, Result);
2126 void SelectionDAGLowering::visitIntToPtr(User &I) {
2127 // What to do depends on the size of the integer and the size of the pointer.
2128 // We can either truncate, zero extend, or no-op, accordingly.
2129 SDOperand N = getValue(I.getOperand(0));
2130 MVT::ValueType SrcVT = N.getValueType();
2131 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2132 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2133 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2135 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2136 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2139 void SelectionDAGLowering::visitBitCast(User &I) {
2140 SDOperand N = getValue(I.getOperand(0));
2141 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2142 if (DestVT == MVT::Vector) {
2143 // This is a cast to a vector from something else.
2144 // Get information about the output vector.
2145 const VectorType *DestTy = cast<VectorType>(I.getType());
2146 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2147 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2148 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2149 DAG.getValueType(EltVT)));
2152 MVT::ValueType SrcVT = N.getValueType();
2153 if (SrcVT == MVT::Vector) {
2154 // This is a cast from a vctor to something else.
2155 // Get information about the input vector.
2156 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
2160 // BitCast assures us that source and destination are the same size so this
2161 // is either a BIT_CONVERT or a no-op.
2162 if (DestVT != N.getValueType())
2163 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2165 setValue(&I, N); // noop cast.
2168 void SelectionDAGLowering::visitInsertElement(User &I) {
2169 SDOperand InVec = getValue(I.getOperand(0));
2170 SDOperand InVal = getValue(I.getOperand(1));
2171 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2172 getValue(I.getOperand(2)));
2174 SDOperand Num = *(InVec.Val->op_end()-2);
2175 SDOperand Typ = *(InVec.Val->op_end()-1);
2176 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2177 InVec, InVal, InIdx, Num, Typ));
2180 void SelectionDAGLowering::visitExtractElement(User &I) {
2181 SDOperand InVec = getValue(I.getOperand(0));
2182 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2183 getValue(I.getOperand(1)));
2184 SDOperand Typ = *(InVec.Val->op_end()-1);
2185 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2186 TLI.getValueType(I.getType()), InVec, InIdx));
2189 void SelectionDAGLowering::visitShuffleVector(User &I) {
2190 SDOperand V1 = getValue(I.getOperand(0));
2191 SDOperand V2 = getValue(I.getOperand(1));
2192 SDOperand Mask = getValue(I.getOperand(2));
2194 SDOperand Num = *(V1.Val->op_end()-2);
2195 SDOperand Typ = *(V2.Val->op_end()-1);
2196 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2197 V1, V2, Mask, Num, Typ));
2201 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2202 SDOperand N = getValue(I.getOperand(0));
2203 const Type *Ty = I.getOperand(0)->getType();
2205 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2208 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2209 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2212 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2213 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2214 getIntPtrConstant(Offset));
2216 Ty = StTy->getElementType(Field);
2218 Ty = cast<SequentialType>(Ty)->getElementType();
2220 // If this is a constant subscript, handle it quickly.
2221 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2222 if (CI->getZExtValue() == 0) continue;
2224 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2225 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2229 // N = N + Idx * ElementSize;
2230 uint64_t ElementSize = TD->getTypeSize(Ty);
2231 SDOperand IdxN = getValue(Idx);
2233 // If the index is smaller or larger than intptr_t, truncate or extend
2235 if (IdxN.getValueType() < N.getValueType()) {
2236 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2237 } else if (IdxN.getValueType() > N.getValueType())
2238 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2240 // If this is a multiply by a power of two, turn it into a shl
2241 // immediately. This is a very common case.
2242 if (isPowerOf2_64(ElementSize)) {
2243 unsigned Amt = Log2_64(ElementSize);
2244 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2245 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2246 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2250 SDOperand Scale = getIntPtrConstant(ElementSize);
2251 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2252 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2258 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2259 // If this is a fixed sized alloca in the entry block of the function,
2260 // allocate it statically on the stack.
2261 if (FuncInfo.StaticAllocaMap.count(&I))
2262 return; // getValue will auto-populate this.
2264 const Type *Ty = I.getAllocatedType();
2265 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
2267 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2270 SDOperand AllocSize = getValue(I.getArraySize());
2271 MVT::ValueType IntPtr = TLI.getPointerTy();
2272 if (IntPtr < AllocSize.getValueType())
2273 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2274 else if (IntPtr > AllocSize.getValueType())
2275 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2277 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2278 getIntPtrConstant(TySize));
2280 // Handle alignment. If the requested alignment is less than or equal to the
2281 // stack alignment, ignore it and round the size of the allocation up to the
2282 // stack alignment size. If the size is greater than the stack alignment, we
2283 // note this in the DYNAMIC_STACKALLOC node.
2284 unsigned StackAlign =
2285 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2286 if (Align <= StackAlign) {
2288 // Add SA-1 to the size.
2289 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2290 getIntPtrConstant(StackAlign-1));
2291 // Mask out the low bits for alignment purposes.
2292 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2293 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2296 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
2297 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2299 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2301 DAG.setRoot(DSA.getValue(1));
2303 // Inform the Frame Information that we have just allocated a variable-sized
2305 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2308 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2309 SDOperand Ptr = getValue(I.getOperand(0));
2315 // Do not serialize non-volatile loads against each other.
2316 Root = DAG.getRoot();
2319 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2320 Root, I.isVolatile(), I.getAlignment()));
2323 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2324 const Value *SV, SDOperand Root,
2326 unsigned Alignment) {
2328 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
2329 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
2330 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2331 DAG.getSrcValue(SV));
2333 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2334 isVolatile, Alignment);
2338 DAG.setRoot(L.getValue(1));
2340 PendingLoads.push_back(L.getValue(1));
2346 void SelectionDAGLowering::visitStore(StoreInst &I) {
2347 Value *SrcV = I.getOperand(0);
2348 SDOperand Src = getValue(SrcV);
2349 SDOperand Ptr = getValue(I.getOperand(1));
2350 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2351 I.isVolatile(), I.getAlignment()));
2354 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2355 /// access memory and has no other side effects at all.
2356 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2357 #define GET_NO_MEMORY_INTRINSICS
2358 #include "llvm/Intrinsics.gen"
2359 #undef GET_NO_MEMORY_INTRINSICS
2363 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2364 // have any side-effects or if it only reads memory.
2365 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2366 #define GET_SIDE_EFFECT_INFO
2367 #include "llvm/Intrinsics.gen"
2368 #undef GET_SIDE_EFFECT_INFO
2372 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2374 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2375 unsigned Intrinsic) {
2376 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
2377 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
2379 // Build the operand list.
2380 SmallVector<SDOperand, 8> Ops;
2381 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2383 // We don't need to serialize loads against other loads.
2384 Ops.push_back(DAG.getRoot());
2386 Ops.push_back(getRoot());
2390 // Add the intrinsic ID as an integer operand.
2391 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2393 // Add all operands of the call to the operand list.
2394 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2395 SDOperand Op = getValue(I.getOperand(i));
2397 // If this is a vector type, force it to the right vector type.
2398 if (Op.getValueType() == MVT::Vector) {
2399 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
2400 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2402 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2403 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2404 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2407 assert(TLI.isTypeLegal(Op.getValueType()) &&
2408 "Intrinsic uses a non-legal type?");
2412 std::vector<MVT::ValueType> VTs;
2413 if (I.getType() != Type::VoidTy) {
2414 MVT::ValueType VT = TLI.getValueType(I.getType());
2415 if (VT == MVT::Vector) {
2416 const VectorType *DestTy = cast<VectorType>(I.getType());
2417 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2419 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2420 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2423 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2427 VTs.push_back(MVT::Other);
2429 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2434 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2435 &Ops[0], Ops.size());
2436 else if (I.getType() != Type::VoidTy)
2437 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2438 &Ops[0], Ops.size());
2440 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2441 &Ops[0], Ops.size());
2444 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2446 PendingLoads.push_back(Chain);
2450 if (I.getType() != Type::VoidTy) {
2451 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2452 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2453 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2454 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2455 DAG.getValueType(EVT));
2457 setValue(&I, Result);
2461 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2462 /// we want to emit this as a call to a named external function, return the name
2463 /// otherwise lower it and return null.
2465 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2466 switch (Intrinsic) {
2468 // By default, turn this into a target intrinsic node.
2469 visitTargetIntrinsic(I, Intrinsic);
2471 case Intrinsic::vastart: visitVAStart(I); return 0;
2472 case Intrinsic::vaend: visitVAEnd(I); return 0;
2473 case Intrinsic::vacopy: visitVACopy(I); return 0;
2474 case Intrinsic::returnaddress:
2475 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2476 getValue(I.getOperand(1))));
2478 case Intrinsic::frameaddress:
2479 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2480 getValue(I.getOperand(1))));
2482 case Intrinsic::setjmp:
2483 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2485 case Intrinsic::longjmp:
2486 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2488 case Intrinsic::memcpy_i32:
2489 case Intrinsic::memcpy_i64:
2490 visitMemIntrinsic(I, ISD::MEMCPY);
2492 case Intrinsic::memset_i32:
2493 case Intrinsic::memset_i64:
2494 visitMemIntrinsic(I, ISD::MEMSET);
2496 case Intrinsic::memmove_i32:
2497 case Intrinsic::memmove_i64:
2498 visitMemIntrinsic(I, ISD::MEMMOVE);
2501 case Intrinsic::dbg_stoppoint: {
2502 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2503 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2504 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2508 Ops[1] = getValue(SPI.getLineValue());
2509 Ops[2] = getValue(SPI.getColumnValue());
2511 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2512 assert(DD && "Not a debug information descriptor");
2513 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2515 Ops[3] = DAG.getString(CompileUnit->getFileName());
2516 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2518 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2523 case Intrinsic::dbg_region_start: {
2524 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2525 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2526 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2527 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2528 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2529 DAG.getConstant(LabelID, MVT::i32)));
2534 case Intrinsic::dbg_region_end: {
2535 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2536 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2537 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2538 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2539 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2540 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2545 case Intrinsic::dbg_func_start: {
2546 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2547 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2548 if (MMI && FSI.getSubprogram() &&
2549 MMI->Verify(FSI.getSubprogram())) {
2550 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
2551 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2552 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2557 case Intrinsic::dbg_declare: {
2558 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2559 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2560 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
2561 SDOperand AddressOp = getValue(DI.getAddress());
2562 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2563 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
2569 case Intrinsic::eh_exception: {
2570 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2573 // Add a label to mark the beginning of the landing pad. Deletion of the
2574 // landing pad can thus be detected via the MachineModuleInfo.
2575 unsigned LabelID = MMI->addLandingPad(CurMBB);
2576 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2577 DAG.getConstant(LabelID, MVT::i32)));
2579 // Mark exception register as live in.
2580 unsigned Reg = TLI.getExceptionAddressRegister();
2581 if (Reg) CurMBB->addLiveIn(Reg);
2583 // Insert the EXCEPTIONADDR instruction.
2584 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2586 Ops[0] = DAG.getRoot();
2587 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2589 DAG.setRoot(Op.getValue(1));
2591 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2596 case Intrinsic::eh_selector:
2597 case Intrinsic::eh_filter:{
2598 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2601 // Inform the MachineModuleInfo of the personality for this landing pad.
2602 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2603 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2604 isa<Function>(CE->getOperand(0)) &&
2605 "Personality should be a function");
2606 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
2607 if (Intrinsic == Intrinsic::eh_filter)
2608 MMI->setIsFilterLandingPad(CurMBB);
2610 // Gather all the type infos for this landing pad and pass them along to
2611 // MachineModuleInfo.
2612 std::vector<GlobalVariable *> TyInfo;
2613 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2614 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2615 if (CE && CE->getOpcode() == Instruction::BitCast &&
2616 isa<GlobalVariable>(CE->getOperand(0))) {
2617 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2619 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2620 assert(CI && CI->getZExtValue() == 0 &&
2621 "TypeInfo must be a global variable typeinfo or NULL");
2622 TyInfo.push_back(NULL);
2625 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2627 // Mark exception selector register as live in.
2628 unsigned Reg = TLI.getExceptionSelectorRegister();
2629 if (Reg) CurMBB->addLiveIn(Reg);
2631 // Insert the EHSELECTION instruction.
2632 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
2634 Ops[0] = getValue(I.getOperand(1));
2636 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2638 DAG.setRoot(Op.getValue(1));
2640 setValue(&I, DAG.getConstant(0, MVT::i32));
2646 case Intrinsic::eh_typeid_for: {
2647 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2650 // Find the type id for the given typeinfo.
2651 GlobalVariable *GV = NULL;
2652 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2653 if (CE && CE->getOpcode() == Instruction::BitCast &&
2654 isa<GlobalVariable>(CE->getOperand(0))) {
2655 GV = cast<GlobalVariable>(CE->getOperand(0));
2657 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2658 assert(CI && CI->getZExtValue() == 0 &&
2659 "TypeInfo must be a global variable typeinfo or NULL");
2663 unsigned TypeID = MMI->getTypeIDFor(GV);
2664 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2666 setValue(&I, DAG.getConstant(0, MVT::i32));
2672 case Intrinsic::sqrt_f32:
2673 case Intrinsic::sqrt_f64:
2674 setValue(&I, DAG.getNode(ISD::FSQRT,
2675 getValue(I.getOperand(1)).getValueType(),
2676 getValue(I.getOperand(1))));
2678 case Intrinsic::powi_f32:
2679 case Intrinsic::powi_f64:
2680 setValue(&I, DAG.getNode(ISD::FPOWI,
2681 getValue(I.getOperand(1)).getValueType(),
2682 getValue(I.getOperand(1)),
2683 getValue(I.getOperand(2))));
2685 case Intrinsic::pcmarker: {
2686 SDOperand Tmp = getValue(I.getOperand(1));
2687 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2690 case Intrinsic::readcyclecounter: {
2691 SDOperand Op = getRoot();
2692 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2693 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2696 DAG.setRoot(Tmp.getValue(1));
2699 case Intrinsic::part_select: {
2700 // Currently not implemented: just abort
2701 assert(0 && "part_select intrinsic not implemented");
2704 case Intrinsic::part_set: {
2705 // Currently not implemented: just abort
2706 assert(0 && "part_set intrinsic not implemented");
2709 case Intrinsic::bswap:
2710 setValue(&I, DAG.getNode(ISD::BSWAP,
2711 getValue(I.getOperand(1)).getValueType(),
2712 getValue(I.getOperand(1))));
2714 case Intrinsic::cttz: {
2715 SDOperand Arg = getValue(I.getOperand(1));
2716 MVT::ValueType Ty = Arg.getValueType();
2717 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2719 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2720 else if (Ty > MVT::i32)
2721 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2722 setValue(&I, result);
2725 case Intrinsic::ctlz: {
2726 SDOperand Arg = getValue(I.getOperand(1));
2727 MVT::ValueType Ty = Arg.getValueType();
2728 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2730 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2731 else if (Ty > MVT::i32)
2732 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2733 setValue(&I, result);
2736 case Intrinsic::ctpop: {
2737 SDOperand Arg = getValue(I.getOperand(1));
2738 MVT::ValueType Ty = Arg.getValueType();
2739 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2741 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2742 else if (Ty > MVT::i32)
2743 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2744 setValue(&I, result);
2747 case Intrinsic::stacksave: {
2748 SDOperand Op = getRoot();
2749 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2750 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2752 DAG.setRoot(Tmp.getValue(1));
2755 case Intrinsic::stackrestore: {
2756 SDOperand Tmp = getValue(I.getOperand(1));
2757 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2760 case Intrinsic::prefetch:
2761 // FIXME: Currently discarding prefetches.
2767 void SelectionDAGLowering::LowerCallTo(Instruction &I,
2768 const Type *CalledValueTy,
2769 unsigned CallingConv,
2771 SDOperand Callee, unsigned OpIdx) {
2772 const PointerType *PT = cast<PointerType>(CalledValueTy);
2773 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2774 const ParamAttrsList *Attrs = FTy->getParamAttrs();
2776 TargetLowering::ArgListTy Args;
2777 TargetLowering::ArgListEntry Entry;
2778 Args.reserve(I.getNumOperands());
2779 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2780 Value *Arg = I.getOperand(i);
2781 SDOperand ArgNode = getValue(Arg);
2782 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2783 Entry.isSExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::SExt);
2784 Entry.isZExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::ZExt);
2785 Entry.isInReg = Attrs && Attrs->paramHasAttr(i, ParamAttr::InReg);
2786 Entry.isSRet = Attrs && Attrs->paramHasAttr(i, ParamAttr::StructRet);
2787 Args.push_back(Entry);
2790 std::pair<SDOperand,SDOperand> Result =
2791 TLI.LowerCallTo(getRoot(), I.getType(),
2792 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
2793 FTy->isVarArg(), CallingConv, IsTailCall,
2795 if (I.getType() != Type::VoidTy)
2796 setValue(&I, Result.first);
2797 DAG.setRoot(Result.second);
2801 void SelectionDAGLowering::visitCall(CallInst &I) {
2802 const char *RenameFn = 0;
2803 if (Function *F = I.getCalledFunction()) {
2804 if (F->isDeclaration())
2805 if (unsigned IID = F->getIntrinsicID()) {
2806 RenameFn = visitIntrinsicCall(I, IID);
2809 } else { // Not an LLVM intrinsic.
2810 const std::string &Name = F->getName();
2811 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2812 if (I.getNumOperands() == 3 && // Basic sanity checks.
2813 I.getOperand(1)->getType()->isFloatingPoint() &&
2814 I.getType() == I.getOperand(1)->getType() &&
2815 I.getType() == I.getOperand(2)->getType()) {
2816 SDOperand LHS = getValue(I.getOperand(1));
2817 SDOperand RHS = getValue(I.getOperand(2));
2818 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2822 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2823 if (I.getNumOperands() == 2 && // Basic sanity checks.
2824 I.getOperand(1)->getType()->isFloatingPoint() &&
2825 I.getType() == I.getOperand(1)->getType()) {
2826 SDOperand Tmp = getValue(I.getOperand(1));
2827 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2830 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2831 if (I.getNumOperands() == 2 && // Basic sanity checks.
2832 I.getOperand(1)->getType()->isFloatingPoint() &&
2833 I.getType() == I.getOperand(1)->getType()) {
2834 SDOperand Tmp = getValue(I.getOperand(1));
2835 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2838 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2839 if (I.getNumOperands() == 2 && // Basic sanity checks.
2840 I.getOperand(1)->getType()->isFloatingPoint() &&
2841 I.getType() == I.getOperand(1)->getType()) {
2842 SDOperand Tmp = getValue(I.getOperand(1));
2843 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2848 } else if (isa<InlineAsm>(I.getOperand(0))) {
2855 Callee = getValue(I.getOperand(0));
2857 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2859 LowerCallTo(I, I.getCalledValue()->getType(),
2867 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2868 SDOperand &Chain, SDOperand &Flag)const{
2869 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2870 Chain = Val.getValue(1);
2871 Flag = Val.getValue(2);
2873 // If the result was expanded, copy from the top part.
2874 if (Regs.size() > 1) {
2875 assert(Regs.size() == 2 &&
2876 "Cannot expand to more than 2 elts yet!");
2877 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2878 Chain = Hi.getValue(1);
2879 Flag = Hi.getValue(2);
2880 if (DAG.getTargetLoweringInfo().isLittleEndian())
2881 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2883 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2886 // Otherwise, if the return value was promoted or extended, truncate it to the
2887 // appropriate type.
2888 if (RegVT == ValueVT)
2891 if (MVT::isVector(RegVT)) {
2892 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2893 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2894 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2896 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2899 if (MVT::isInteger(RegVT)) {
2900 if (ValueVT < RegVT)
2901 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2903 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2906 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2907 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2910 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2911 /// specified value into the registers specified by this object. This uses
2912 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2913 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2914 SDOperand &Chain, SDOperand &Flag,
2915 MVT::ValueType PtrVT) const {
2916 if (Regs.size() == 1) {
2917 // If there is a single register and the types differ, this must be
2919 if (RegVT != ValueVT) {
2920 if (MVT::isVector(RegVT)) {
2921 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2922 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
2923 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
2924 if (RegVT < ValueVT)
2925 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2927 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2928 } else if (MVT::isFloatingPoint(RegVT) &&
2929 MVT::isFloatingPoint(Val.getValueType())) {
2930 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2931 } else if (MVT::getSizeInBits(RegVT) ==
2932 MVT::getSizeInBits(Val.getValueType())) {
2933 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2935 assert(0 && "Unknown mismatch!");
2938 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2939 Flag = Chain.getValue(1);
2941 std::vector<unsigned> R(Regs);
2942 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2943 std::reverse(R.begin(), R.end());
2945 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2946 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2947 DAG.getConstant(i, PtrVT));
2948 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2949 Flag = Chain.getValue(1);
2954 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2955 /// operand list. This adds the code marker and includes the number of
2956 /// values added into it.
2957 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2958 std::vector<SDOperand> &Ops) const {
2959 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2960 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
2961 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2962 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2965 /// isAllocatableRegister - If the specified register is safe to allocate,
2966 /// i.e. it isn't a stack pointer or some other special register, return the
2967 /// register class for the register. Otherwise, return null.
2968 static const TargetRegisterClass *
2969 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2970 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2971 MVT::ValueType FoundVT = MVT::Other;
2972 const TargetRegisterClass *FoundRC = 0;
2973 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2974 E = MRI->regclass_end(); RCI != E; ++RCI) {
2975 MVT::ValueType ThisVT = MVT::Other;
2977 const TargetRegisterClass *RC = *RCI;
2978 // If none of the the value types for this register class are valid, we
2979 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2980 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2982 if (TLI.isTypeLegal(*I)) {
2983 // If we have already found this register in a different register class,
2984 // choose the one with the largest VT specified. For example, on
2985 // PowerPC, we favor f64 register classes over f32.
2986 if (FoundVT == MVT::Other ||
2987 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2994 if (ThisVT == MVT::Other) continue;
2996 // NOTE: This isn't ideal. In particular, this might allocate the
2997 // frame pointer in functions that need it (due to them not being taken
2998 // out of allocation, because a variable sized allocation hasn't been seen
2999 // yet). This is a slight code pessimization, but should still work.
3000 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3001 E = RC->allocation_order_end(MF); I != E; ++I)
3003 // We found a matching register class. Keep looking at others in case
3004 // we find one with larger registers that this physreg is also in.
3013 RegsForValue SelectionDAGLowering::
3014 GetRegistersForValue(const std::string &ConstrCode,
3015 MVT::ValueType VT, bool isOutReg, bool isInReg,
3016 std::set<unsigned> &OutputRegs,
3017 std::set<unsigned> &InputRegs) {
3018 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3019 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
3020 std::vector<unsigned> Regs;
3022 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
3023 MVT::ValueType RegVT;
3024 MVT::ValueType ValueVT = VT;
3026 // If this is a constraint for a specific physical register, like {r17},
3028 if (PhysReg.first) {
3029 if (VT == MVT::Other)
3030 ValueVT = *PhysReg.second->vt_begin();
3032 // Get the actual register value type. This is important, because the user
3033 // may have asked for (e.g.) the AX register in i32 type. We need to
3034 // remember that AX is actually i16 to get the right extension.
3035 RegVT = *PhysReg.second->vt_begin();
3037 // This is a explicit reference to a physical register.
3038 Regs.push_back(PhysReg.first);
3040 // If this is an expanded reference, add the rest of the regs to Regs.
3042 TargetRegisterClass::iterator I = PhysReg.second->begin();
3043 TargetRegisterClass::iterator E = PhysReg.second->end();
3044 for (; *I != PhysReg.first; ++I)
3045 assert(I != E && "Didn't find reg!");
3047 // Already added the first reg.
3049 for (; NumRegs; --NumRegs, ++I) {
3050 assert(I != E && "Ran out of registers to allocate!");
3054 return RegsForValue(Regs, RegVT, ValueVT);
3057 // Otherwise, if this was a reference to an LLVM register class, create vregs
3058 // for this reference.
3059 std::vector<unsigned> RegClassRegs;
3060 if (PhysReg.second) {
3061 // If this is an early clobber or tied register, our regalloc doesn't know
3062 // how to maintain the constraint. If it isn't, go ahead and create vreg
3063 // and let the regalloc do the right thing.
3064 if (!isOutReg || !isInReg) {
3065 RegVT = *PhysReg.second->vt_begin();
3067 if (VT == MVT::Other)
3070 // Create the appropriate number of virtual registers.
3071 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
3072 for (; NumRegs; --NumRegs)
3073 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3075 return RegsForValue(Regs, RegVT, ValueVT);
3078 // Otherwise, we can't allocate it. Let the code below figure out how to
3079 // maintain these constraints.
3080 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3083 // This is a reference to a register class that doesn't directly correspond
3084 // to an LLVM register class. Allocate NumRegs consecutive, available,
3085 // registers from the class.
3086 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
3089 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3090 MachineFunction &MF = *CurMBB->getParent();
3091 unsigned NumAllocated = 0;
3092 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3093 unsigned Reg = RegClassRegs[i];
3094 // See if this register is available.
3095 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3096 (isInReg && InputRegs.count(Reg))) { // Already used.
3097 // Make sure we find consecutive registers.
3102 // Check to see if this register is allocatable (i.e. don't give out the
3104 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3106 // Make sure we find consecutive registers.
3111 // Okay, this register is good, we can use it.
3114 // If we allocated enough consecutive registers, succeed.
3115 if (NumAllocated == NumRegs) {
3116 unsigned RegStart = (i-NumAllocated)+1;
3117 unsigned RegEnd = i+1;
3118 // Mark all of the allocated registers used.
3119 for (unsigned i = RegStart; i != RegEnd; ++i) {
3120 unsigned Reg = RegClassRegs[i];
3121 Regs.push_back(Reg);
3122 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
3123 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
3126 return RegsForValue(Regs, *RC->vt_begin(), VT);
3130 // Otherwise, we couldn't allocate enough registers for this.
3131 return RegsForValue();
3134 /// getConstraintGenerality - Return an integer indicating how general CT is.
3135 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3137 default: assert(0 && "Unknown constraint type!");
3138 case TargetLowering::C_Other:
3139 case TargetLowering::C_Unknown:
3141 case TargetLowering::C_Register:
3143 case TargetLowering::C_RegisterClass:
3145 case TargetLowering::C_Memory:
3150 static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
3151 const TargetLowering &TLI) {
3152 assert(!C.empty() && "Must have at least one constraint");
3153 if (C.size() == 1) return C[0];
3155 std::string *Current = &C[0];
3156 // If we have multiple constraints, try to pick the most general one ahead
3157 // of time. This isn't a wonderful solution, but handles common cases.
3158 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0]);
3159 for (unsigned j = 1, e = C.size(); j != e; ++j) {
3160 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j]);
3161 if (getConstraintGenerality(ThisFlavor) >
3162 getConstraintGenerality(Flavor)) {
3163 // This constraint letter is more general than the previous one,
3165 Flavor = ThisFlavor;
3173 /// visitInlineAsm - Handle a call to an InlineAsm object.
3175 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3176 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
3178 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
3181 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
3182 std::vector<MVT::ValueType> ConstraintVTs;
3184 /// AsmNodeOperands - A list of pairs. The first element is a register, the
3185 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
3186 /// if it is a def of that register.
3187 std::vector<SDOperand> AsmNodeOperands;
3188 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3189 AsmNodeOperands.push_back(AsmStr);
3191 SDOperand Chain = getRoot();
3194 // We fully assign registers here at isel time. This is not optimal, but
3195 // should work. For register classes that correspond to LLVM classes, we
3196 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
3197 // over the constraints, collecting fixed registers that we know we can't use.
3198 std::set<unsigned> OutputRegs, InputRegs;
3200 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
3201 std::string ConstraintCode =
3202 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
3204 MVT::ValueType OpVT;
3206 // Compute the value type for each operand and add it to ConstraintVTs.
3207 switch (Constraints[i].Type) {
3208 case InlineAsm::isOutput:
3209 if (!Constraints[i].isIndirectOutput) {
3210 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3211 OpVT = TLI.getValueType(I.getType());
3213 const Type *OpTy = I.getOperand(OpNum)->getType();
3214 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
3215 OpNum++; // Consumes a call operand.
3218 case InlineAsm::isInput:
3219 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
3220 OpNum++; // Consumes a call operand.
3222 case InlineAsm::isClobber:
3227 ConstraintVTs.push_back(OpVT);
3229 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
3230 continue; // Not assigned a fixed reg.
3232 // Build a list of regs that this operand uses. This always has a single
3233 // element for promoted/expanded operands.
3234 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
3236 OutputRegs, InputRegs);
3238 switch (Constraints[i].Type) {
3239 case InlineAsm::isOutput:
3240 // We can't assign any other output to this register.
3241 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3242 // If this is an early-clobber output, it cannot be assigned to the same
3243 // value as the input reg.
3244 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
3245 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3247 case InlineAsm::isInput:
3248 // We can't assign any other input to this register.
3249 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3251 case InlineAsm::isClobber:
3252 // Clobbered regs cannot be used as inputs or outputs.
3253 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3254 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3259 // Loop over all of the inputs, copying the operand values into the
3260 // appropriate registers and processing the output regs.
3261 RegsForValue RetValRegs;
3262 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3265 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
3266 std::string ConstraintCode =
3267 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
3269 switch (Constraints[i].Type) {
3270 case InlineAsm::isOutput: {
3271 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3272 if (ConstraintCode.size() == 1) // not a physreg name.
3273 CTy = TLI.getConstraintType(ConstraintCode);
3275 if (CTy == TargetLowering::C_Memory) {
3277 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
3279 // Check that the operand (the address to store to) isn't a float.
3280 if (!MVT::isInteger(InOperandVal.getValueType()))
3281 assert(0 && "MATCH FAIL!");
3283 if (!Constraints[i].isIndirectOutput)
3284 assert(0 && "MATCH FAIL!");
3286 OpNum++; // Consumes a call operand.
3288 // Extend/truncate to the right pointer type if needed.
3289 MVT::ValueType PtrType = TLI.getPointerTy();
3290 if (InOperandVal.getValueType() < PtrType)
3291 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3292 else if (InOperandVal.getValueType() > PtrType)
3293 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3295 // Add information to the INLINEASM node to know about this output.
3296 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3297 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3298 AsmNodeOperands.push_back(InOperandVal);
3302 // Otherwise, this is a register output.
3303 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3305 // If this is an early-clobber output, or if there is an input
3306 // constraint that matches this, we need to reserve the input register
3307 // so no other inputs allocate to it.
3308 bool UsesInputRegister = false;
3309 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
3310 UsesInputRegister = true;
3312 // Copy the output from the appropriate register. Find a register that
3315 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3316 true, UsesInputRegister,
3317 OutputRegs, InputRegs);
3318 if (Regs.Regs.empty()) {
3319 cerr << "Couldn't allocate output reg for contraint '"
3320 << ConstraintCode << "'!\n";
3324 if (!Constraints[i].isIndirectOutput) {
3325 assert(RetValRegs.Regs.empty() &&
3326 "Cannot have multiple output constraints yet!");
3327 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3330 IndirectStoresToEmit.push_back(std::make_pair(Regs,
3331 I.getOperand(OpNum)));
3332 OpNum++; // Consumes a call operand.
3335 // Add information to the INLINEASM node to know that this register is
3337 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
3340 case InlineAsm::isInput: {
3341 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
3342 OpNum++; // Consumes a call operand.
3344 if (isdigit(ConstraintCode[0])) { // Matching constraint?
3345 // If this is required to match an output register we have already set,
3346 // just use its register.
3347 unsigned OperandNo = atoi(ConstraintCode.c_str());
3349 // Scan until we find the definition we already emitted of this operand.
3350 // When we find it, create a RegsForValue operand.
3351 unsigned CurOp = 2; // The first operand.
3352 for (; OperandNo; --OperandNo) {
3353 // Advance to the next operand.
3355 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3356 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3357 (NumOps & 7) == 4 /*MEM*/) &&
3358 "Skipped past definitions?");
3359 CurOp += (NumOps>>3)+1;
3363 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3364 if ((NumOps & 7) == 2 /*REGDEF*/) {
3365 // Add NumOps>>3 registers to MatchedRegs.
3366 RegsForValue MatchedRegs;
3367 MatchedRegs.ValueVT = InOperandVal.getValueType();
3368 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3369 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3371 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3372 MatchedRegs.Regs.push_back(Reg);
3375 // Use the produced MatchedRegs object to
3376 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3377 TLI.getPointerTy());
3378 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3381 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3382 assert(0 && "matching constraints for memory operands unimp");
3386 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
3387 if (ConstraintCode.size() == 1) // not a physreg name.
3388 CTy = TLI.getConstraintType(ConstraintCode);
3390 if (CTy == TargetLowering::C_Other) {
3391 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3392 ConstraintCode[0], DAG);
3393 if (!InOperandVal.Val) {
3394 cerr << "Invalid operand for inline asm constraint '"
3395 << ConstraintCode << "'!\n";
3399 // Add information to the INLINEASM node to know about this input.
3400 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3401 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3402 AsmNodeOperands.push_back(InOperandVal);
3404 } else if (CTy == TargetLowering::C_Memory) {
3407 // If the operand is a float, spill to a constant pool entry to get its
3409 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
3410 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
3412 if (!MVT::isInteger(InOperandVal.getValueType())) {
3413 cerr << "Match failed, cannot handle this yet!\n";
3414 InOperandVal.Val->dump();
3418 // Extend/truncate to the right pointer type if needed.
3419 MVT::ValueType PtrType = TLI.getPointerTy();
3420 if (InOperandVal.getValueType() < PtrType)
3421 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
3422 else if (InOperandVal.getValueType() > PtrType)
3423 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
3425 // Add information to the INLINEASM node to know about this input.
3426 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3427 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3428 AsmNodeOperands.push_back(InOperandVal);
3432 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
3434 // Copy the input into the appropriate registers.
3435 RegsForValue InRegs =
3436 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
3437 false, true, OutputRegs, InputRegs);
3438 // FIXME: should be match fail.
3439 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
3441 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
3443 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
3446 case InlineAsm::isClobber: {
3447 RegsForValue ClobberedRegs =
3448 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
3449 OutputRegs, InputRegs);
3450 // Add the clobbered value to the operand list, so that the register
3451 // allocator is aware that the physreg got clobbered.
3452 if (!ClobberedRegs.Regs.empty())
3453 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
3459 // Finish up input operands.
3460 AsmNodeOperands[0] = Chain;
3461 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3463 Chain = DAG.getNode(ISD::INLINEASM,
3464 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
3465 &AsmNodeOperands[0], AsmNodeOperands.size());
3466 Flag = Chain.getValue(1);
3468 // If this asm returns a register value, copy the result from that register
3469 // and set it as the value of the call.
3470 if (!RetValRegs.Regs.empty()) {
3471 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3473 // If the result of the inline asm is a vector, it may have the wrong
3474 // width/num elts. Make sure to convert it to the right type with
3476 if (Val.getValueType() == MVT::Vector) {
3477 const VectorType *VTy = cast<VectorType>(I.getType());
3478 unsigned DesiredNumElts = VTy->getNumElements();
3479 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3481 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3482 DAG.getConstant(DesiredNumElts, MVT::i32),
3483 DAG.getValueType(DesiredEltVT));
3489 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3491 // Process indirect outputs, first output all of the flagged copies out of
3493 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
3494 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
3495 Value *Ptr = IndirectStoresToEmit[i].second;
3496 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3497 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
3500 // Emit the non-flagged stores from the physregs.
3501 SmallVector<SDOperand, 8> OutChains;
3502 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
3503 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
3504 getValue(StoresToEmit[i].second),
3505 StoresToEmit[i].second, 0));
3506 if (!OutChains.empty())
3507 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3508 &OutChains[0], OutChains.size());
3513 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3514 SDOperand Src = getValue(I.getOperand(0));
3516 MVT::ValueType IntPtr = TLI.getPointerTy();
3518 if (IntPtr < Src.getValueType())
3519 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3520 else if (IntPtr > Src.getValueType())
3521 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
3523 // Scale the source by the type size.
3524 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
3525 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3526 Src, getIntPtrConstant(ElementSize));
3528 TargetLowering::ArgListTy Args;
3529 TargetLowering::ArgListEntry Entry;
3531 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3532 Args.push_back(Entry);
3534 std::pair<SDOperand,SDOperand> Result =
3535 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
3536 DAG.getExternalSymbol("malloc", IntPtr),
3538 setValue(&I, Result.first); // Pointers always fit in registers
3539 DAG.setRoot(Result.second);
3542 void SelectionDAGLowering::visitFree(FreeInst &I) {
3543 TargetLowering::ArgListTy Args;
3544 TargetLowering::ArgListEntry Entry;
3545 Entry.Node = getValue(I.getOperand(0));
3546 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3547 Args.push_back(Entry);
3548 MVT::ValueType IntPtr = TLI.getPointerTy();
3549 std::pair<SDOperand,SDOperand> Result =
3550 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
3551 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3552 DAG.setRoot(Result.second);
3555 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
3556 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3557 // instructions are special in various ways, which require special support to
3558 // insert. The specified MachineInstr is created but not inserted into any
3559 // basic blocks, and the scheduler passes ownership of it to this method.
3560 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3561 MachineBasicBlock *MBB) {
3562 cerr << "If a target marks an instruction with "
3563 << "'usesCustomDAGSchedInserter', it must implement "
3564 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
3569 void SelectionDAGLowering::visitVAStart(CallInst &I) {
3570 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3571 getValue(I.getOperand(1)),
3572 DAG.getSrcValue(I.getOperand(1))));
3575 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
3576 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3577 getValue(I.getOperand(0)),
3578 DAG.getSrcValue(I.getOperand(0)));
3580 DAG.setRoot(V.getValue(1));
3583 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
3584 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3585 getValue(I.getOperand(1)),
3586 DAG.getSrcValue(I.getOperand(1))));
3589 void SelectionDAGLowering::visitVACopy(CallInst &I) {
3590 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3591 getValue(I.getOperand(1)),
3592 getValue(I.getOperand(2)),
3593 DAG.getSrcValue(I.getOperand(1)),
3594 DAG.getSrcValue(I.getOperand(2))));
3597 /// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3598 /// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3599 static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3600 unsigned &i, SelectionDAG &DAG,
3601 TargetLowering &TLI) {
3602 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3603 return SDOperand(Arg, i++);
3605 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3606 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3608 return DAG.getNode(ISD::BIT_CONVERT, VT,
3609 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3610 } else if (NumVals == 2) {
3611 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3612 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3613 if (!TLI.isLittleEndian())
3615 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3617 // Value scalarized into many values. Unimp for now.
3618 assert(0 && "Cannot expand i64 -> i16 yet!");
3623 /// TargetLowering::LowerArguments - This is the default LowerArguments
3624 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
3625 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3626 /// integrated into SDISel.
3627 std::vector<SDOperand>
3628 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
3629 const FunctionType *FTy = F.getFunctionType();
3630 const ParamAttrsList *Attrs = FTy->getParamAttrs();
3631 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3632 std::vector<SDOperand> Ops;
3633 Ops.push_back(DAG.getRoot());
3634 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3635 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3637 // Add one result value for each formal argument.
3638 std::vector<MVT::ValueType> RetVals;
3640 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3642 MVT::ValueType VT = getValueType(I->getType());
3643 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3644 unsigned OriginalAlignment =
3645 getTargetData()->getABITypeAlignment(I->getType());
3647 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3648 // that is zero extended!
3649 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
3650 Flags &= ~(ISD::ParamFlags::SExt);
3651 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
3652 Flags |= ISD::ParamFlags::SExt;
3653 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
3654 Flags |= ISD::ParamFlags::InReg;
3655 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
3656 Flags |= ISD::ParamFlags::StructReturn;
3657 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
3659 switch (getTypeAction(VT)) {
3660 default: assert(0 && "Unknown type action!");
3662 RetVals.push_back(VT);
3663 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3666 RetVals.push_back(getTypeToTransformTo(VT));
3667 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3670 if (VT != MVT::Vector) {
3671 // If this is a large integer, it needs to be broken up into small
3672 // integers. Figure out what the destination type is and how many small
3673 // integers it turns into.
3674 MVT::ValueType NVT = getTypeToExpandTo(VT);
3675 unsigned NumVals = getNumElements(VT);
3676 for (unsigned i = 0; i != NumVals; ++i) {
3677 RetVals.push_back(NVT);
3678 // if it isn't first piece, alignment must be 1
3680 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3681 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3682 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3685 // Otherwise, this is a vector type. We only support legal vectors
3687 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3688 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
3690 // Figure out if there is a Packed type corresponding to this Vector
3691 // type. If so, convert to the vector type.
3692 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3693 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3694 RetVals.push_back(TVT);
3695 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3697 assert(0 && "Don't support illegal by-val vector arguments yet!");
3704 RetVals.push_back(MVT::Other);
3707 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3708 DAG.getNodeValueTypes(RetVals), RetVals.size(),
3709 &Ops[0], Ops.size()).Val;
3711 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
3713 // Set up the return result vector.
3717 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3719 MVT::ValueType VT = getValueType(I->getType());
3721 switch (getTypeAction(VT)) {
3722 default: assert(0 && "Unknown type action!");
3724 Ops.push_back(SDOperand(Result, i++));
3727 SDOperand Op(Result, i++);
3728 if (MVT::isInteger(VT)) {
3729 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
3730 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3731 DAG.getValueType(VT));
3732 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
3733 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3734 DAG.getValueType(VT));
3735 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3737 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3738 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3744 if (VT != MVT::Vector) {
3745 // If this is a large integer or a floating point node that needs to be
3746 // expanded, it needs to be reassembled from small integers. Figure out
3747 // what the source elt type is and how many small integers it is.
3748 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
3750 // Otherwise, this is a vector type. We only support legal vectors
3752 const VectorType *PTy = cast<VectorType>(I->getType());
3753 unsigned NumElems = PTy->getNumElements();
3754 const Type *EltTy = PTy->getElementType();
3756 // Figure out if there is a Packed type corresponding to this Vector
3757 // type. If so, convert to the vector type.
3758 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3759 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3760 SDOperand N = SDOperand(Result, i++);
3761 // Handle copies from generic vectors to registers.
3762 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3763 DAG.getConstant(NumElems, MVT::i32),
3764 DAG.getValueType(getValueType(EltTy)));
3767 assert(0 && "Don't support illegal by-val vector arguments yet!");
3778 /// ExpandScalarCallArgs - Recursively expand call argument node by
3779 /// bit_converting it or extract a pair of elements from the larger node.
3780 static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3782 SmallVector<SDOperand, 32> &Ops,
3784 TargetLowering &TLI,
3785 bool isFirst = true) {
3787 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3788 // if it isn't first piece, alignment must be 1
3790 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3791 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3793 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3797 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3798 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3800 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3801 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
3802 } else if (NumVals == 2) {
3803 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3804 DAG.getConstant(0, TLI.getPointerTy()));
3805 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3806 DAG.getConstant(1, TLI.getPointerTy()));
3807 if (!TLI.isLittleEndian())
3809 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3810 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
3812 // Value scalarized into many values. Unimp for now.
3813 assert(0 && "Cannot expand i64 -> i16 yet!");
3817 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
3818 /// implementation, which just inserts an ISD::CALL node, which is later custom
3819 /// lowered by the target to something concrete. FIXME: When all targets are
3820 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3821 std::pair<SDOperand, SDOperand>
3822 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3823 bool RetTyIsSigned, bool isVarArg,
3824 unsigned CallingConv, bool isTailCall,
3826 ArgListTy &Args, SelectionDAG &DAG) {
3827 SmallVector<SDOperand, 32> Ops;
3828 Ops.push_back(Chain); // Op#0 - Chain
3829 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3830 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3831 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3832 Ops.push_back(Callee);
3834 // Handle all of the outgoing arguments.
3835 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3836 MVT::ValueType VT = getValueType(Args[i].Ty);
3837 SDOperand Op = Args[i].Node;
3838 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3839 unsigned OriginalAlignment =
3840 getTargetData()->getABITypeAlignment(Args[i].Ty);
3843 Flags |= ISD::ParamFlags::SExt;
3845 Flags |= ISD::ParamFlags::ZExt;
3846 if (Args[i].isInReg)
3847 Flags |= ISD::ParamFlags::InReg;
3849 Flags |= ISD::ParamFlags::StructReturn;
3850 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
3852 switch (getTypeAction(VT)) {
3853 default: assert(0 && "Unknown type action!");
3856 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3859 if (MVT::isInteger(VT)) {
3862 ExtOp = ISD::SIGN_EXTEND;
3863 else if (Args[i].isZExt)
3864 ExtOp = ISD::ZERO_EXTEND;
3866 ExtOp = ISD::ANY_EXTEND;
3867 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3869 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3870 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3873 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3876 if (VT != MVT::Vector) {
3877 // If this is a large integer, it needs to be broken down into small
3878 // integers. Figure out what the source elt type is and how many small
3880 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
3882 // Otherwise, this is a vector type. We only support legal vectors
3884 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
3885 unsigned NumElems = PTy->getNumElements();
3886 const Type *EltTy = PTy->getElementType();
3888 // Figure out if there is a Packed type corresponding to this Vector
3889 // type. If so, convert to the vector type.
3890 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3891 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3892 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
3893 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3895 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3897 assert(0 && "Don't support illegal by-val vector call args yet!");
3905 // Figure out the result value types.
3906 SmallVector<MVT::ValueType, 4> RetTys;
3908 if (RetTy != Type::VoidTy) {
3909 MVT::ValueType VT = getValueType(RetTy);
3910 switch (getTypeAction(VT)) {
3911 default: assert(0 && "Unknown type action!");
3913 RetTys.push_back(VT);
3916 RetTys.push_back(getTypeToTransformTo(VT));
3919 if (VT != MVT::Vector) {
3920 // If this is a large integer, it needs to be reassembled from small
3921 // integers. Figure out what the source elt type is and how many small
3923 MVT::ValueType NVT = getTypeToExpandTo(VT);
3924 unsigned NumVals = getNumElements(VT);
3925 for (unsigned i = 0; i != NumVals; ++i)
3926 RetTys.push_back(NVT);
3928 // Otherwise, this is a vector type. We only support legal vectors
3930 const VectorType *PTy = cast<VectorType>(RetTy);
3931 unsigned NumElems = PTy->getNumElements();
3932 const Type *EltTy = PTy->getElementType();
3934 // Figure out if there is a Packed type corresponding to this Vector
3935 // type. If so, convert to the vector type.
3936 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3937 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3938 RetTys.push_back(TVT);
3940 assert(0 && "Don't support illegal by-val vector call results yet!");
3947 RetTys.push_back(MVT::Other); // Always has a chain.
3949 // Finally, create the CALL node.
3950 SDOperand Res = DAG.getNode(ISD::CALL,
3951 DAG.getVTList(&RetTys[0], RetTys.size()),
3952 &Ops[0], Ops.size());
3954 // This returns a pair of operands. The first element is the
3955 // return value for the function (if RetTy is not VoidTy). The second
3956 // element is the outgoing token chain.
3958 if (RetTys.size() != 1) {
3959 MVT::ValueType VT = getValueType(RetTy);
3960 if (RetTys.size() == 2) {
3963 // If this value was promoted, truncate it down.
3964 if (ResVal.getValueType() != VT) {
3965 if (VT == MVT::Vector) {
3966 // Insert a VBIT_CONVERT to convert from the packed result type to the
3967 // MVT::Vector type.
3968 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3969 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
3971 // Figure out if there is a Packed type corresponding to this Vector
3972 // type. If so, convert to the vector type.
3973 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
3974 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3975 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3976 // "N x PTyElementVT" MVT::Vector type.
3977 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
3978 DAG.getConstant(NumElems, MVT::i32),
3979 DAG.getValueType(getValueType(EltTy)));
3983 } else if (MVT::isInteger(VT)) {
3984 unsigned AssertOp = ISD::AssertSext;
3986 AssertOp = ISD::AssertZext;
3987 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3988 DAG.getValueType(VT));
3989 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3991 assert(MVT::isFloatingPoint(VT));
3992 if (getTypeAction(VT) == Expand)
3993 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3995 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3998 } else if (RetTys.size() == 3) {
3999 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4000 Res.getValue(0), Res.getValue(1));
4003 assert(0 && "Case not handled yet!");
4007 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4010 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4011 assert(0 && "LowerOperation not implemented for this target!");
4016 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4017 SelectionDAG &DAG) {
4018 assert(0 && "CustomPromoteOperation not implemented for this target!");
4023 /// getMemsetValue - Vectorized representation of the memset value
4025 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
4026 SelectionDAG &DAG) {
4027 MVT::ValueType CurVT = VT;
4028 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4029 uint64_t Val = C->getValue() & 255;
4031 while (CurVT != MVT::i8) {
4032 Val = (Val << Shift) | Val;
4034 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4036 return DAG.getConstant(Val, VT);
4038 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4040 while (CurVT != MVT::i8) {
4042 DAG.getNode(ISD::OR, VT,
4043 DAG.getNode(ISD::SHL, VT, Value,
4044 DAG.getConstant(Shift, MVT::i8)), Value);
4046 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4053 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4054 /// used when a memcpy is turned into a memset when the source is a constant
4056 static SDOperand getMemsetStringVal(MVT::ValueType VT,
4057 SelectionDAG &DAG, TargetLowering &TLI,
4058 std::string &Str, unsigned Offset) {
4060 unsigned MSB = getSizeInBits(VT) / 8;
4061 if (TLI.isLittleEndian())
4062 Offset = Offset + MSB - 1;
4063 for (unsigned i = 0; i != MSB; ++i) {
4064 Val = (Val << 8) | (unsigned char)Str[Offset];
4065 Offset += TLI.isLittleEndian() ? -1 : 1;
4067 return DAG.getConstant(Val, VT);
4070 /// getMemBasePlusOffset - Returns base and offset node for the
4071 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4072 SelectionDAG &DAG, TargetLowering &TLI) {
4073 MVT::ValueType VT = Base.getValueType();
4074 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4077 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
4078 /// to replace the memset / memcpy is below the threshold. It also returns the
4079 /// types of the sequence of memory ops to perform memset / memcpy.
4080 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4081 unsigned Limit, uint64_t Size,
4082 unsigned Align, TargetLowering &TLI) {
4085 if (TLI.allowsUnalignedMemoryAccesses()) {
4088 switch (Align & 7) {
4104 MVT::ValueType LVT = MVT::i64;
4105 while (!TLI.isTypeLegal(LVT))
4106 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4107 assert(MVT::isInteger(LVT));
4112 unsigned NumMemOps = 0;
4114 unsigned VTSize = getSizeInBits(VT) / 8;
4115 while (VTSize > Size) {
4116 VT = (MVT::ValueType)((unsigned)VT - 1);
4119 assert(MVT::isInteger(VT));
4121 if (++NumMemOps > Limit)
4123 MemOps.push_back(VT);
4130 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
4131 SDOperand Op1 = getValue(I.getOperand(1));
4132 SDOperand Op2 = getValue(I.getOperand(2));
4133 SDOperand Op3 = getValue(I.getOperand(3));
4134 SDOperand Op4 = getValue(I.getOperand(4));
4135 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4136 if (Align == 0) Align = 1;
4138 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4139 std::vector<MVT::ValueType> MemOps;
4141 // Expand memset / memcpy to a series of load / store ops
4142 // if the size operand falls below a certain threshold.
4143 SmallVector<SDOperand, 8> OutChains;
4145 default: break; // Do nothing for now.
4147 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4148 Size->getValue(), Align, TLI)) {
4149 unsigned NumMemOps = MemOps.size();
4150 unsigned Offset = 0;
4151 for (unsigned i = 0; i < NumMemOps; i++) {
4152 MVT::ValueType VT = MemOps[i];
4153 unsigned VTSize = getSizeInBits(VT) / 8;
4154 SDOperand Value = getMemsetValue(Op2, VT, DAG);
4155 SDOperand Store = DAG.getStore(getRoot(), Value,
4156 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
4157 I.getOperand(1), Offset);
4158 OutChains.push_back(Store);
4165 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4166 Size->getValue(), Align, TLI)) {
4167 unsigned NumMemOps = MemOps.size();
4168 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
4169 GlobalAddressSDNode *G = NULL;
4171 bool CopyFromStr = false;
4173 if (Op2.getOpcode() == ISD::GlobalAddress)
4174 G = cast<GlobalAddressSDNode>(Op2);
4175 else if (Op2.getOpcode() == ISD::ADD &&
4176 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4177 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4178 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
4179 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
4182 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
4183 if (GV && GV->isConstant()) {
4184 Str = GV->getStringValue(false);
4192 for (unsigned i = 0; i < NumMemOps; i++) {
4193 MVT::ValueType VT = MemOps[i];
4194 unsigned VTSize = getSizeInBits(VT) / 8;
4195 SDOperand Value, Chain, Store;
4198 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4201 DAG.getStore(Chain, Value,
4202 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4203 I.getOperand(1), DstOff);
4205 Value = DAG.getLoad(VT, getRoot(),
4206 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
4207 I.getOperand(2), SrcOff);
4208 Chain = Value.getValue(1);
4210 DAG.getStore(Chain, Value,
4211 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4212 I.getOperand(1), DstOff);
4214 OutChains.push_back(Store);
4223 if (!OutChains.empty()) {
4224 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4225 &OutChains[0], OutChains.size()));
4230 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
4233 //===----------------------------------------------------------------------===//
4234 // SelectionDAGISel code
4235 //===----------------------------------------------------------------------===//
4237 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4238 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4241 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4242 AU.addRequired<AliasAnalysis>();
4243 AU.setPreservesAll();
4248 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4249 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4250 RegMap = MF.getSSARegMap();
4251 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4253 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4255 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4256 SelectBasicBlock(I, MF, FuncInfo);
4258 // Add function live-ins to entry block live-in set.
4259 BasicBlock *EntryBB = &Fn.getEntryBlock();
4260 BB = FuncInfo.MBBMap[EntryBB];
4261 if (!MF.livein_empty())
4262 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4263 E = MF.livein_end(); I != E; ++I)
4264 BB->addLiveIn(I->first);
4269 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4271 SDOperand Op = getValue(V);
4272 assert((Op.getOpcode() != ISD::CopyFromReg ||
4273 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4274 "Copy from a reg to the same reg!");
4276 // If this type is not legal, we must make sure to not create an invalid
4278 MVT::ValueType SrcVT = Op.getValueType();
4279 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
4280 if (SrcVT == DestVT) {
4281 return DAG.getCopyToReg(getRoot(), Reg, Op);
4282 } else if (SrcVT == MVT::Vector) {
4283 // Handle copies from generic vectors to registers.
4284 MVT::ValueType PTyElementVT, PTyLegalElementVT;
4285 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
4286 PTyElementVT, PTyLegalElementVT);
4288 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4289 // MVT::Vector type.
4290 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4291 DAG.getConstant(NE, MVT::i32),
4292 DAG.getValueType(PTyElementVT));
4294 // Loop over all of the elements of the resultant vector,
4295 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4296 // copying them into output registers.
4297 SmallVector<SDOperand, 8> OutChains;
4298 SDOperand Root = getRoot();
4299 for (unsigned i = 0; i != NE; ++i) {
4300 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
4301 Op, DAG.getConstant(i, TLI.getPointerTy()));
4302 if (PTyElementVT == PTyLegalElementVT) {
4303 // Elements are legal.
4304 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4305 } else if (PTyLegalElementVT > PTyElementVT) {
4306 // Elements are promoted.
4307 if (MVT::isFloatingPoint(PTyLegalElementVT))
4308 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4310 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4311 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4313 // Elements are expanded.
4314 // The src value is expanded into multiple registers.
4315 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
4316 Elt, DAG.getConstant(0, TLI.getPointerTy()));
4317 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
4318 Elt, DAG.getConstant(1, TLI.getPointerTy()));
4319 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4320 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4323 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4324 &OutChains[0], OutChains.size());
4325 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
4326 // The src value is promoted to the register.
4327 if (MVT::isFloatingPoint(SrcVT))
4328 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4330 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
4331 return DAG.getCopyToReg(getRoot(), Reg, Op);
4333 DestVT = TLI.getTypeToExpandTo(SrcVT);
4334 unsigned NumVals = TLI.getNumElements(SrcVT);
4336 return DAG.getCopyToReg(getRoot(), Reg,
4337 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4338 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
4339 // The src value is expanded into multiple registers.
4340 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4341 Op, DAG.getConstant(0, TLI.getPointerTy()));
4342 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4343 Op, DAG.getConstant(1, TLI.getPointerTy()));
4344 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
4345 return DAG.getCopyToReg(Op, Reg+1, Hi);
4349 void SelectionDAGISel::
4350 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
4351 std::vector<SDOperand> &UnorderedChains) {
4352 // If this is the entry block, emit arguments.
4353 Function &F = *LLVMBB->getParent();
4354 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4355 SDOperand OldRoot = SDL.DAG.getRoot();
4356 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4359 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4361 if (!AI->use_empty()) {
4362 SDL.setValue(AI, Args[a]);
4364 // If this argument is live outside of the entry block, insert a copy from
4365 // whereever we got it to the vreg that other BB's will reference it as.
4366 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4367 if (VMI != FuncInfo.ValueMap.end()) {
4368 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
4369 UnorderedChains.push_back(Copy);
4373 // Finally, if the target has anything special to do, allow it to do so.
4374 // FIXME: this should insert code into the DAG!
4375 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4378 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4379 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4380 FunctionLoweringInfo &FuncInfo) {
4381 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
4383 std::vector<SDOperand> UnorderedChains;
4385 // Lower any arguments needed in this block if this is the entry block.
4386 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4387 LowerArguments(LLVMBB, SDL, UnorderedChains);
4389 BB = FuncInfo.MBBMap[LLVMBB];
4390 SDL.setCurrentBasicBlock(BB);
4392 // Lower all of the non-terminator instructions.
4393 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4397 // Lower call part of invoke.
4398 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4399 if (Invoke) SDL.visitInvoke(*Invoke, false);
4401 // Ensure that all instructions which are used outside of their defining
4402 // blocks are available as virtual registers.
4403 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4404 if (!I->use_empty() && !isa<PHINode>(I)) {
4405 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4406 if (VMI != FuncInfo.ValueMap.end())
4407 UnorderedChains.push_back(
4408 SDL.CopyValueToVirtualRegister(I, VMI->second));
4411 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4412 // ensure constants are generated when needed. Remember the virtual registers
4413 // that need to be added to the Machine PHI nodes as input. We cannot just
4414 // directly add them, because expansion might result in multiple MBB's for one
4415 // BB. As such, the start of the BB might correspond to a different MBB than
4418 TerminatorInst *TI = LLVMBB->getTerminator();
4420 // Emit constants only once even if used by multiple PHI nodes.
4421 std::map<Constant*, unsigned> ConstantsOut;
4423 // Vector bool would be better, but vector<bool> is really slow.
4424 std::vector<unsigned char> SuccsHandled;
4425 if (TI->getNumSuccessors())
4426 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4428 // Check successor nodes PHI nodes that expect a constant to be available from
4430 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4431 BasicBlock *SuccBB = TI->getSuccessor(succ);
4432 if (!isa<PHINode>(SuccBB->begin())) continue;
4433 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4435 // If this terminator has multiple identical successors (common for
4436 // switches), only handle each succ once.
4437 unsigned SuccMBBNo = SuccMBB->getNumber();
4438 if (SuccsHandled[SuccMBBNo]) continue;
4439 SuccsHandled[SuccMBBNo] = true;
4441 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4444 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4445 // nodes and Machine PHI nodes, but the incoming operands have not been
4447 for (BasicBlock::iterator I = SuccBB->begin();
4448 (PN = dyn_cast<PHINode>(I)); ++I) {
4449 // Ignore dead phi's.
4450 if (PN->use_empty()) continue;
4453 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4455 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4456 unsigned &RegOut = ConstantsOut[C];
4458 RegOut = FuncInfo.CreateRegForValue(C);
4459 UnorderedChains.push_back(
4460 SDL.CopyValueToVirtualRegister(C, RegOut));
4464 Reg = FuncInfo.ValueMap[PHIOp];
4466 assert(isa<AllocaInst>(PHIOp) &&
4467 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4468 "Didn't codegen value into a register!??");
4469 Reg = FuncInfo.CreateRegForValue(PHIOp);
4470 UnorderedChains.push_back(
4471 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4475 // Remember that this register needs to added to the machine PHI node as
4476 // the input for this MBB.
4477 MVT::ValueType VT = TLI.getValueType(PN->getType());
4478 unsigned NumElements;
4479 if (VT != MVT::Vector)
4480 NumElements = TLI.getNumElements(VT);
4482 MVT::ValueType VT1,VT2;
4484 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
4487 for (unsigned i = 0, e = NumElements; i != e; ++i)
4488 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4491 ConstantsOut.clear();
4493 // Turn all of the unordered chains into one factored node.
4494 if (!UnorderedChains.empty()) {
4495 SDOperand Root = SDL.getRoot();
4496 if (Root.getOpcode() != ISD::EntryToken) {
4497 unsigned i = 0, e = UnorderedChains.size();
4498 for (; i != e; ++i) {
4499 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4500 if (UnorderedChains[i].Val->getOperand(0) == Root)
4501 break; // Don't add the root if we already indirectly depend on it.
4505 UnorderedChains.push_back(Root);
4507 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4508 &UnorderedChains[0], UnorderedChains.size()));
4511 // Lower the terminator after the copies are emitted.
4513 // Just the branch part of invoke.
4514 SDL.visitInvoke(*Invoke, true);
4516 SDL.visit(*LLVMBB->getTerminator());
4519 // Copy over any CaseBlock records that may now exist due to SwitchInst
4520 // lowering, as well as any jump table information.
4521 SwitchCases.clear();
4522 SwitchCases = SDL.SwitchCases;
4524 JTCases = SDL.JTCases;
4525 BitTestCases.clear();
4526 BitTestCases = SDL.BitTestCases;
4528 // Make sure the root of the DAG is up-to-date.
4529 DAG.setRoot(SDL.getRoot());
4532 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4533 // Get alias analysis for load/store combining.
4534 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4536 // Run the DAG combiner in pre-legalize mode.
4537 DAG.Combine(false, AA);
4539 DOUT << "Lowered selection DAG:\n";
4542 // Second step, hack on the DAG until it only uses operations and types that
4543 // the target supports.
4546 DOUT << "Legalized selection DAG:\n";
4549 // Run the DAG combiner in post-legalize mode.
4550 DAG.Combine(true, AA);
4552 if (ViewISelDAGs) DAG.viewGraph();
4554 // Third, instruction select all of the operations to machine code, adding the
4555 // code to the MachineBasicBlock.
4556 InstructionSelectBasicBlock(DAG);
4558 DOUT << "Selected machine code:\n";
4562 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4563 FunctionLoweringInfo &FuncInfo) {
4564 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4566 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4569 // First step, lower LLVM code to some DAG. This DAG may use operations and
4570 // types that are not supported by the target.
4571 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4573 // Second step, emit the lowered DAG as machine code.
4574 CodeGenAndEmitDAG(DAG);
4577 DOUT << "Total amount of phi nodes to update: "
4578 << PHINodesToUpdate.size() << "\n";
4579 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4580 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4581 << ", " << PHINodesToUpdate[i].second << ")\n";);
4583 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4584 // PHI nodes in successors.
4585 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4586 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4587 MachineInstr *PHI = PHINodesToUpdate[i].first;
4588 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4589 "This is not a machine PHI node that we are updating!");
4590 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4591 PHI->addMachineBasicBlockOperand(BB);
4596 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4597 // Lower header first, if it wasn't already lowered
4598 if (!BitTestCases[i].Emitted) {
4599 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4601 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4602 // Set the current basic block to the mbb we wish to insert the code into
4603 BB = BitTestCases[i].Parent;
4604 HSDL.setCurrentBasicBlock(BB);
4606 HSDL.visitBitTestHeader(BitTestCases[i]);
4607 HSDAG.setRoot(HSDL.getRoot());
4608 CodeGenAndEmitDAG(HSDAG);
4611 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4612 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4614 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4615 // Set the current basic block to the mbb we wish to insert the code into
4616 BB = BitTestCases[i].Cases[j].ThisBB;
4617 BSDL.setCurrentBasicBlock(BB);
4620 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4621 BitTestCases[i].Reg,
4622 BitTestCases[i].Cases[j]);
4624 BSDL.visitBitTestCase(BitTestCases[i].Default,
4625 BitTestCases[i].Reg,
4626 BitTestCases[i].Cases[j]);
4629 BSDAG.setRoot(BSDL.getRoot());
4630 CodeGenAndEmitDAG(BSDAG);
4634 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4635 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4636 MachineBasicBlock *PHIBB = PHI->getParent();
4637 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4638 "This is not a machine PHI node that we are updating!");
4639 // This is "default" BB. We have two jumps to it. From "header" BB and
4640 // from last "case" BB.
4641 if (PHIBB == BitTestCases[i].Default) {
4642 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4643 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
4644 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4645 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4647 // One of "cases" BB.
4648 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4649 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4650 if (cBB->succ_end() !=
4651 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4652 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4653 PHI->addMachineBasicBlockOperand(cBB);
4659 // If the JumpTable record is filled in, then we need to emit a jump table.
4660 // Updating the PHI nodes is tricky in this case, since we need to determine
4661 // whether the PHI is a successor of the range check MBB or the jump table MBB
4662 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4663 // Lower header first, if it wasn't already lowered
4664 if (!JTCases[i].first.Emitted) {
4665 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4667 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4668 // Set the current basic block to the mbb we wish to insert the code into
4669 BB = JTCases[i].first.HeaderBB;
4670 HSDL.setCurrentBasicBlock(BB);
4672 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4673 HSDAG.setRoot(HSDL.getRoot());
4674 CodeGenAndEmitDAG(HSDAG);
4677 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4679 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
4680 // Set the current basic block to the mbb we wish to insert the code into
4681 BB = JTCases[i].second.MBB;
4682 JSDL.setCurrentBasicBlock(BB);
4684 JSDL.visitJumpTable(JTCases[i].second);
4685 JSDAG.setRoot(JSDL.getRoot());
4686 CodeGenAndEmitDAG(JSDAG);
4689 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4690 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4691 MachineBasicBlock *PHIBB = PHI->getParent();
4692 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4693 "This is not a machine PHI node that we are updating!");
4694 // "default" BB. We can go there only from header BB.
4695 if (PHIBB == JTCases[i].second.Default) {
4696 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4697 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
4699 // JT BB. Just iterate over successors here
4700 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4701 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4702 PHI->addMachineBasicBlockOperand(BB);
4707 // If the switch block involved a branch to one of the actual successors, we
4708 // need to update PHI nodes in that block.
4709 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4710 MachineInstr *PHI = PHINodesToUpdate[i].first;
4711 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4712 "This is not a machine PHI node that we are updating!");
4713 if (BB->isSuccessor(PHI->getParent())) {
4714 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4715 PHI->addMachineBasicBlockOperand(BB);
4719 // If we generated any switch lowering information, build and codegen any
4720 // additional DAGs necessary.
4721 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4722 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4724 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4726 // Set the current basic block to the mbb we wish to insert the code into
4727 BB = SwitchCases[i].ThisBB;
4728 SDL.setCurrentBasicBlock(BB);
4731 SDL.visitSwitchCase(SwitchCases[i]);
4732 SDAG.setRoot(SDL.getRoot());
4733 CodeGenAndEmitDAG(SDAG);
4735 // Handle any PHI nodes in successors of this chunk, as if we were coming
4736 // from the original BB before switch expansion. Note that PHI nodes can
4737 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4738 // handle them the right number of times.
4739 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4740 for (MachineBasicBlock::iterator Phi = BB->begin();
4741 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4742 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4743 for (unsigned pn = 0; ; ++pn) {
4744 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4745 if (PHINodesToUpdate[pn].first == Phi) {
4746 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4747 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4753 // Don't process RHS if same block as LHS.
4754 if (BB == SwitchCases[i].FalseBB)
4755 SwitchCases[i].FalseBB = 0;
4757 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4758 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4759 SwitchCases[i].FalseBB = 0;
4761 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4766 //===----------------------------------------------------------------------===//
4767 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4768 /// target node in the graph.
4769 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4770 if (ViewSchedDAGs) DAG.viewGraph();
4772 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4776 RegisterScheduler::setDefault(Ctor);
4779 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4785 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4786 return new HazardRecognizer();
4789 //===----------------------------------------------------------------------===//
4790 // Helper functions used by the generated instruction selector.
4791 //===----------------------------------------------------------------------===//
4792 // Calls to these methods are generated by tblgen.
4794 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4795 /// the dag combiner simplified the 255, we still want to match. RHS is the
4796 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4797 /// specified in the .td file (e.g. 255).
4798 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4799 int64_t DesiredMaskS) {
4800 uint64_t ActualMask = RHS->getValue();
4801 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4803 // If the actual mask exactly matches, success!
4804 if (ActualMask == DesiredMask)
4807 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4808 if (ActualMask & ~DesiredMask)
4811 // Otherwise, the DAG Combiner may have proven that the value coming in is
4812 // either already zero or is not demanded. Check for known zero input bits.
4813 uint64_t NeededMask = DesiredMask & ~ActualMask;
4814 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4817 // TODO: check to see if missing bits are just not demanded.
4819 // Otherwise, this pattern doesn't match.
4823 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4824 /// the dag combiner simplified the 255, we still want to match. RHS is the
4825 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4826 /// specified in the .td file (e.g. 255).
4827 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4828 int64_t DesiredMaskS) {
4829 uint64_t ActualMask = RHS->getValue();
4830 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4832 // If the actual mask exactly matches, success!
4833 if (ActualMask == DesiredMask)
4836 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4837 if (ActualMask & ~DesiredMask)
4840 // Otherwise, the DAG Combiner may have proven that the value coming in is
4841 // either already zero or is not demanded. Check for known zero input bits.
4842 uint64_t NeededMask = DesiredMask & ~ActualMask;
4844 uint64_t KnownZero, KnownOne;
4845 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4847 // If all the missing bits in the or are already known to be set, match!
4848 if ((NeededMask & KnownOne) == NeededMask)
4851 // TODO: check to see if missing bits are just not demanded.
4853 // Otherwise, this pattern doesn't match.
4858 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4859 /// by tblgen. Others should not call it.
4860 void SelectionDAGISel::
4861 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4862 std::vector<SDOperand> InOps;
4863 std::swap(InOps, Ops);
4865 Ops.push_back(InOps[0]); // input chain.
4866 Ops.push_back(InOps[1]); // input asm string.
4868 unsigned i = 2, e = InOps.size();
4869 if (InOps[e-1].getValueType() == MVT::Flag)
4870 --e; // Don't process a flag operand if it is here.
4873 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4874 if ((Flags & 7) != 4 /*MEM*/) {
4875 // Just skip over this operand, copying the operands verbatim.
4876 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4877 i += (Flags >> 3) + 1;
4879 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4880 // Otherwise, this is a memory operand. Ask the target to select it.
4881 std::vector<SDOperand> SelOps;
4882 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4883 cerr << "Could not match memory address. Inline asm failure!\n";
4887 // Add this to the output node.
4888 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4889 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4891 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4896 // Add the flag input back if present.
4897 if (e != InOps.size())
4898 Ops.push_back(InOps.back());