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);
85 namespace { struct AsmOperandInfo; }
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
92 struct VISIBILITY_HIDDEN RegsForValue {
93 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
96 std::vector<unsigned> Regs;
98 /// RegVT - The value type of each register.
100 MVT::ValueType RegVT;
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
112 RegsForValue(const std::vector<unsigned> ®s,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
121 SDOperand &Chain, SDOperand &Flag) const;
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131 /// operand list. This adds the code marker and includes the number of
132 /// values added into it.
133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
134 std::vector<SDOperand> &Ops) const;
139 //===--------------------------------------------------------------------===//
140 /// createDefaultScheduler - This creates an instruction scheduler appropriate
142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
144 MachineBasicBlock *BB) {
145 TargetLowering &TLI = IS->getTargetLowering();
147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148 return createTDListDAGScheduler(IS, DAG, BB);
150 assert(TLI.getSchedulingPreference() ==
151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152 return createBURRListDAGScheduler(IS, DAG, BB);
157 //===--------------------------------------------------------------------===//
158 /// FunctionLoweringInfo - This contains information that is global to a
159 /// function that is used when lowering a region of the function.
160 class FunctionLoweringInfo {
167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
172 /// ValueMap - Since we emit code for the function a basic block at a time,
173 /// we must remember which virtual registers hold the values for
174 /// cross-basic-block values.
175 DenseMap<const Value*, unsigned> ValueMap;
177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178 /// the entry block. This allows the allocas to be efficiently referenced
179 /// anywhere in the function.
180 std::map<const AllocaInst*, int> StaticAllocaMap;
183 SmallSet<Instruction*, 8> CatchInfoLost;
184 SmallSet<Instruction*, 8> CatchInfoFound;
187 unsigned MakeReg(MVT::ValueType VT) {
188 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
191 /// isExportedInst - Return true if the specified value is an instruction
192 /// exported from its block.
193 bool isExportedInst(const Value *V) {
194 return ValueMap.count(V);
197 unsigned CreateRegForValue(const Value *V);
199 unsigned InitializeRegForValue(const Value *V) {
200 unsigned &R = ValueMap[V];
201 assert(R == 0 && "Already initialized this value register!");
202 return R = CreateRegForValue(V);
207 /// isFilterOrSelector - Return true if this instruction is a call to the
208 /// eh.filter or the eh.selector intrinsic.
209 static bool isFilterOrSelector(Instruction *I) {
210 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
211 return II->getIntrinsicID() == Intrinsic::eh_selector
212 || II->getIntrinsicID() == Intrinsic::eh_filter;
216 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
217 /// PHI nodes or outside of the basic block that defines it, or used by a
218 /// switch instruction, which may expand to multiple basic blocks.
219 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
220 if (isa<PHINode>(I)) return true;
221 BasicBlock *BB = I->getParent();
222 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
223 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
224 // FIXME: Remove switchinst special case.
225 isa<SwitchInst>(*UI))
230 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
231 /// entry block, return true. This includes arguments used by switches, since
232 /// the switch may expand into multiple basic blocks.
233 static bool isOnlyUsedInEntryBlock(Argument *A) {
234 BasicBlock *Entry = A->getParent()->begin();
235 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
236 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
237 return false; // Use not in entry block.
241 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
242 Function &fn, MachineFunction &mf)
243 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
245 // Create a vreg for each argument register that is not dead and is used
246 // outside of the entry block for the function.
247 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
249 if (!isOnlyUsedInEntryBlock(AI))
250 InitializeRegForValue(AI);
252 // Initialize the mapping of values to registers. This is only set up for
253 // instruction values that are used outside of the block that defines
255 Function::iterator BB = Fn.begin(), EB = Fn.end();
256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
257 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
258 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
259 const Type *Ty = AI->getAllocatedType();
260 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
262 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
265 TySize *= CUI->getZExtValue(); // Get total allocated size.
266 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
267 StaticAllocaMap[AI] =
268 MF.getFrameInfo()->CreateStackObject(TySize, Align);
271 for (; BB != EB; ++BB)
272 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
273 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
274 if (!isa<AllocaInst>(I) ||
275 !StaticAllocaMap.count(cast<AllocaInst>(I)))
276 InitializeRegForValue(I);
278 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
279 // also creates the initial PHI MachineInstrs, though none of the input
280 // operands are populated.
281 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
282 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
284 MF.getBasicBlockList().push_back(MBB);
286 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
289 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
290 if (PN->use_empty()) continue;
292 MVT::ValueType VT = TLI.getValueType(PN->getType());
293 unsigned NumRegisters = TLI.getNumRegisters(VT);
294 unsigned PHIReg = ValueMap[PN];
295 assert(PHIReg && "PHI node does not have an assigned virtual register!");
296 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
297 for (unsigned i = 0; i != NumRegisters; ++i)
298 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
303 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
304 /// the correctly promoted or expanded types. Assign these registers
305 /// consecutive vreg numbers and return the first assigned number.
306 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
307 MVT::ValueType VT = TLI.getValueType(V->getType());
309 unsigned NumRegisters;
310 MVT::ValueType RegisterVT;
311 if (MVT::isVector(VT)) {
312 MVT::ValueType ElementVT;
313 NumRegisters = TLI.getVectorTypeBreakdown(VT, ElementVT, RegisterVT);
315 RegisterVT = TLI.getTypeToTransformTo(VT);
316 NumRegisters = TLI.getNumRegisters(VT);
319 unsigned R = MakeReg(RegisterVT);
320 for (unsigned i = 1; i != NumRegisters; ++i)
326 //===----------------------------------------------------------------------===//
327 /// SelectionDAGLowering - This is the common target-independent lowering
328 /// implementation that is parameterized by a TargetLowering object.
329 /// Also, targets can overload any lowering method.
332 class SelectionDAGLowering {
333 MachineBasicBlock *CurMBB;
335 DenseMap<const Value*, SDOperand> NodeMap;
337 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
338 /// them up and then emit token factor nodes when possible. This allows us to
339 /// get simple disambiguation between loads without worrying about alias
341 std::vector<SDOperand> PendingLoads;
343 /// Case - A struct to record the Value for a switch case, and the
344 /// case's target basic block.
348 MachineBasicBlock* BB;
350 Case() : Low(0), High(0), BB(0) { }
351 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
352 Low(low), High(high), BB(bb) { }
353 uint64_t size() const {
354 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
355 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
356 return (rHigh - rLow + 1ULL);
362 MachineBasicBlock* BB;
365 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
366 Mask(mask), BB(bb), Bits(bits) { }
369 typedef std::vector<Case> CaseVector;
370 typedef std::vector<CaseBits> CaseBitsVector;
371 typedef CaseVector::iterator CaseItr;
372 typedef std::pair<CaseItr, CaseItr> CaseRange;
374 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
375 /// of conditional branches.
377 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
378 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
380 /// CaseBB - The MBB in which to emit the compare and branch
381 MachineBasicBlock *CaseBB;
382 /// LT, GE - If nonzero, we know the current case value must be less-than or
383 /// greater-than-or-equal-to these Constants.
386 /// Range - A pair of iterators representing the range of case values to be
387 /// processed at this point in the binary search tree.
391 typedef std::vector<CaseRec> CaseRecVector;
393 /// The comparison function for sorting the switch case values in the vector.
394 /// WARNING: Case ranges should be disjoint!
396 bool operator () (const Case& C1, const Case& C2) {
397 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
398 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
399 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
400 return CI1->getValue().slt(CI2->getValue());
405 bool operator () (const CaseBits& C1, const CaseBits& C2) {
406 return C1.Bits > C2.Bits;
410 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
413 // TLI - This is information that describes the available target features we
414 // need for lowering. This indicates when operations are unavailable,
415 // implemented with a libcall, etc.
418 const TargetData *TD;
420 /// SwitchCases - Vector of CaseBlock structures used to communicate
421 /// SwitchInst code generation information.
422 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
423 /// JTCases - Vector of JumpTable structures used to communicate
424 /// SwitchInst code generation information.
425 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
426 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
428 /// FuncInfo - Information about the function as a whole.
430 FunctionLoweringInfo &FuncInfo;
432 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
433 FunctionLoweringInfo &funcinfo)
434 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
438 /// getRoot - Return the current virtual root of the Selection DAG.
440 SDOperand getRoot() {
441 if (PendingLoads.empty())
442 return DAG.getRoot();
444 if (PendingLoads.size() == 1) {
445 SDOperand Root = PendingLoads[0];
447 PendingLoads.clear();
451 // Otherwise, we have to make a token factor node.
452 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
453 &PendingLoads[0], PendingLoads.size());
454 PendingLoads.clear();
459 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
461 void visit(Instruction &I) { visit(I.getOpcode(), I); }
463 void visit(unsigned Opcode, User &I) {
464 // Note: this doesn't use InstVisitor, because it has to work with
465 // ConstantExpr's in addition to instructions.
467 default: assert(0 && "Unknown instruction type encountered!");
469 // Build the switch statement using the Instruction.def file.
470 #define HANDLE_INST(NUM, OPCODE, CLASS) \
471 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
472 #include "llvm/Instruction.def"
476 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
478 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
479 const Value *SV, SDOperand Root,
480 bool isVolatile, unsigned Alignment);
482 SDOperand getIntPtrConstant(uint64_t Val) {
483 return DAG.getConstant(Val, TLI.getPointerTy());
486 SDOperand getValue(const Value *V);
488 void setValue(const Value *V, SDOperand NewN) {
489 SDOperand &N = NodeMap[V];
490 assert(N.Val == 0 && "Already set a value for this node!");
494 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
495 std::set<unsigned> &OutputRegs,
496 std::set<unsigned> &InputRegs);
498 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
499 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
501 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
502 void ExportFromCurrentBlock(Value *V);
503 void LowerCallTo(Instruction &I,
504 const Type *CalledValueTy, unsigned CallingConv,
505 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
506 MachineBasicBlock *LandingPad = NULL);
508 // Terminator instructions.
509 void visitRet(ReturnInst &I);
510 void visitBr(BranchInst &I);
511 void visitSwitch(SwitchInst &I);
512 void visitUnreachable(UnreachableInst &I) { /* noop */ }
514 // Helpers for visitSwitch
515 bool handleSmallSwitchRange(CaseRec& CR,
516 CaseRecVector& WorkList,
518 MachineBasicBlock* Default);
519 bool handleJTSwitchCase(CaseRec& CR,
520 CaseRecVector& WorkList,
522 MachineBasicBlock* Default);
523 bool handleBTSplitSwitchCase(CaseRec& CR,
524 CaseRecVector& WorkList,
526 MachineBasicBlock* Default);
527 bool handleBitTestsSwitchCase(CaseRec& CR,
528 CaseRecVector& WorkList,
530 MachineBasicBlock* Default);
531 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
532 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
533 void visitBitTestCase(MachineBasicBlock* NextMBB,
535 SelectionDAGISel::BitTestCase &B);
536 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
537 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
538 SelectionDAGISel::JumpTableHeader &JTH);
540 // These all get lowered before this pass.
541 void visitInvoke(InvokeInst &I);
542 void visitUnwind(UnwindInst &I);
544 void visitBinary(User &I, unsigned OpCode);
545 void visitShift(User &I, unsigned Opcode);
546 void visitAdd(User &I) {
547 if (I.getType()->isFPOrFPVector())
548 visitBinary(I, ISD::FADD);
550 visitBinary(I, ISD::ADD);
552 void visitSub(User &I);
553 void visitMul(User &I) {
554 if (I.getType()->isFPOrFPVector())
555 visitBinary(I, ISD::FMUL);
557 visitBinary(I, ISD::MUL);
559 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
560 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
561 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
562 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
563 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
564 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
565 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
566 void visitOr (User &I) { visitBinary(I, ISD::OR); }
567 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
568 void visitShl (User &I) { visitShift(I, ISD::SHL); }
569 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
570 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
571 void visitICmp(User &I);
572 void visitFCmp(User &I);
573 // Visit the conversion instructions
574 void visitTrunc(User &I);
575 void visitZExt(User &I);
576 void visitSExt(User &I);
577 void visitFPTrunc(User &I);
578 void visitFPExt(User &I);
579 void visitFPToUI(User &I);
580 void visitFPToSI(User &I);
581 void visitUIToFP(User &I);
582 void visitSIToFP(User &I);
583 void visitPtrToInt(User &I);
584 void visitIntToPtr(User &I);
585 void visitBitCast(User &I);
587 void visitExtractElement(User &I);
588 void visitInsertElement(User &I);
589 void visitShuffleVector(User &I);
591 void visitGetElementPtr(User &I);
592 void visitSelect(User &I);
594 void visitMalloc(MallocInst &I);
595 void visitFree(FreeInst &I);
596 void visitAlloca(AllocaInst &I);
597 void visitLoad(LoadInst &I);
598 void visitStore(StoreInst &I);
599 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
600 void visitCall(CallInst &I);
601 void visitInlineAsm(CallInst &I);
602 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
603 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
605 void visitVAStart(CallInst &I);
606 void visitVAArg(VAArgInst &I);
607 void visitVAEnd(CallInst &I);
608 void visitVACopy(CallInst &I);
610 void visitMemIntrinsic(CallInst &I, unsigned Op);
612 void visitUserOp1(Instruction &I) {
613 assert(0 && "UserOp1 should not exist at instruction selection time!");
616 void visitUserOp2(Instruction &I) {
617 assert(0 && "UserOp2 should not exist at instruction selection time!");
621 } // end namespace llvm
623 SDOperand SelectionDAGLowering::getValue(const Value *V) {
624 SDOperand &N = NodeMap[V];
627 const Type *VTy = V->getType();
628 MVT::ValueType VT = TLI.getValueType(VTy);
629 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
630 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
631 visit(CE->getOpcode(), *CE);
632 SDOperand N1 = NodeMap[V];
633 assert(N1.Val && "visit didn't populate the ValueMap!");
635 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
636 return N = DAG.getGlobalAddress(GV, VT);
637 } else if (isa<ConstantPointerNull>(C)) {
638 return N = DAG.getConstant(0, TLI.getPointerTy());
639 } else if (isa<UndefValue>(C)) {
640 if (!isa<VectorType>(VTy))
641 return N = DAG.getNode(ISD::UNDEF, VT);
643 // Create a BUILD_VECTOR of undef nodes.
644 const VectorType *PTy = cast<VectorType>(VTy);
645 unsigned NumElements = PTy->getNumElements();
646 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
648 SmallVector<SDOperand, 8> Ops;
649 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
651 // Create a VConstant node with generic Vector type.
652 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
653 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
654 &Ops[0], Ops.size());
655 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
656 return N = DAG.getConstantFP(CFP->getValue(), VT);
657 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
658 unsigned NumElements = PTy->getNumElements();
659 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
661 // Now that we know the number and type of the elements, push a
662 // Constant or ConstantFP node onto the ops list for each element of
663 // the packed constant.
664 SmallVector<SDOperand, 8> Ops;
665 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
666 for (unsigned i = 0; i != NumElements; ++i)
667 Ops.push_back(getValue(CP->getOperand(i)));
669 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
671 if (MVT::isFloatingPoint(PVT))
672 Op = DAG.getConstantFP(0, PVT);
674 Op = DAG.getConstant(0, PVT);
675 Ops.assign(NumElements, Op);
678 // Create a BUILD_VECTOR node.
679 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
680 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
683 // Canonicalize all constant ints to be unsigned.
684 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
688 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
689 std::map<const AllocaInst*, int>::iterator SI =
690 FuncInfo.StaticAllocaMap.find(AI);
691 if (SI != FuncInfo.StaticAllocaMap.end())
692 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
695 unsigned InReg = FuncInfo.ValueMap[V];
696 assert(InReg && "Value not in map!");
698 // If this type is not legal, make it so now.
699 if (!MVT::isVector(VT)) {
700 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
701 // Source must be expanded. This input value is actually coming from the
702 // register pair InReg and InReg+1.
703 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
704 unsigned NumVals = TLI.getNumRegisters(VT);
705 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
707 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
709 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
710 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
711 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
714 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
715 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
716 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
717 N = MVT::isFloatingPoint(VT)
718 ? DAG.getNode(ISD::FP_ROUND, VT, N)
719 : DAG.getNode(ISD::TRUNCATE, VT, N);
722 // Otherwise, if this is a vector, make it available as a vector
724 MVT::ValueType ElementVT, LegalElementVT;
725 unsigned NE = TLI.getVectorTypeBreakdown(VT, ElementVT,
728 // Build a BUILD_VECTOR or CONCAT_VECTORS with the input registers.
729 SmallVector<SDOperand, 8> Ops;
730 if (ElementVT == LegalElementVT) {
731 // If the value types are legal, just BUILD the CopyFromReg nodes.
732 for (unsigned i = 0; i != NE; ++i)
733 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
735 } else if (ElementVT < LegalElementVT) {
736 // If the register was promoted, use TRUNCATE or FP_ROUND as appropriate.
737 for (unsigned i = 0; i != NE; ++i) {
738 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
740 if (MVT::isFloatingPoint(ElementVT))
741 Op = DAG.getNode(ISD::FP_ROUND, ElementVT, Op);
743 Op = DAG.getNode(ISD::TRUNCATE, ElementVT, Op);
747 // If the register was expanded, use BUILD_PAIR.
748 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
749 for (unsigned i = 0; i != NE; ++i) {
750 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
752 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
754 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, ElementVT, Op0, Op1));
758 if (MVT::isVector(ElementVT)) {
759 N = DAG.getNode(ISD::CONCAT_VECTORS,
760 MVT::getVectorType(MVT::getVectorElementType(ElementVT),
761 NE * MVT::getVectorNumElements(ElementVT)),
762 &Ops[0], Ops.size());
764 N = DAG.getNode(ISD::BUILD_VECTOR,
765 MVT::getVectorType(ElementVT, NE),
766 &Ops[0], Ops.size());
774 void SelectionDAGLowering::visitRet(ReturnInst &I) {
775 if (I.getNumOperands() == 0) {
776 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
779 SmallVector<SDOperand, 8> NewValues;
780 NewValues.push_back(getRoot());
781 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
782 SDOperand RetOp = getValue(I.getOperand(i));
784 // If this is an integer return value, we need to promote it ourselves to
785 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
787 // FIXME: C calling convention requires the return type to be promoted to
788 // at least 32-bit. But this is not necessary for non-C calling conventions.
789 if (MVT::isInteger(RetOp.getValueType()) &&
790 RetOp.getValueType() < MVT::i64) {
791 MVT::ValueType TmpVT;
792 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
793 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
796 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
797 const ParamAttrsList *Attrs = FTy->getParamAttrs();
798 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
799 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
800 ExtendKind = ISD::SIGN_EXTEND;
801 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
802 ExtendKind = ISD::ZERO_EXTEND;
803 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
805 NewValues.push_back(RetOp);
806 NewValues.push_back(DAG.getConstant(false, MVT::i32));
808 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
809 &NewValues[0], NewValues.size()));
812 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
813 /// the current basic block, add it to ValueMap now so that we'll get a
815 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
816 // No need to export constants.
817 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
820 if (FuncInfo.isExportedInst(V)) return;
822 unsigned Reg = FuncInfo.InitializeRegForValue(V);
823 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
826 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
827 const BasicBlock *FromBB) {
828 // The operands of the setcc have to be in this block. We don't know
829 // how to export them from some other block.
830 if (Instruction *VI = dyn_cast<Instruction>(V)) {
831 // Can export from current BB.
832 if (VI->getParent() == FromBB)
835 // Is already exported, noop.
836 return FuncInfo.isExportedInst(V);
839 // If this is an argument, we can export it if the BB is the entry block or
840 // if it is already exported.
841 if (isa<Argument>(V)) {
842 if (FromBB == &FromBB->getParent()->getEntryBlock())
845 // Otherwise, can only export this if it is already exported.
846 return FuncInfo.isExportedInst(V);
849 // Otherwise, constants can always be exported.
853 static bool InBlock(const Value *V, const BasicBlock *BB) {
854 if (const Instruction *I = dyn_cast<Instruction>(V))
855 return I->getParent() == BB;
859 /// FindMergedConditions - If Cond is an expression like
860 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
861 MachineBasicBlock *TBB,
862 MachineBasicBlock *FBB,
863 MachineBasicBlock *CurBB,
865 // If this node is not part of the or/and tree, emit it as a branch.
866 Instruction *BOp = dyn_cast<Instruction>(Cond);
868 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
869 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
870 BOp->getParent() != CurBB->getBasicBlock() ||
871 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
872 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
873 const BasicBlock *BB = CurBB->getBasicBlock();
875 // If the leaf of the tree is a comparison, merge the condition into
877 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
878 // The operands of the cmp have to be in this block. We don't know
879 // how to export them from some other block. If this is the first block
880 // of the sequence, no exporting is needed.
882 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
883 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
884 BOp = cast<Instruction>(Cond);
885 ISD::CondCode Condition;
886 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
887 switch (IC->getPredicate()) {
888 default: assert(0 && "Unknown icmp predicate opcode!");
889 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
890 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
891 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
892 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
893 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
894 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
895 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
896 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
897 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
898 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
900 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
901 ISD::CondCode FPC, FOC;
902 switch (FC->getPredicate()) {
903 default: assert(0 && "Unknown fcmp predicate opcode!");
904 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
905 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
906 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
907 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
908 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
909 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
910 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
911 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
912 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
913 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
914 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
915 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
916 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
917 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
918 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
919 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
921 if (FiniteOnlyFPMath())
926 Condition = ISD::SETEQ; // silence warning.
927 assert(0 && "Unknown compare instruction");
930 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
931 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
932 SwitchCases.push_back(CB);
936 // Create a CaseBlock record representing this branch.
937 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
938 NULL, TBB, FBB, CurBB);
939 SwitchCases.push_back(CB);
944 // Create TmpBB after CurBB.
945 MachineFunction::iterator BBI = CurBB;
946 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
947 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
949 if (Opc == Instruction::Or) {
958 // Emit the LHS condition.
959 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
961 // Emit the RHS condition into TmpBB.
962 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
964 assert(Opc == Instruction::And && "Unknown merge op!");
972 // This requires creation of TmpBB after CurBB.
974 // Emit the LHS condition.
975 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
977 // Emit the RHS condition into TmpBB.
978 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
982 /// If the set of cases should be emitted as a series of branches, return true.
983 /// If we should emit this as a bunch of and/or'd together conditions, return
986 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
987 if (Cases.size() != 2) return true;
989 // If this is two comparisons of the same values or'd or and'd together, they
990 // will get folded into a single comparison, so don't emit two blocks.
991 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
992 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
993 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
994 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1001 void SelectionDAGLowering::visitBr(BranchInst &I) {
1002 // Update machine-CFG edges.
1003 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1005 // Figure out which block is immediately after the current one.
1006 MachineBasicBlock *NextBlock = 0;
1007 MachineFunction::iterator BBI = CurMBB;
1008 if (++BBI != CurMBB->getParent()->end())
1011 if (I.isUnconditional()) {
1012 // If this is not a fall-through branch, emit the branch.
1013 if (Succ0MBB != NextBlock)
1014 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1015 DAG.getBasicBlock(Succ0MBB)));
1017 // Update machine-CFG edges.
1018 CurMBB->addSuccessor(Succ0MBB);
1023 // If this condition is one of the special cases we handle, do special stuff
1025 Value *CondVal = I.getCondition();
1026 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1028 // If this is a series of conditions that are or'd or and'd together, emit
1029 // this as a sequence of branches instead of setcc's with and/or operations.
1030 // For example, instead of something like:
1043 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1044 if (BOp->hasOneUse() &&
1045 (BOp->getOpcode() == Instruction::And ||
1046 BOp->getOpcode() == Instruction::Or)) {
1047 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1048 // If the compares in later blocks need to use values not currently
1049 // exported from this block, export them now. This block should always
1050 // be the first entry.
1051 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1053 // Allow some cases to be rejected.
1054 if (ShouldEmitAsBranches(SwitchCases)) {
1055 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1056 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1057 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1060 // Emit the branch for this block.
1061 visitSwitchCase(SwitchCases[0]);
1062 SwitchCases.erase(SwitchCases.begin());
1066 // Okay, we decided not to do this, remove any inserted MBB's and clear
1068 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1069 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1071 SwitchCases.clear();
1075 // Create a CaseBlock record representing this branch.
1076 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1077 NULL, Succ0MBB, Succ1MBB, CurMBB);
1078 // Use visitSwitchCase to actually insert the fast branch sequence for this
1080 visitSwitchCase(CB);
1083 /// visitSwitchCase - Emits the necessary code to represent a single node in
1084 /// the binary search tree resulting from lowering a switch instruction.
1085 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1087 SDOperand CondLHS = getValue(CB.CmpLHS);
1089 // Build the setcc now.
1090 if (CB.CmpMHS == NULL) {
1091 // Fold "(X == true)" to X and "(X == false)" to !X to
1092 // handle common cases produced by branch lowering.
1093 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1095 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1096 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1097 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1099 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1101 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1103 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1104 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1106 SDOperand CmpOp = getValue(CB.CmpMHS);
1107 MVT::ValueType VT = CmpOp.getValueType();
1109 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1110 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1112 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1113 Cond = DAG.getSetCC(MVT::i1, SUB,
1114 DAG.getConstant(High-Low, VT), ISD::SETULE);
1119 // Set NextBlock to be the MBB immediately after the current one, if any.
1120 // This is used to avoid emitting unnecessary branches to the next block.
1121 MachineBasicBlock *NextBlock = 0;
1122 MachineFunction::iterator BBI = CurMBB;
1123 if (++BBI != CurMBB->getParent()->end())
1126 // If the lhs block is the next block, invert the condition so that we can
1127 // fall through to the lhs instead of the rhs block.
1128 if (CB.TrueBB == NextBlock) {
1129 std::swap(CB.TrueBB, CB.FalseBB);
1130 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1131 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1133 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1134 DAG.getBasicBlock(CB.TrueBB));
1135 if (CB.FalseBB == NextBlock)
1136 DAG.setRoot(BrCond);
1138 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1139 DAG.getBasicBlock(CB.FalseBB)));
1140 // Update successor info
1141 CurMBB->addSuccessor(CB.TrueBB);
1142 CurMBB->addSuccessor(CB.FalseBB);
1145 /// visitJumpTable - Emit JumpTable node in the current MBB
1146 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1147 // Emit the code for the jump table
1148 assert(JT.Reg != -1U && "Should lower JT Header first!");
1149 MVT::ValueType PTy = TLI.getPointerTy();
1150 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1151 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1152 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1157 /// visitJumpTableHeader - This function emits necessary code to produce index
1158 /// in the JumpTable from switch case.
1159 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1160 SelectionDAGISel::JumpTableHeader &JTH) {
1161 // Subtract the lowest switch case value from the value being switched on
1162 // and conditional branch to default mbb if the result is greater than the
1163 // difference between smallest and largest cases.
1164 SDOperand SwitchOp = getValue(JTH.SValue);
1165 MVT::ValueType VT = SwitchOp.getValueType();
1166 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1167 DAG.getConstant(JTH.First, VT));
1169 // The SDNode we just created, which holds the value being switched on
1170 // minus the the smallest case value, needs to be copied to a virtual
1171 // register so it can be used as an index into the jump table in a
1172 // subsequent basic block. This value may be smaller or larger than the
1173 // target's pointer type, and therefore require extension or truncating.
1174 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
1175 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1177 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1179 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1180 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1181 JT.Reg = JumpTableReg;
1183 // Emit the range check for the jump table, and branch to the default
1184 // block for the switch statement if the value being switched on exceeds
1185 // the largest case in the switch.
1186 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1187 DAG.getConstant(JTH.Last-JTH.First,VT),
1190 // Set NextBlock to be the MBB immediately after the current one, if any.
1191 // This is used to avoid emitting unnecessary branches to the next block.
1192 MachineBasicBlock *NextBlock = 0;
1193 MachineFunction::iterator BBI = CurMBB;
1194 if (++BBI != CurMBB->getParent()->end())
1197 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1198 DAG.getBasicBlock(JT.Default));
1200 if (JT.MBB == NextBlock)
1201 DAG.setRoot(BrCond);
1203 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1204 DAG.getBasicBlock(JT.MBB)));
1209 /// visitBitTestHeader - This function emits necessary code to produce value
1210 /// suitable for "bit tests"
1211 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1212 // Subtract the minimum value
1213 SDOperand SwitchOp = getValue(B.SValue);
1214 MVT::ValueType VT = SwitchOp.getValueType();
1215 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1216 DAG.getConstant(B.First, VT));
1219 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1220 DAG.getConstant(B.Range, VT),
1224 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
1225 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1227 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1229 // Make desired shift
1230 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1231 DAG.getConstant(1, TLI.getPointerTy()),
1234 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1235 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1238 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1239 DAG.getBasicBlock(B.Default));
1241 // Set NextBlock to be the MBB immediately after the current one, if any.
1242 // This is used to avoid emitting unnecessary branches to the next block.
1243 MachineBasicBlock *NextBlock = 0;
1244 MachineFunction::iterator BBI = CurMBB;
1245 if (++BBI != CurMBB->getParent()->end())
1248 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1249 if (MBB == NextBlock)
1250 DAG.setRoot(BrRange);
1252 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1253 DAG.getBasicBlock(MBB)));
1255 CurMBB->addSuccessor(B.Default);
1256 CurMBB->addSuccessor(MBB);
1261 /// visitBitTestCase - this function produces one "bit test"
1262 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1264 SelectionDAGISel::BitTestCase &B) {
1265 // Emit bit tests and jumps
1266 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1268 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1270 DAG.getConstant(B.Mask,
1271 TLI.getPointerTy()));
1272 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1273 DAG.getConstant(0, TLI.getPointerTy()),
1275 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1276 AndCmp, DAG.getBasicBlock(B.TargetBB));
1278 // Set NextBlock to be the MBB immediately after the current one, if any.
1279 // This is used to avoid emitting unnecessary branches to the next block.
1280 MachineBasicBlock *NextBlock = 0;
1281 MachineFunction::iterator BBI = CurMBB;
1282 if (++BBI != CurMBB->getParent()->end())
1285 if (NextMBB == NextBlock)
1288 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1289 DAG.getBasicBlock(NextMBB)));
1291 CurMBB->addSuccessor(B.TargetBB);
1292 CurMBB->addSuccessor(NextMBB);
1297 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1298 // Retrieve successors.
1299 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1300 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1302 LowerCallTo(I, I.getCalledValue()->getType(),
1305 getValue(I.getOperand(0)),
1308 // If the value of the invoke is used outside of its defining block, make it
1309 // available as a virtual register.
1310 if (!I.use_empty()) {
1311 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1312 if (VMI != FuncInfo.ValueMap.end())
1313 DAG.setRoot(CopyValueToVirtualRegister(&I, VMI->second));
1316 // Drop into normal successor.
1317 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1318 DAG.getBasicBlock(Return)));
1320 // Update successor info
1321 CurMBB->addSuccessor(Return);
1322 CurMBB->addSuccessor(LandingPad);
1325 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1328 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1329 /// small case ranges).
1330 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1331 CaseRecVector& WorkList,
1333 MachineBasicBlock* Default) {
1334 Case& BackCase = *(CR.Range.second-1);
1336 // Size is the number of Cases represented by this range.
1337 unsigned Size = CR.Range.second - CR.Range.first;
1341 // Get the MachineFunction which holds the current MBB. This is used when
1342 // inserting any additional MBBs necessary to represent the switch.
1343 MachineFunction *CurMF = CurMBB->getParent();
1345 // Figure out which block is immediately after the current one.
1346 MachineBasicBlock *NextBlock = 0;
1347 MachineFunction::iterator BBI = CR.CaseBB;
1349 if (++BBI != CurMBB->getParent()->end())
1352 // TODO: If any two of the cases has the same destination, and if one value
1353 // is the same as the other, but has one bit unset that the other has set,
1354 // use bit manipulation to do two compares at once. For example:
1355 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1357 // Rearrange the case blocks so that the last one falls through if possible.
1358 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1359 // The last case block won't fall through into 'NextBlock' if we emit the
1360 // branches in this order. See if rearranging a case value would help.
1361 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1362 if (I->BB == NextBlock) {
1363 std::swap(*I, BackCase);
1369 // Create a CaseBlock record representing a conditional branch to
1370 // the Case's target mbb if the value being switched on SV is equal
1372 MachineBasicBlock *CurBlock = CR.CaseBB;
1373 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1374 MachineBasicBlock *FallThrough;
1376 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1377 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1379 // If the last case doesn't match, go to the default block.
1380 FallThrough = Default;
1383 Value *RHS, *LHS, *MHS;
1385 if (I->High == I->Low) {
1386 // This is just small small case range :) containing exactly 1 case
1388 LHS = SV; RHS = I->High; MHS = NULL;
1391 LHS = I->Low; MHS = SV; RHS = I->High;
1393 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1394 I->BB, FallThrough, CurBlock);
1396 // If emitting the first comparison, just call visitSwitchCase to emit the
1397 // code into the current block. Otherwise, push the CaseBlock onto the
1398 // vector to be later processed by SDISel, and insert the node's MBB
1399 // before the next MBB.
1400 if (CurBlock == CurMBB)
1401 visitSwitchCase(CB);
1403 SwitchCases.push_back(CB);
1405 CurBlock = FallThrough;
1411 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1412 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1413 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1416 /// handleJTSwitchCase - Emit jumptable for current switch case range
1417 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1418 CaseRecVector& WorkList,
1420 MachineBasicBlock* Default) {
1421 Case& FrontCase = *CR.Range.first;
1422 Case& BackCase = *(CR.Range.second-1);
1424 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1425 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1428 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1432 if (!areJTsAllowed(TLI) || TSize <= 3)
1435 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1439 DOUT << "Lowering jump table\n"
1440 << "First entry: " << First << ". Last entry: " << Last << "\n"
1441 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1443 // Get the MachineFunction which holds the current MBB. This is used when
1444 // inserting any additional MBBs necessary to represent the switch.
1445 MachineFunction *CurMF = CurMBB->getParent();
1447 // Figure out which block is immediately after the current one.
1448 MachineBasicBlock *NextBlock = 0;
1449 MachineFunction::iterator BBI = CR.CaseBB;
1451 if (++BBI != CurMBB->getParent()->end())
1454 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1456 // Create a new basic block to hold the code for loading the address
1457 // of the jump table, and jumping to it. Update successor information;
1458 // we will either branch to the default case for the switch, or the jump
1460 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1461 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1462 CR.CaseBB->addSuccessor(Default);
1463 CR.CaseBB->addSuccessor(JumpTableBB);
1465 // Build a vector of destination BBs, corresponding to each target
1466 // of the jump table. If the value of the jump table slot corresponds to
1467 // a case statement, push the case's BB onto the vector, otherwise, push
1469 std::vector<MachineBasicBlock*> DestBBs;
1470 int64_t TEI = First;
1471 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1472 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1473 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1475 if ((Low <= TEI) && (TEI <= High)) {
1476 DestBBs.push_back(I->BB);
1480 DestBBs.push_back(Default);
1484 // Update successor info. Add one edge to each unique successor.
1485 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1486 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1487 E = DestBBs.end(); I != E; ++I) {
1488 if (!SuccsHandled[(*I)->getNumber()]) {
1489 SuccsHandled[(*I)->getNumber()] = true;
1490 JumpTableBB->addSuccessor(*I);
1494 // Create a jump table index for this jump table, or return an existing
1496 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1498 // Set the jump table information so that we can codegen it as a second
1499 // MachineBasicBlock
1500 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1501 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1502 (CR.CaseBB == CurMBB));
1503 if (CR.CaseBB == CurMBB)
1504 visitJumpTableHeader(JT, JTH);
1506 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1511 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1513 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1514 CaseRecVector& WorkList,
1516 MachineBasicBlock* Default) {
1517 // Get the MachineFunction which holds the current MBB. This is used when
1518 // inserting any additional MBBs necessary to represent the switch.
1519 MachineFunction *CurMF = CurMBB->getParent();
1521 // Figure out which block is immediately after the current one.
1522 MachineBasicBlock *NextBlock = 0;
1523 MachineFunction::iterator BBI = CR.CaseBB;
1525 if (++BBI != CurMBB->getParent()->end())
1528 Case& FrontCase = *CR.Range.first;
1529 Case& BackCase = *(CR.Range.second-1);
1530 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1532 // Size is the number of Cases represented by this range.
1533 unsigned Size = CR.Range.second - CR.Range.first;
1535 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1536 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1538 CaseItr Pivot = CR.Range.first + Size/2;
1540 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1541 // (heuristically) allow us to emit JumpTable's later.
1543 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1547 uint64_t LSize = FrontCase.size();
1548 uint64_t RSize = TSize-LSize;
1549 DOUT << "Selecting best pivot: \n"
1550 << "First: " << First << ", Last: " << Last <<"\n"
1551 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1552 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1554 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1555 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1556 assert((RBegin-LEnd>=1) && "Invalid case distance");
1557 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1558 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1559 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1560 // Should always split in some non-trivial place
1562 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1563 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1564 << "Metric: " << Metric << "\n";
1565 if (FMetric < Metric) {
1568 DOUT << "Current metric set to: " << FMetric << "\n";
1574 if (areJTsAllowed(TLI)) {
1575 // If our case is dense we *really* should handle it earlier!
1576 assert((FMetric > 0) && "Should handle dense range earlier!");
1578 Pivot = CR.Range.first + Size/2;
1581 CaseRange LHSR(CR.Range.first, Pivot);
1582 CaseRange RHSR(Pivot, CR.Range.second);
1583 Constant *C = Pivot->Low;
1584 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1586 // We know that we branch to the LHS if the Value being switched on is
1587 // less than the Pivot value, C. We use this to optimize our binary
1588 // tree a bit, by recognizing that if SV is greater than or equal to the
1589 // LHS's Case Value, and that Case Value is exactly one less than the
1590 // Pivot's Value, then we can branch directly to the LHS's Target,
1591 // rather than creating a leaf node for it.
1592 if ((LHSR.second - LHSR.first) == 1 &&
1593 LHSR.first->High == CR.GE &&
1594 cast<ConstantInt>(C)->getSExtValue() ==
1595 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1596 TrueBB = LHSR.first->BB;
1598 TrueBB = new MachineBasicBlock(LLVMBB);
1599 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1600 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1603 // Similar to the optimization above, if the Value being switched on is
1604 // known to be less than the Constant CR.LT, and the current Case Value
1605 // is CR.LT - 1, then we can branch directly to the target block for
1606 // the current Case Value, rather than emitting a RHS leaf node for it.
1607 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1608 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1609 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1610 FalseBB = RHSR.first->BB;
1612 FalseBB = new MachineBasicBlock(LLVMBB);
1613 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1614 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1617 // Create a CaseBlock record representing a conditional branch to
1618 // the LHS node if the value being switched on SV is less than C.
1619 // Otherwise, branch to LHS.
1620 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1621 TrueBB, FalseBB, CR.CaseBB);
1623 if (CR.CaseBB == CurMBB)
1624 visitSwitchCase(CB);
1626 SwitchCases.push_back(CB);
1631 /// handleBitTestsSwitchCase - if current case range has few destination and
1632 /// range span less, than machine word bitwidth, encode case range into series
1633 /// of masks and emit bit tests with these masks.
1634 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1635 CaseRecVector& WorkList,
1637 MachineBasicBlock* Default){
1638 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
1640 Case& FrontCase = *CR.Range.first;
1641 Case& BackCase = *(CR.Range.second-1);
1643 // Get the MachineFunction which holds the current MBB. This is used when
1644 // inserting any additional MBBs necessary to represent the switch.
1645 MachineFunction *CurMF = CurMBB->getParent();
1647 unsigned numCmps = 0;
1648 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1650 // Single case counts one, case range - two.
1651 if (I->Low == I->High)
1657 // Count unique destinations
1658 SmallSet<MachineBasicBlock*, 4> Dests;
1659 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1660 Dests.insert(I->BB);
1661 if (Dests.size() > 3)
1662 // Don't bother the code below, if there are too much unique destinations
1665 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1666 << "Total number of comparisons: " << numCmps << "\n";
1668 // Compute span of values.
1669 Constant* minValue = FrontCase.Low;
1670 Constant* maxValue = BackCase.High;
1671 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1672 cast<ConstantInt>(minValue)->getSExtValue();
1673 DOUT << "Compare range: " << range << "\n"
1674 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1675 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1677 if (range>=IntPtrBits ||
1678 (!(Dests.size() == 1 && numCmps >= 3) &&
1679 !(Dests.size() == 2 && numCmps >= 5) &&
1680 !(Dests.size() >= 3 && numCmps >= 6)))
1683 DOUT << "Emitting bit tests\n";
1684 int64_t lowBound = 0;
1686 // Optimize the case where all the case values fit in a
1687 // word without having to subtract minValue. In this case,
1688 // we can optimize away the subtraction.
1689 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1690 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1691 range = cast<ConstantInt>(maxValue)->getSExtValue();
1693 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1696 CaseBitsVector CasesBits;
1697 unsigned i, count = 0;
1699 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1700 MachineBasicBlock* Dest = I->BB;
1701 for (i = 0; i < count; ++i)
1702 if (Dest == CasesBits[i].BB)
1706 assert((count < 3) && "Too much destinations to test!");
1707 CasesBits.push_back(CaseBits(0, Dest, 0));
1711 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1712 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1714 for (uint64_t j = lo; j <= hi; j++) {
1715 CasesBits[i].Mask |= 1ULL << j;
1716 CasesBits[i].Bits++;
1720 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1722 SelectionDAGISel::BitTestInfo BTC;
1724 // Figure out which block is immediately after the current one.
1725 MachineFunction::iterator BBI = CR.CaseBB;
1728 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1731 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1732 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1733 << ", BB: " << CasesBits[i].BB << "\n";
1735 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1736 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1737 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1742 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
1743 -1U, (CR.CaseBB == CurMBB),
1744 CR.CaseBB, Default, BTC);
1746 if (CR.CaseBB == CurMBB)
1747 visitBitTestHeader(BTB);
1749 BitTestCases.push_back(BTB);
1755 // Clusterify - Transform simple list of Cases into list of CaseRange's
1756 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1757 const SwitchInst& SI) {
1758 unsigned numCmps = 0;
1760 // Start with "simple" cases
1761 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1762 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1763 Cases.push_back(Case(SI.getSuccessorValue(i),
1764 SI.getSuccessorValue(i),
1767 sort(Cases.begin(), Cases.end(), CaseCmp());
1769 // Merge case into clusters
1770 if (Cases.size()>=2)
1771 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1772 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1773 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1774 MachineBasicBlock* nextBB = J->BB;
1775 MachineBasicBlock* currentBB = I->BB;
1777 // If the two neighboring cases go to the same destination, merge them
1778 // into a single case.
1779 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1787 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1788 if (I->Low != I->High)
1789 // A range counts double, since it requires two compares.
1796 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1797 // Figure out which block is immediately after the current one.
1798 MachineBasicBlock *NextBlock = 0;
1799 MachineFunction::iterator BBI = CurMBB;
1801 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1803 // If there is only the default destination, branch to it if it is not the
1804 // next basic block. Otherwise, just fall through.
1805 if (SI.getNumOperands() == 2) {
1806 // Update machine-CFG edges.
1808 // If this is not a fall-through branch, emit the branch.
1809 if (Default != NextBlock)
1810 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1811 DAG.getBasicBlock(Default)));
1813 CurMBB->addSuccessor(Default);
1817 // If there are any non-default case statements, create a vector of Cases
1818 // representing each one, and sort the vector so that we can efficiently
1819 // create a binary search tree from them.
1821 unsigned numCmps = Clusterify(Cases, SI);
1822 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1823 << ". Total compares: " << numCmps << "\n";
1825 // Get the Value to be switched on and default basic blocks, which will be
1826 // inserted into CaseBlock records, representing basic blocks in the binary
1828 Value *SV = SI.getOperand(0);
1830 // Push the initial CaseRec onto the worklist
1831 CaseRecVector WorkList;
1832 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1834 while (!WorkList.empty()) {
1835 // Grab a record representing a case range to process off the worklist
1836 CaseRec CR = WorkList.back();
1837 WorkList.pop_back();
1839 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1842 // If the range has few cases (two or less) emit a series of specific
1844 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1847 // If the switch has more than 5 blocks, and at least 40% dense, and the
1848 // target supports indirect branches, then emit a jump table rather than
1849 // lowering the switch to a binary tree of conditional branches.
1850 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1853 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1854 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1855 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
1860 void SelectionDAGLowering::visitSub(User &I) {
1861 // -0.0 - X --> fneg
1862 const Type *Ty = I.getType();
1863 if (isa<VectorType>(Ty)) {
1864 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
1865 const VectorType *DestTy = cast<VectorType>(I.getType());
1866 const Type *ElTy = DestTy->getElementType();
1867 unsigned VL = DestTy->getNumElements();
1868 std::vector<Constant*> NZ(VL, ConstantFP::get(ElTy, -0.0));
1869 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
1871 SDOperand Op2 = getValue(I.getOperand(1));
1872 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1877 if (Ty->isFloatingPoint()) {
1878 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1879 if (CFP->isExactlyValue(-0.0)) {
1880 SDOperand Op2 = getValue(I.getOperand(1));
1881 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1886 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
1889 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
1890 SDOperand Op1 = getValue(I.getOperand(0));
1891 SDOperand Op2 = getValue(I.getOperand(1));
1893 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
1896 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1897 SDOperand Op1 = getValue(I.getOperand(0));
1898 SDOperand Op2 = getValue(I.getOperand(1));
1900 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
1901 MVT::getSizeInBits(Op2.getValueType()))
1902 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1903 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1904 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1906 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1909 void SelectionDAGLowering::visitICmp(User &I) {
1910 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1911 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1912 predicate = IC->getPredicate();
1913 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1914 predicate = ICmpInst::Predicate(IC->getPredicate());
1915 SDOperand Op1 = getValue(I.getOperand(0));
1916 SDOperand Op2 = getValue(I.getOperand(1));
1917 ISD::CondCode Opcode;
1918 switch (predicate) {
1919 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1920 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1921 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1922 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1923 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1924 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1925 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1926 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1927 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1928 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1930 assert(!"Invalid ICmp predicate value");
1931 Opcode = ISD::SETEQ;
1934 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1937 void SelectionDAGLowering::visitFCmp(User &I) {
1938 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1939 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1940 predicate = FC->getPredicate();
1941 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1942 predicate = FCmpInst::Predicate(FC->getPredicate());
1943 SDOperand Op1 = getValue(I.getOperand(0));
1944 SDOperand Op2 = getValue(I.getOperand(1));
1945 ISD::CondCode Condition, FOC, FPC;
1946 switch (predicate) {
1947 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1948 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1949 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1950 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1951 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1952 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1953 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1954 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1955 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1956 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1957 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1958 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1959 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1960 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1961 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1962 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1964 assert(!"Invalid FCmp predicate value");
1965 FOC = FPC = ISD::SETFALSE;
1968 if (FiniteOnlyFPMath())
1972 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
1975 void SelectionDAGLowering::visitSelect(User &I) {
1976 SDOperand Cond = getValue(I.getOperand(0));
1977 SDOperand TrueVal = getValue(I.getOperand(1));
1978 SDOperand FalseVal = getValue(I.getOperand(2));
1979 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1980 TrueVal, FalseVal));
1984 void SelectionDAGLowering::visitTrunc(User &I) {
1985 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1986 SDOperand N = getValue(I.getOperand(0));
1987 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1988 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1991 void SelectionDAGLowering::visitZExt(User &I) {
1992 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1993 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1994 SDOperand N = getValue(I.getOperand(0));
1995 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1996 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1999 void SelectionDAGLowering::visitSExt(User &I) {
2000 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2001 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2002 SDOperand N = getValue(I.getOperand(0));
2003 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2004 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2007 void SelectionDAGLowering::visitFPTrunc(User &I) {
2008 // FPTrunc is never a no-op cast, no need to check
2009 SDOperand N = getValue(I.getOperand(0));
2010 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2011 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2014 void SelectionDAGLowering::visitFPExt(User &I){
2015 // FPTrunc is never a no-op cast, no need to check
2016 SDOperand N = getValue(I.getOperand(0));
2017 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2018 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2021 void SelectionDAGLowering::visitFPToUI(User &I) {
2022 // FPToUI is never a no-op cast, no need to check
2023 SDOperand N = getValue(I.getOperand(0));
2024 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2025 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2028 void SelectionDAGLowering::visitFPToSI(User &I) {
2029 // FPToSI is never a no-op cast, no need to check
2030 SDOperand N = getValue(I.getOperand(0));
2031 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2032 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2035 void SelectionDAGLowering::visitUIToFP(User &I) {
2036 // UIToFP is never a no-op cast, no need to check
2037 SDOperand N = getValue(I.getOperand(0));
2038 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2039 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2042 void SelectionDAGLowering::visitSIToFP(User &I){
2043 // UIToFP is never a no-op cast, no need to check
2044 SDOperand N = getValue(I.getOperand(0));
2045 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2046 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2049 void SelectionDAGLowering::visitPtrToInt(User &I) {
2050 // What to do depends on the size of the integer and the size of the pointer.
2051 // We can either truncate, zero extend, or no-op, accordingly.
2052 SDOperand N = getValue(I.getOperand(0));
2053 MVT::ValueType SrcVT = N.getValueType();
2054 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2056 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2057 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2059 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2060 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2061 setValue(&I, Result);
2064 void SelectionDAGLowering::visitIntToPtr(User &I) {
2065 // What to do depends on the size of the integer and the size of the pointer.
2066 // We can either truncate, zero extend, or no-op, accordingly.
2067 SDOperand N = getValue(I.getOperand(0));
2068 MVT::ValueType SrcVT = N.getValueType();
2069 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2070 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2071 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2073 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2074 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2077 void SelectionDAGLowering::visitBitCast(User &I) {
2078 SDOperand N = getValue(I.getOperand(0));
2079 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2081 // BitCast assures us that source and destination are the same size so this
2082 // is either a BIT_CONVERT or a no-op.
2083 if (DestVT != N.getValueType())
2084 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2086 setValue(&I, N); // noop cast.
2089 void SelectionDAGLowering::visitInsertElement(User &I) {
2090 SDOperand InVec = getValue(I.getOperand(0));
2091 SDOperand InVal = getValue(I.getOperand(1));
2092 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2093 getValue(I.getOperand(2)));
2095 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2096 TLI.getValueType(I.getType()),
2097 InVec, InVal, InIdx));
2100 void SelectionDAGLowering::visitExtractElement(User &I) {
2101 SDOperand InVec = getValue(I.getOperand(0));
2102 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2103 getValue(I.getOperand(1)));
2104 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2105 TLI.getValueType(I.getType()), InVec, InIdx));
2108 void SelectionDAGLowering::visitShuffleVector(User &I) {
2109 SDOperand V1 = getValue(I.getOperand(0));
2110 SDOperand V2 = getValue(I.getOperand(1));
2111 SDOperand Mask = getValue(I.getOperand(2));
2113 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2114 TLI.getValueType(I.getType()),
2119 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2120 SDOperand N = getValue(I.getOperand(0));
2121 const Type *Ty = I.getOperand(0)->getType();
2123 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2126 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2127 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2130 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2131 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2132 getIntPtrConstant(Offset));
2134 Ty = StTy->getElementType(Field);
2136 Ty = cast<SequentialType>(Ty)->getElementType();
2138 // If this is a constant subscript, handle it quickly.
2139 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2140 if (CI->getZExtValue() == 0) continue;
2142 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2143 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2147 // N = N + Idx * ElementSize;
2148 uint64_t ElementSize = TD->getTypeSize(Ty);
2149 SDOperand IdxN = getValue(Idx);
2151 // If the index is smaller or larger than intptr_t, truncate or extend
2153 if (IdxN.getValueType() < N.getValueType()) {
2154 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2155 } else if (IdxN.getValueType() > N.getValueType())
2156 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2158 // If this is a multiply by a power of two, turn it into a shl
2159 // immediately. This is a very common case.
2160 if (isPowerOf2_64(ElementSize)) {
2161 unsigned Amt = Log2_64(ElementSize);
2162 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2163 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2164 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2168 SDOperand Scale = getIntPtrConstant(ElementSize);
2169 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2170 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2176 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2177 // If this is a fixed sized alloca in the entry block of the function,
2178 // allocate it statically on the stack.
2179 if (FuncInfo.StaticAllocaMap.count(&I))
2180 return; // getValue will auto-populate this.
2182 const Type *Ty = I.getAllocatedType();
2183 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
2185 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2188 SDOperand AllocSize = getValue(I.getArraySize());
2189 MVT::ValueType IntPtr = TLI.getPointerTy();
2190 if (IntPtr < AllocSize.getValueType())
2191 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2192 else if (IntPtr > AllocSize.getValueType())
2193 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2195 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2196 getIntPtrConstant(TySize));
2198 // Handle alignment. If the requested alignment is less than or equal to the
2199 // stack alignment, ignore it and round the size of the allocation up to the
2200 // stack alignment size. If the size is greater than the stack alignment, we
2201 // note this in the DYNAMIC_STACKALLOC node.
2202 unsigned StackAlign =
2203 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2204 if (Align <= StackAlign) {
2206 // Add SA-1 to the size.
2207 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2208 getIntPtrConstant(StackAlign-1));
2209 // Mask out the low bits for alignment purposes.
2210 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2211 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2214 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
2215 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2217 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2219 DAG.setRoot(DSA.getValue(1));
2221 // Inform the Frame Information that we have just allocated a variable-sized
2223 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2226 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2227 SDOperand Ptr = getValue(I.getOperand(0));
2233 // Do not serialize non-volatile loads against each other.
2234 Root = DAG.getRoot();
2237 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2238 Root, I.isVolatile(), I.getAlignment()));
2241 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2242 const Value *SV, SDOperand Root,
2244 unsigned Alignment) {
2246 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2247 isVolatile, Alignment);
2250 DAG.setRoot(L.getValue(1));
2252 PendingLoads.push_back(L.getValue(1));
2258 void SelectionDAGLowering::visitStore(StoreInst &I) {
2259 Value *SrcV = I.getOperand(0);
2260 SDOperand Src = getValue(SrcV);
2261 SDOperand Ptr = getValue(I.getOperand(1));
2262 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2263 I.isVolatile(), I.getAlignment()));
2266 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2267 /// access memory and has no other side effects at all.
2268 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2269 #define GET_NO_MEMORY_INTRINSICS
2270 #include "llvm/Intrinsics.gen"
2271 #undef GET_NO_MEMORY_INTRINSICS
2275 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2276 // have any side-effects or if it only reads memory.
2277 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2278 #define GET_SIDE_EFFECT_INFO
2279 #include "llvm/Intrinsics.gen"
2280 #undef GET_SIDE_EFFECT_INFO
2284 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2286 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2287 unsigned Intrinsic) {
2288 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
2289 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
2291 // Build the operand list.
2292 SmallVector<SDOperand, 8> Ops;
2293 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2295 // We don't need to serialize loads against other loads.
2296 Ops.push_back(DAG.getRoot());
2298 Ops.push_back(getRoot());
2302 // Add the intrinsic ID as an integer operand.
2303 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2305 // Add all operands of the call to the operand list.
2306 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2307 SDOperand Op = getValue(I.getOperand(i));
2308 assert(TLI.isTypeLegal(Op.getValueType()) &&
2309 "Intrinsic uses a non-legal type?");
2313 std::vector<MVT::ValueType> VTs;
2314 if (I.getType() != Type::VoidTy) {
2315 MVT::ValueType VT = TLI.getValueType(I.getType());
2316 if (MVT::isVector(VT)) {
2317 const VectorType *DestTy = cast<VectorType>(I.getType());
2318 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2320 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2321 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2324 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2328 VTs.push_back(MVT::Other);
2330 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2335 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2336 &Ops[0], Ops.size());
2337 else if (I.getType() != Type::VoidTy)
2338 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2339 &Ops[0], Ops.size());
2341 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2342 &Ops[0], Ops.size());
2345 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2347 PendingLoads.push_back(Chain);
2351 if (I.getType() != Type::VoidTy) {
2352 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2353 MVT::ValueType VT = TLI.getValueType(PTy);
2354 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2356 setValue(&I, Result);
2360 /// ExtractGlobalVariable - If C is a global variable, or a bitcast of one
2361 /// (possibly constant folded), return it. Otherwise return NULL.
2362 static GlobalVariable *ExtractGlobalVariable (Constant *C) {
2363 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2365 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2366 if (CE->getOpcode() == Instruction::BitCast)
2367 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2368 else if (CE->getOpcode() == Instruction::GetElementPtr) {
2369 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2370 if (!CE->getOperand(i)->isNullValue())
2372 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2378 /// addCatchInfo - Extract the personality and type infos from an eh.selector
2379 /// or eh.filter call, and add them to the specified machine basic block.
2380 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2381 MachineBasicBlock *MBB) {
2382 // Inform the MachineModuleInfo of the personality for this landing pad.
2383 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2384 assert(CE->getOpcode() == Instruction::BitCast &&
2385 isa<Function>(CE->getOperand(0)) &&
2386 "Personality should be a function");
2387 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2389 // Gather all the type infos for this landing pad and pass them along to
2390 // MachineModuleInfo.
2391 std::vector<GlobalVariable *> TyInfo;
2392 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2393 Constant *C = cast<Constant>(I.getOperand(i));
2394 GlobalVariable *GV = ExtractGlobalVariable(C);
2395 assert (GV || isa<ConstantPointerNull>(C) &&
2396 "TypeInfo must be a global variable or NULL");
2397 TyInfo.push_back(GV);
2399 if (I.getCalledFunction()->getIntrinsicID() == Intrinsic::eh_filter)
2400 MMI->addFilterTypeInfo(MBB, TyInfo);
2402 MMI->addCatchTypeInfo(MBB, TyInfo);
2405 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2406 /// we want to emit this as a call to a named external function, return the name
2407 /// otherwise lower it and return null.
2409 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2410 switch (Intrinsic) {
2412 // By default, turn this into a target intrinsic node.
2413 visitTargetIntrinsic(I, Intrinsic);
2415 case Intrinsic::vastart: visitVAStart(I); return 0;
2416 case Intrinsic::vaend: visitVAEnd(I); return 0;
2417 case Intrinsic::vacopy: visitVACopy(I); return 0;
2418 case Intrinsic::returnaddress:
2419 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2420 getValue(I.getOperand(1))));
2422 case Intrinsic::frameaddress:
2423 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2424 getValue(I.getOperand(1))));
2426 case Intrinsic::setjmp:
2427 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2429 case Intrinsic::longjmp:
2430 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2432 case Intrinsic::memcpy_i32:
2433 case Intrinsic::memcpy_i64:
2434 visitMemIntrinsic(I, ISD::MEMCPY);
2436 case Intrinsic::memset_i32:
2437 case Intrinsic::memset_i64:
2438 visitMemIntrinsic(I, ISD::MEMSET);
2440 case Intrinsic::memmove_i32:
2441 case Intrinsic::memmove_i64:
2442 visitMemIntrinsic(I, ISD::MEMMOVE);
2445 case Intrinsic::dbg_stoppoint: {
2446 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2447 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2448 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2452 Ops[1] = getValue(SPI.getLineValue());
2453 Ops[2] = getValue(SPI.getColumnValue());
2455 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2456 assert(DD && "Not a debug information descriptor");
2457 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2459 Ops[3] = DAG.getString(CompileUnit->getFileName());
2460 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2462 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2467 case Intrinsic::dbg_region_start: {
2468 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2469 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2470 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2471 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2472 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2473 DAG.getConstant(LabelID, MVT::i32)));
2478 case Intrinsic::dbg_region_end: {
2479 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2480 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2481 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2482 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2483 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2484 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2489 case Intrinsic::dbg_func_start: {
2490 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2491 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2492 if (MMI && FSI.getSubprogram() &&
2493 MMI->Verify(FSI.getSubprogram())) {
2494 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
2495 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2496 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2501 case Intrinsic::dbg_declare: {
2502 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2503 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2504 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
2505 SDOperand AddressOp = getValue(DI.getAddress());
2506 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2507 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
2513 case Intrinsic::eh_exception: {
2514 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2516 if (ExceptionHandling && MMI) {
2517 // Mark exception register as live in.
2518 unsigned Reg = TLI.getExceptionAddressRegister();
2519 if (Reg) CurMBB->addLiveIn(Reg);
2521 // Insert the EXCEPTIONADDR instruction.
2522 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2524 Ops[0] = DAG.getRoot();
2525 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2527 DAG.setRoot(Op.getValue(1));
2529 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2534 case Intrinsic::eh_selector:
2535 case Intrinsic::eh_filter:{
2536 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2538 if (ExceptionHandling && MMI) {
2539 if (CurMBB->isLandingPad())
2540 addCatchInfo(I, MMI, CurMBB);
2543 FuncInfo.CatchInfoLost.insert(&I);
2546 // Mark exception selector register as live in.
2547 unsigned Reg = TLI.getExceptionSelectorRegister();
2548 if (Reg) CurMBB->addLiveIn(Reg);
2550 // Insert the EHSELECTION instruction.
2551 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2553 Ops[0] = getValue(I.getOperand(1));
2555 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2557 DAG.setRoot(Op.getValue(1));
2559 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2565 case Intrinsic::eh_typeid_for: {
2566 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2569 // Find the type id for the given typeinfo.
2570 Constant *C = cast<Constant>(I.getOperand(1));
2571 GlobalVariable *GV = ExtractGlobalVariable(C);
2572 assert (GV || isa<ConstantPointerNull>(C) &&
2573 "TypeInfo must be a global variable or NULL");
2575 unsigned TypeID = MMI->getTypeIDFor(GV);
2576 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2578 setValue(&I, DAG.getConstant(0, MVT::i32));
2584 case Intrinsic::sqrt_f32:
2585 case Intrinsic::sqrt_f64:
2586 setValue(&I, DAG.getNode(ISD::FSQRT,
2587 getValue(I.getOperand(1)).getValueType(),
2588 getValue(I.getOperand(1))));
2590 case Intrinsic::powi_f32:
2591 case Intrinsic::powi_f64:
2592 setValue(&I, DAG.getNode(ISD::FPOWI,
2593 getValue(I.getOperand(1)).getValueType(),
2594 getValue(I.getOperand(1)),
2595 getValue(I.getOperand(2))));
2597 case Intrinsic::pcmarker: {
2598 SDOperand Tmp = getValue(I.getOperand(1));
2599 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2602 case Intrinsic::readcyclecounter: {
2603 SDOperand Op = getRoot();
2604 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2605 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2608 DAG.setRoot(Tmp.getValue(1));
2611 case Intrinsic::part_select: {
2612 // Currently not implemented: just abort
2613 assert(0 && "part_select intrinsic not implemented");
2616 case Intrinsic::part_set: {
2617 // Currently not implemented: just abort
2618 assert(0 && "part_set intrinsic not implemented");
2621 case Intrinsic::bswap:
2622 setValue(&I, DAG.getNode(ISD::BSWAP,
2623 getValue(I.getOperand(1)).getValueType(),
2624 getValue(I.getOperand(1))));
2626 case Intrinsic::cttz: {
2627 SDOperand Arg = getValue(I.getOperand(1));
2628 MVT::ValueType Ty = Arg.getValueType();
2629 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2631 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2632 else if (Ty > MVT::i32)
2633 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2634 setValue(&I, result);
2637 case Intrinsic::ctlz: {
2638 SDOperand Arg = getValue(I.getOperand(1));
2639 MVT::ValueType Ty = Arg.getValueType();
2640 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2642 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2643 else if (Ty > MVT::i32)
2644 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2645 setValue(&I, result);
2648 case Intrinsic::ctpop: {
2649 SDOperand Arg = getValue(I.getOperand(1));
2650 MVT::ValueType Ty = Arg.getValueType();
2651 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2653 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2654 else if (Ty > MVT::i32)
2655 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2656 setValue(&I, result);
2659 case Intrinsic::stacksave: {
2660 SDOperand Op = getRoot();
2661 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2662 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2664 DAG.setRoot(Tmp.getValue(1));
2667 case Intrinsic::stackrestore: {
2668 SDOperand Tmp = getValue(I.getOperand(1));
2669 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2672 case Intrinsic::prefetch:
2673 // FIXME: Currently discarding prefetches.
2676 case Intrinsic::var_annotation:
2677 // Discard annotate attributes
2683 void SelectionDAGLowering::LowerCallTo(Instruction &I,
2684 const Type *CalledValueTy,
2685 unsigned CallingConv,
2687 SDOperand Callee, unsigned OpIdx,
2688 MachineBasicBlock *LandingPad) {
2689 const PointerType *PT = cast<PointerType>(CalledValueTy);
2690 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2691 const ParamAttrsList *Attrs = FTy->getParamAttrs();
2692 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2693 unsigned BeginLabel = 0, EndLabel = 0;
2695 TargetLowering::ArgListTy Args;
2696 TargetLowering::ArgListEntry Entry;
2697 Args.reserve(I.getNumOperands());
2698 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2699 Value *Arg = I.getOperand(i);
2700 SDOperand ArgNode = getValue(Arg);
2701 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2703 unsigned attrInd = i - OpIdx + 1;
2704 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2705 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2706 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2707 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
2708 Args.push_back(Entry);
2711 if (ExceptionHandling && MMI) {
2712 // Insert a label before the invoke call to mark the try range. This can be
2713 // used to detect deletion of the invoke via the MachineModuleInfo.
2714 BeginLabel = MMI->NextLabelID();
2715 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2716 DAG.getConstant(BeginLabel, MVT::i32)));
2719 std::pair<SDOperand,SDOperand> Result =
2720 TLI.LowerCallTo(getRoot(), I.getType(),
2721 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
2722 FTy->isVarArg(), CallingConv, IsTailCall,
2724 if (I.getType() != Type::VoidTy)
2725 setValue(&I, Result.first);
2726 DAG.setRoot(Result.second);
2728 if (ExceptionHandling && MMI) {
2729 // Insert a label at the end of the invoke call to mark the try range. This
2730 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2731 EndLabel = MMI->NextLabelID();
2732 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2733 DAG.getConstant(EndLabel, MVT::i32)));
2735 // Inform MachineModuleInfo of range.
2736 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2741 void SelectionDAGLowering::visitCall(CallInst &I) {
2742 const char *RenameFn = 0;
2743 if (Function *F = I.getCalledFunction()) {
2744 if (F->isDeclaration())
2745 if (unsigned IID = F->getIntrinsicID()) {
2746 RenameFn = visitIntrinsicCall(I, IID);
2749 } else { // Not an LLVM intrinsic.
2750 const std::string &Name = F->getName();
2751 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2752 if (I.getNumOperands() == 3 && // Basic sanity checks.
2753 I.getOperand(1)->getType()->isFloatingPoint() &&
2754 I.getType() == I.getOperand(1)->getType() &&
2755 I.getType() == I.getOperand(2)->getType()) {
2756 SDOperand LHS = getValue(I.getOperand(1));
2757 SDOperand RHS = getValue(I.getOperand(2));
2758 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2762 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2763 if (I.getNumOperands() == 2 && // Basic sanity checks.
2764 I.getOperand(1)->getType()->isFloatingPoint() &&
2765 I.getType() == I.getOperand(1)->getType()) {
2766 SDOperand Tmp = getValue(I.getOperand(1));
2767 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2770 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2771 if (I.getNumOperands() == 2 && // Basic sanity checks.
2772 I.getOperand(1)->getType()->isFloatingPoint() &&
2773 I.getType() == I.getOperand(1)->getType()) {
2774 SDOperand Tmp = getValue(I.getOperand(1));
2775 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2778 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2779 if (I.getNumOperands() == 2 && // Basic sanity checks.
2780 I.getOperand(1)->getType()->isFloatingPoint() &&
2781 I.getType() == I.getOperand(1)->getType()) {
2782 SDOperand Tmp = getValue(I.getOperand(1));
2783 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2788 } else if (isa<InlineAsm>(I.getOperand(0))) {
2795 Callee = getValue(I.getOperand(0));
2797 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2799 LowerCallTo(I, I.getCalledValue()->getType(),
2807 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2808 SDOperand &Chain, SDOperand &Flag)const{
2809 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2810 Chain = Val.getValue(1);
2811 Flag = Val.getValue(2);
2813 // If the result was expanded, copy from the top part.
2814 if (Regs.size() > 1) {
2815 assert(Regs.size() == 2 &&
2816 "Cannot expand to more than 2 elts yet!");
2817 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2818 Chain = Hi.getValue(1);
2819 Flag = Hi.getValue(2);
2820 if (DAG.getTargetLoweringInfo().isLittleEndian())
2821 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2823 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2826 // Otherwise, if the return value was promoted or extended, truncate it to the
2827 // appropriate type.
2828 if (RegVT == ValueVT)
2831 if (MVT::isVector(RegVT)) {
2832 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
2833 return DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2836 if (MVT::isInteger(RegVT)) {
2837 if (ValueVT < RegVT)
2838 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2840 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2843 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2844 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2847 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2848 /// specified value into the registers specified by this object. This uses
2849 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2850 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2851 SDOperand &Chain, SDOperand &Flag,
2852 MVT::ValueType PtrVT) const {
2853 if (Regs.size() == 1) {
2854 // If there is a single register and the types differ, this must be
2856 if (RegVT != ValueVT) {
2857 if (MVT::isVector(RegVT)) {
2858 assert(MVT::isVector(Val.getValueType()) &&
2859 "Not a vector-vector cast?");
2860 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2861 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
2862 if (RegVT < ValueVT)
2863 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2865 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2866 } else if (MVT::isFloatingPoint(RegVT) &&
2867 MVT::isFloatingPoint(Val.getValueType())) {
2868 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2869 } else if (MVT::getSizeInBits(RegVT) ==
2870 MVT::getSizeInBits(Val.getValueType())) {
2871 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2873 assert(0 && "Unknown mismatch!");
2876 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2877 Flag = Chain.getValue(1);
2879 std::vector<unsigned> R(Regs);
2880 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2881 std::reverse(R.begin(), R.end());
2883 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2884 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2885 DAG.getConstant(i, PtrVT));
2886 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2887 Flag = Chain.getValue(1);
2892 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2893 /// operand list. This adds the code marker and includes the number of
2894 /// values added into it.
2895 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2896 std::vector<SDOperand> &Ops) const {
2897 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2898 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
2899 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2900 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2903 /// isAllocatableRegister - If the specified register is safe to allocate,
2904 /// i.e. it isn't a stack pointer or some other special register, return the
2905 /// register class for the register. Otherwise, return null.
2906 static const TargetRegisterClass *
2907 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2908 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2909 MVT::ValueType FoundVT = MVT::Other;
2910 const TargetRegisterClass *FoundRC = 0;
2911 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2912 E = MRI->regclass_end(); RCI != E; ++RCI) {
2913 MVT::ValueType ThisVT = MVT::Other;
2915 const TargetRegisterClass *RC = *RCI;
2916 // If none of the the value types for this register class are valid, we
2917 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2918 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2920 if (TLI.isTypeLegal(*I)) {
2921 // If we have already found this register in a different register class,
2922 // choose the one with the largest VT specified. For example, on
2923 // PowerPC, we favor f64 register classes over f32.
2924 if (FoundVT == MVT::Other ||
2925 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2932 if (ThisVT == MVT::Other) continue;
2934 // NOTE: This isn't ideal. In particular, this might allocate the
2935 // frame pointer in functions that need it (due to them not being taken
2936 // out of allocation, because a variable sized allocation hasn't been seen
2937 // yet). This is a slight code pessimization, but should still work.
2938 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2939 E = RC->allocation_order_end(MF); I != E; ++I)
2941 // We found a matching register class. Keep looking at others in case
2942 // we find one with larger registers that this physreg is also in.
2953 /// AsmOperandInfo - This contains information for each constraint that we are
2955 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2956 /// ConstraintCode - This contains the actual string for the code, like "m".
2957 std::string ConstraintCode;
2959 /// ConstraintType - Information about the constraint code, e.g. Register,
2960 /// RegisterClass, Memory, Other, Unknown.
2961 TargetLowering::ConstraintType ConstraintType;
2963 /// CallOperand/CallOperandval - If this is the result output operand or a
2964 /// clobber, this is null, otherwise it is the incoming operand to the
2965 /// CallInst. This gets modified as the asm is processed.
2966 SDOperand CallOperand;
2967 Value *CallOperandVal;
2969 /// ConstraintVT - The ValueType for the operand value.
2970 MVT::ValueType ConstraintVT;
2972 /// AssignedRegs - If this is a register or register class operand, this
2973 /// contains the set of register corresponding to the operand.
2974 RegsForValue AssignedRegs;
2976 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
2977 : InlineAsm::ConstraintInfo(info),
2978 ConstraintType(TargetLowering::C_Unknown),
2979 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
2982 void ComputeConstraintToUse(const TargetLowering &TLI);
2984 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
2985 /// busy in OutputRegs/InputRegs.
2986 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
2987 std::set<unsigned> &OutputRegs,
2988 std::set<unsigned> &InputRegs) const {
2990 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
2992 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
2995 } // end anon namespace.
2997 /// getConstraintGenerality - Return an integer indicating how general CT is.
2998 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3000 default: assert(0 && "Unknown constraint type!");
3001 case TargetLowering::C_Other:
3002 case TargetLowering::C_Unknown:
3004 case TargetLowering::C_Register:
3006 case TargetLowering::C_RegisterClass:
3008 case TargetLowering::C_Memory:
3013 void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3014 assert(!Codes.empty() && "Must have at least one constraint");
3016 std::string *Current = &Codes[0];
3017 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3018 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3019 ConstraintCode = *Current;
3020 ConstraintType = CurType;
3024 unsigned CurGenerality = getConstraintGenerality(CurType);
3026 // If we have multiple constraints, try to pick the most general one ahead
3027 // of time. This isn't a wonderful solution, but handles common cases.
3028 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3029 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3030 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3031 if (ThisGenerality > CurGenerality) {
3032 // This constraint letter is more general than the previous one,
3035 Current = &Codes[j];
3036 CurGenerality = ThisGenerality;
3040 ConstraintCode = *Current;
3041 ConstraintType = CurType;
3045 void SelectionDAGLowering::
3046 GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
3047 std::set<unsigned> &OutputRegs,
3048 std::set<unsigned> &InputRegs) {
3049 // Compute whether this value requires an input register, an output register,
3051 bool isOutReg = false;
3052 bool isInReg = false;
3053 switch (OpInfo.Type) {
3054 case InlineAsm::isOutput:
3057 // If this is an early-clobber output, or if there is an input
3058 // constraint that matches this, we need to reserve the input register
3059 // so no other inputs allocate to it.
3060 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3062 case InlineAsm::isInput:
3066 case InlineAsm::isClobber:
3073 MachineFunction &MF = DAG.getMachineFunction();
3074 std::vector<unsigned> Regs;
3076 // If this is a constraint for a single physreg, or a constraint for a
3077 // register class, find it.
3078 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3079 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3080 OpInfo.ConstraintVT);
3082 unsigned NumRegs = 1;
3083 if (OpInfo.ConstraintVT != MVT::Other)
3084 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3085 MVT::ValueType RegVT;
3086 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3089 // If this is a constraint for a specific physical register, like {r17},
3091 if (PhysReg.first) {
3092 if (OpInfo.ConstraintVT == MVT::Other)
3093 ValueVT = *PhysReg.second->vt_begin();
3095 // Get the actual register value type. This is important, because the user
3096 // may have asked for (e.g.) the AX register in i32 type. We need to
3097 // remember that AX is actually i16 to get the right extension.
3098 RegVT = *PhysReg.second->vt_begin();
3100 // This is a explicit reference to a physical register.
3101 Regs.push_back(PhysReg.first);
3103 // If this is an expanded reference, add the rest of the regs to Regs.
3105 TargetRegisterClass::iterator I = PhysReg.second->begin();
3106 TargetRegisterClass::iterator E = PhysReg.second->end();
3107 for (; *I != PhysReg.first; ++I)
3108 assert(I != E && "Didn't find reg!");
3110 // Already added the first reg.
3112 for (; NumRegs; --NumRegs, ++I) {
3113 assert(I != E && "Ran out of registers to allocate!");
3117 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3118 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3122 // Otherwise, if this was a reference to an LLVM register class, create vregs
3123 // for this reference.
3124 std::vector<unsigned> RegClassRegs;
3125 const TargetRegisterClass *RC = PhysReg.second;
3127 // If this is an early clobber or tied register, our regalloc doesn't know
3128 // how to maintain the constraint. If it isn't, go ahead and create vreg
3129 // and let the regalloc do the right thing.
3130 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3131 // If there is some other early clobber and this is an input register,
3132 // then we are forced to pre-allocate the input reg so it doesn't
3133 // conflict with the earlyclobber.
3134 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3135 RegVT = *PhysReg.second->vt_begin();
3137 if (OpInfo.ConstraintVT == MVT::Other)
3140 // Create the appropriate number of virtual registers.
3141 SSARegMap *RegMap = MF.getSSARegMap();
3142 for (; NumRegs; --NumRegs)
3143 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3145 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3146 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3150 // Otherwise, we can't allocate it. Let the code below figure out how to
3151 // maintain these constraints.
3152 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3155 // This is a reference to a register class that doesn't directly correspond
3156 // to an LLVM register class. Allocate NumRegs consecutive, available,
3157 // registers from the class.
3158 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3159 OpInfo.ConstraintVT);
3162 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3163 unsigned NumAllocated = 0;
3164 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3165 unsigned Reg = RegClassRegs[i];
3166 // See if this register is available.
3167 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3168 (isInReg && InputRegs.count(Reg))) { // Already used.
3169 // Make sure we find consecutive registers.
3174 // Check to see if this register is allocatable (i.e. don't give out the
3177 RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3178 if (!RC) { // Couldn't allocate this register.
3179 // Reset NumAllocated to make sure we return consecutive registers.
3185 // Okay, this register is good, we can use it.
3188 // If we allocated enough consecutive registers, succeed.
3189 if (NumAllocated == NumRegs) {
3190 unsigned RegStart = (i-NumAllocated)+1;
3191 unsigned RegEnd = i+1;
3192 // Mark all of the allocated registers used.
3193 for (unsigned i = RegStart; i != RegEnd; ++i)
3194 Regs.push_back(RegClassRegs[i]);
3196 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3197 OpInfo.ConstraintVT);
3198 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3203 // Otherwise, we couldn't allocate enough registers for this.
3208 /// visitInlineAsm - Handle a call to an InlineAsm object.
3210 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3211 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
3213 /// ConstraintOperands - Information about all of the constraints.
3214 std::vector<AsmOperandInfo> ConstraintOperands;
3216 SDOperand Chain = getRoot();
3219 std::set<unsigned> OutputRegs, InputRegs;
3221 // Do a prepass over the constraints, canonicalizing them, and building up the
3222 // ConstraintOperands list.
3223 std::vector<InlineAsm::ConstraintInfo>
3224 ConstraintInfos = IA->ParseConstraints();
3226 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3227 // constraint. If so, we can't let the register allocator allocate any input
3228 // registers, because it will not know to avoid the earlyclobbered output reg.
3229 bool SawEarlyClobber = false;
3231 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
3232 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3233 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3234 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3236 MVT::ValueType OpVT = MVT::Other;
3238 // Compute the value type for each operand.
3239 switch (OpInfo.Type) {
3240 case InlineAsm::isOutput:
3241 if (!OpInfo.isIndirect) {
3242 // The return value of the call is this value. As such, there is no
3243 // corresponding argument.
3244 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3245 OpVT = TLI.getValueType(I.getType());
3247 OpInfo.CallOperandVal = I.getOperand(OpNo++);
3250 case InlineAsm::isInput:
3251 OpInfo.CallOperandVal = I.getOperand(OpNo++);
3253 case InlineAsm::isClobber:
3258 // If this is an input or an indirect output, process the call argument.
3259 if (OpInfo.CallOperandVal) {
3260 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3261 const Type *OpTy = OpInfo.CallOperandVal->getType();
3262 // If this is an indirect operand, the operand is a pointer to the
3264 if (OpInfo.isIndirect)
3265 OpTy = cast<PointerType>(OpTy)->getElementType();
3267 // If OpTy is not a first-class value, it may be a struct/union that we
3268 // can tile with integers.
3269 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3270 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3278 OpTy = IntegerType::get(BitSize);
3283 OpVT = TLI.getValueType(OpTy, true);
3286 OpInfo.ConstraintVT = OpVT;
3288 // Compute the constraint code and ConstraintType to use.
3289 OpInfo.ComputeConstraintToUse(TLI);
3291 // Keep track of whether we see an earlyclobber.
3292 SawEarlyClobber |= OpInfo.isEarlyClobber;
3294 // If this is a memory input, and if the operand is not indirect, do what we
3295 // need to to provide an address for the memory input.
3296 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3297 !OpInfo.isIndirect) {
3298 assert(OpInfo.Type == InlineAsm::isInput &&
3299 "Can only indirectify direct input operands!");
3301 // Memory operands really want the address of the value. If we don't have
3302 // an indirect input, put it in the constpool if we can, otherwise spill
3303 // it to a stack slot.
3305 // If the operand is a float, integer, or vector constant, spill to a
3306 // constant pool entry to get its address.
3307 Value *OpVal = OpInfo.CallOperandVal;
3308 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3309 isa<ConstantVector>(OpVal)) {
3310 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3311 TLI.getPointerTy());
3313 // Otherwise, create a stack slot and emit a store to it before the
3315 const Type *Ty = OpVal->getType();
3316 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3317 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3318 MachineFunction &MF = DAG.getMachineFunction();
3319 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3320 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3321 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3322 OpInfo.CallOperand = StackSlot;
3325 // There is no longer a Value* corresponding to this operand.
3326 OpInfo.CallOperandVal = 0;
3327 // It is now an indirect operand.
3328 OpInfo.isIndirect = true;
3331 // If this constraint is for a specific register, allocate it before
3333 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3334 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3336 ConstraintInfos.clear();
3339 // Second pass - Loop over all of the operands, assigning virtual or physregs
3340 // to registerclass operands.
3341 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3342 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3344 // C_Register operands have already been allocated, Other/Memory don't need
3346 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3347 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3350 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3351 std::vector<SDOperand> AsmNodeOperands;
3352 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3353 AsmNodeOperands.push_back(
3354 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3357 // Loop over all of the inputs, copying the operand values into the
3358 // appropriate registers and processing the output regs.
3359 RegsForValue RetValRegs;
3361 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3362 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3364 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3365 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3367 switch (OpInfo.Type) {
3368 case InlineAsm::isOutput: {
3369 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3370 OpInfo.ConstraintType != TargetLowering::C_Register) {
3371 // Memory output, or 'other' output (e.g. 'X' constraint).
3372 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3374 // Add information to the INLINEASM node to know about this output.
3375 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3376 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3377 TLI.getPointerTy()));
3378 AsmNodeOperands.push_back(OpInfo.CallOperand);
3382 // Otherwise, this is a register or register class output.
3384 // Copy the output from the appropriate register. Find a register that
3386 if (OpInfo.AssignedRegs.Regs.empty()) {
3387 cerr << "Couldn't allocate output reg for contraint '"
3388 << OpInfo.ConstraintCode << "'!\n";
3392 if (!OpInfo.isIndirect) {
3393 // This is the result value of the call.
3394 assert(RetValRegs.Regs.empty() &&
3395 "Cannot have multiple output constraints yet!");
3396 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3397 RetValRegs = OpInfo.AssignedRegs;
3399 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
3400 OpInfo.CallOperandVal));
3403 // Add information to the INLINEASM node to know that this register is
3405 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3409 case InlineAsm::isInput: {
3410 SDOperand InOperandVal = OpInfo.CallOperand;
3412 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
3413 // If this is required to match an output register we have already set,
3414 // just use its register.
3415 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
3417 // Scan until we find the definition we already emitted of this operand.
3418 // When we find it, create a RegsForValue operand.
3419 unsigned CurOp = 2; // The first operand.
3420 for (; OperandNo; --OperandNo) {
3421 // Advance to the next operand.
3423 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3424 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3425 (NumOps & 7) == 4 /*MEM*/) &&
3426 "Skipped past definitions?");
3427 CurOp += (NumOps>>3)+1;
3431 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3432 if ((NumOps & 7) == 2 /*REGDEF*/) {
3433 // Add NumOps>>3 registers to MatchedRegs.
3434 RegsForValue MatchedRegs;
3435 MatchedRegs.ValueVT = InOperandVal.getValueType();
3436 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3437 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3439 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3440 MatchedRegs.Regs.push_back(Reg);
3443 // Use the produced MatchedRegs object to
3444 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3445 TLI.getPointerTy());
3446 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3449 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3450 assert(0 && "matching constraints for memory operands unimp");
3454 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
3455 assert(!OpInfo.isIndirect &&
3456 "Don't know how to handle indirect other inputs yet!");
3458 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3459 OpInfo.ConstraintCode[0],
3461 if (!InOperandVal.Val) {
3462 cerr << "Invalid operand for inline asm constraint '"
3463 << OpInfo.ConstraintCode << "'!\n";
3467 // Add information to the INLINEASM node to know about this input.
3468 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3469 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3470 TLI.getPointerTy()));
3471 AsmNodeOperands.push_back(InOperandVal);
3473 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
3474 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
3475 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3476 "Memory operands expect pointer values");
3478 // Add information to the INLINEASM node to know about this input.
3479 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3480 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3481 TLI.getPointerTy()));
3482 AsmNodeOperands.push_back(InOperandVal);
3486 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3487 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3488 "Unknown constraint type!");
3489 assert(!OpInfo.isIndirect &&
3490 "Don't know how to handle indirect register inputs yet!");
3492 // Copy the input into the appropriate registers.
3493 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3494 "Couldn't allocate input reg!");
3496 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3497 TLI.getPointerTy());
3499 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3503 case InlineAsm::isClobber: {
3504 // Add the clobbered value to the operand list, so that the register
3505 // allocator is aware that the physreg got clobbered.
3506 if (!OpInfo.AssignedRegs.Regs.empty())
3507 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3514 // Finish up input operands.
3515 AsmNodeOperands[0] = Chain;
3516 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3518 Chain = DAG.getNode(ISD::INLINEASM,
3519 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
3520 &AsmNodeOperands[0], AsmNodeOperands.size());
3521 Flag = Chain.getValue(1);
3523 // If this asm returns a register value, copy the result from that register
3524 // and set it as the value of the call.
3525 if (!RetValRegs.Regs.empty()) {
3526 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3528 // If the result of the inline asm is a vector, it may have the wrong
3529 // width/num elts. Make sure to convert it to the right type with
3531 if (MVT::isVector(Val.getValueType())) {
3532 const VectorType *VTy = cast<VectorType>(I.getType());
3533 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
3535 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
3541 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3543 // Process indirect outputs, first output all of the flagged copies out of
3545 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
3546 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
3547 Value *Ptr = IndirectStoresToEmit[i].second;
3548 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3549 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
3552 // Emit the non-flagged stores from the physregs.
3553 SmallVector<SDOperand, 8> OutChains;
3554 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
3555 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
3556 getValue(StoresToEmit[i].second),
3557 StoresToEmit[i].second, 0));
3558 if (!OutChains.empty())
3559 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3560 &OutChains[0], OutChains.size());
3565 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3566 SDOperand Src = getValue(I.getOperand(0));
3568 MVT::ValueType IntPtr = TLI.getPointerTy();
3570 if (IntPtr < Src.getValueType())
3571 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3572 else if (IntPtr > Src.getValueType())
3573 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
3575 // Scale the source by the type size.
3576 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
3577 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3578 Src, getIntPtrConstant(ElementSize));
3580 TargetLowering::ArgListTy Args;
3581 TargetLowering::ArgListEntry Entry;
3583 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3584 Args.push_back(Entry);
3586 std::pair<SDOperand,SDOperand> Result =
3587 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
3588 DAG.getExternalSymbol("malloc", IntPtr),
3590 setValue(&I, Result.first); // Pointers always fit in registers
3591 DAG.setRoot(Result.second);
3594 void SelectionDAGLowering::visitFree(FreeInst &I) {
3595 TargetLowering::ArgListTy Args;
3596 TargetLowering::ArgListEntry Entry;
3597 Entry.Node = getValue(I.getOperand(0));
3598 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3599 Args.push_back(Entry);
3600 MVT::ValueType IntPtr = TLI.getPointerTy();
3601 std::pair<SDOperand,SDOperand> Result =
3602 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
3603 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3604 DAG.setRoot(Result.second);
3607 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
3608 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3609 // instructions are special in various ways, which require special support to
3610 // insert. The specified MachineInstr is created but not inserted into any
3611 // basic blocks, and the scheduler passes ownership of it to this method.
3612 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3613 MachineBasicBlock *MBB) {
3614 cerr << "If a target marks an instruction with "
3615 << "'usesCustomDAGSchedInserter', it must implement "
3616 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
3621 void SelectionDAGLowering::visitVAStart(CallInst &I) {
3622 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3623 getValue(I.getOperand(1)),
3624 DAG.getSrcValue(I.getOperand(1))));
3627 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
3628 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3629 getValue(I.getOperand(0)),
3630 DAG.getSrcValue(I.getOperand(0)));
3632 DAG.setRoot(V.getValue(1));
3635 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
3636 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3637 getValue(I.getOperand(1)),
3638 DAG.getSrcValue(I.getOperand(1))));
3641 void SelectionDAGLowering::visitVACopy(CallInst &I) {
3642 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3643 getValue(I.getOperand(1)),
3644 getValue(I.getOperand(2)),
3645 DAG.getSrcValue(I.getOperand(1)),
3646 DAG.getSrcValue(I.getOperand(2))));
3649 /// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3650 /// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3651 static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3652 unsigned &i, SelectionDAG &DAG,
3653 TargetLowering &TLI) {
3654 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3655 return SDOperand(Arg, i++);
3657 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3658 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3660 return DAG.getNode(ISD::BIT_CONVERT, VT,
3661 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3662 } else if (NumVals == 2) {
3663 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3664 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3665 if (!TLI.isLittleEndian())
3667 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3669 // Value scalarized into many values. Unimp for now.
3670 assert(0 && "Cannot expand i64 -> i16 yet!");
3675 /// TargetLowering::LowerArguments - This is the default LowerArguments
3676 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
3677 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3678 /// integrated into SDISel.
3679 std::vector<SDOperand>
3680 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
3681 const FunctionType *FTy = F.getFunctionType();
3682 const ParamAttrsList *Attrs = FTy->getParamAttrs();
3683 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3684 std::vector<SDOperand> Ops;
3685 Ops.push_back(DAG.getRoot());
3686 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3687 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3689 // Add one result value for each formal argument.
3690 std::vector<MVT::ValueType> RetVals;
3692 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3694 MVT::ValueType VT = getValueType(I->getType());
3695 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3696 unsigned OriginalAlignment =
3697 getTargetData()->getABITypeAlignment(I->getType());
3699 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3700 // that is zero extended!
3701 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
3702 Flags &= ~(ISD::ParamFlags::SExt);
3703 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
3704 Flags |= ISD::ParamFlags::SExt;
3705 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
3706 Flags |= ISD::ParamFlags::InReg;
3707 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
3708 Flags |= ISD::ParamFlags::StructReturn;
3709 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
3711 switch (getTypeAction(VT)) {
3712 default: assert(0 && "Unknown type action!");
3714 RetVals.push_back(VT);
3715 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3718 RetVals.push_back(getTypeToTransformTo(VT));
3719 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3722 if (!MVT::isVector(VT)) {
3723 // If this is a large integer, it needs to be broken up into small
3724 // integers. Figure out what the destination type is and how many small
3725 // integers it turns into.
3726 MVT::ValueType NVT = getTypeToExpandTo(VT);
3727 unsigned NumVals = getNumRegisters(VT);
3728 for (unsigned i = 0; i != NumVals; ++i) {
3729 RetVals.push_back(NVT);
3730 // if it isn't first piece, alignment must be 1
3732 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3733 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3734 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3737 // Otherwise, this is a vector type. We only support legal vectors
3739 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3740 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
3742 // Figure out if there is a Packed type corresponding to this Vector
3743 // type. If so, convert to the vector type.
3744 MVT::ValueType TVT =
3745 MVT::getVectorType(getValueType(EltTy), NumElems);
3746 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3747 RetVals.push_back(TVT);
3748 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3750 assert(0 && "Don't support illegal by-val vector arguments yet!");
3757 RetVals.push_back(MVT::Other);
3760 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3761 DAG.getNodeValueTypes(RetVals), RetVals.size(),
3762 &Ops[0], Ops.size()).Val;
3764 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
3766 // Set up the return result vector.
3770 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3772 MVT::ValueType VT = getValueType(I->getType());
3774 switch (getTypeAction(VT)) {
3775 default: assert(0 && "Unknown type action!");
3777 Ops.push_back(SDOperand(Result, i++));
3780 SDOperand Op(Result, i++);
3781 if (MVT::isInteger(VT)) {
3782 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
3783 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3784 DAG.getValueType(VT));
3785 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
3786 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3787 DAG.getValueType(VT));
3788 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3790 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3791 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3797 if (!MVT::isVector(VT)) {
3798 // If this is a large integer or a floating point node that needs to be
3799 // expanded, it needs to be reassembled from small integers. Figure out
3800 // what the source elt type is and how many small integers it is.
3801 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
3803 // Otherwise, this is a vector type. We only support legal vectors
3805 const VectorType *PTy = cast<VectorType>(I->getType());
3806 unsigned NumElems = PTy->getNumElements();
3807 const Type *EltTy = PTy->getElementType();
3809 // Figure out if there is a Packed type corresponding to this Vector
3810 // type. If so, convert to the vector type.
3811 MVT::ValueType TVT =
3812 MVT::getVectorType(getValueType(EltTy), NumElems);
3813 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3814 SDOperand N = SDOperand(Result, i++);
3815 // Handle copies from vectors to registers.
3816 N = DAG.getNode(ISD::BIT_CONVERT, TVT, N);
3819 assert(0 && "Don't support illegal by-val vector arguments yet!");
3830 /// ExpandScalarCallArgs - Recursively expand call argument node by
3831 /// bit_converting it or extract a pair of elements from the larger node.
3832 static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3834 SmallVector<SDOperand, 32> &Ops,
3836 TargetLowering &TLI,
3837 bool isFirst = true) {
3839 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3840 // if it isn't first piece, alignment must be 1
3842 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3843 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3845 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3849 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3850 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3852 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3853 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
3854 } else if (NumVals == 2) {
3855 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3856 DAG.getConstant(0, TLI.getPointerTy()));
3857 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3858 DAG.getConstant(1, TLI.getPointerTy()));
3859 if (!TLI.isLittleEndian())
3861 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3862 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
3864 // Value scalarized into many values. Unimp for now.
3865 assert(0 && "Cannot expand i64 -> i16 yet!");
3869 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
3870 /// implementation, which just inserts an ISD::CALL node, which is later custom
3871 /// lowered by the target to something concrete. FIXME: When all targets are
3872 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3873 std::pair<SDOperand, SDOperand>
3874 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3875 bool RetTyIsSigned, bool isVarArg,
3876 unsigned CallingConv, bool isTailCall,
3878 ArgListTy &Args, SelectionDAG &DAG) {
3879 SmallVector<SDOperand, 32> Ops;
3880 Ops.push_back(Chain); // Op#0 - Chain
3881 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3882 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3883 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3884 Ops.push_back(Callee);
3886 // Handle all of the outgoing arguments.
3887 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3888 MVT::ValueType VT = getValueType(Args[i].Ty);
3889 SDOperand Op = Args[i].Node;
3890 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3891 unsigned OriginalAlignment =
3892 getTargetData()->getABITypeAlignment(Args[i].Ty);
3895 Flags |= ISD::ParamFlags::SExt;
3897 Flags |= ISD::ParamFlags::ZExt;
3898 if (Args[i].isInReg)
3899 Flags |= ISD::ParamFlags::InReg;
3901 Flags |= ISD::ParamFlags::StructReturn;
3902 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
3904 switch (getTypeAction(VT)) {
3905 default: assert(0 && "Unknown type action!");
3908 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3911 if (MVT::isInteger(VT)) {
3914 ExtOp = ISD::SIGN_EXTEND;
3915 else if (Args[i].isZExt)
3916 ExtOp = ISD::ZERO_EXTEND;
3918 ExtOp = ISD::ANY_EXTEND;
3919 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3921 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3922 // A true promotion would change the size of the argument.
3923 // Instead, pretend this is an int. If FP objects are not
3924 // passed the same as ints, the original type should be Legal
3925 // and we should not get here.
3926 Op = DAG.getNode(ISD::BIT_CONVERT,
3927 VT==MVT::f32 ? MVT::i32 :
3928 (VT==MVT::f64 ? MVT::i64 :
3933 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3936 if (!MVT::isVector(VT)) {
3937 // If this is a large integer, it needs to be broken down into small
3938 // integers. Figure out what the source elt type is and how many small
3940 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
3942 // Otherwise, this is a vector type. We only support legal vectors
3944 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
3945 unsigned NumElems = PTy->getNumElements();
3946 const Type *EltTy = PTy->getElementType();
3948 // Figure out if there is a Packed type corresponding to this Vector
3949 // type. If so, convert to the vector type.
3950 MVT::ValueType TVT =
3951 MVT::getVectorType(getValueType(EltTy), NumElems);
3952 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3953 // Insert a BIT_CONVERT of the original type to the vector type.
3954 Op = DAG.getNode(ISD::BIT_CONVERT, TVT, Op);
3956 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3958 assert(0 && "Don't support illegal by-val vector call args yet!");
3966 // Figure out the result value types.
3967 SmallVector<MVT::ValueType, 4> RetTys;
3969 if (RetTy != Type::VoidTy) {
3970 MVT::ValueType VT = getValueType(RetTy);
3971 switch (getTypeAction(VT)) {
3972 default: assert(0 && "Unknown type action!");
3974 RetTys.push_back(VT);
3977 RetTys.push_back(getTypeToTransformTo(VT));
3980 if (!MVT::isVector(VT)) {
3981 // If this is a large integer, it needs to be reassembled from small
3982 // integers. Figure out what the source elt type is and how many small
3984 MVT::ValueType NVT = getTypeToExpandTo(VT);
3985 unsigned NumVals = getNumRegisters(VT);
3986 for (unsigned i = 0; i != NumVals; ++i)
3987 RetTys.push_back(NVT);
3989 // Otherwise, this is a vector type. We only support legal vectors
3991 const VectorType *PTy = cast<VectorType>(RetTy);
3992 unsigned NumElems = PTy->getNumElements();
3993 const Type *EltTy = PTy->getElementType();
3995 // Figure out if there is a Packed type corresponding to this Vector
3996 // type. If so, convert to the vector type.
3997 MVT::ValueType TVT =
3998 MVT::getVectorType(getValueType(EltTy), NumElems);
3999 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4000 RetTys.push_back(TVT);
4002 assert(0 && "Don't support illegal by-val vector call results yet!");
4009 RetTys.push_back(MVT::Other); // Always has a chain.
4011 // Finally, create the CALL node.
4012 SDOperand Res = DAG.getNode(ISD::CALL,
4013 DAG.getVTList(&RetTys[0], RetTys.size()),
4014 &Ops[0], Ops.size());
4016 // This returns a pair of operands. The first element is the
4017 // return value for the function (if RetTy is not VoidTy). The second
4018 // element is the outgoing token chain.
4020 if (RetTys.size() != 1) {
4021 MVT::ValueType VT = getValueType(RetTy);
4022 if (RetTys.size() == 2) {
4025 // If this value was promoted, truncate it down.
4026 if (ResVal.getValueType() != VT) {
4027 if (MVT::isVector(VT)) {
4028 // Insert a BIT_CONVERT to convert from the packed result type to the
4030 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4031 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
4033 // Figure out if there is a Packed type corresponding to this Vector
4034 // type. If so, convert to the vector type.
4035 MVT::ValueType TVT =
4036 MVT::getVectorType(getValueType(EltTy),NumElems);
4037 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4038 // Insert a BIT_CONVERT of the FORMAL_ARGUMENTS to a
4039 // "N x PTyElementVT" vector type.
4040 ResVal = DAG.getNode(ISD::BIT_CONVERT, TVT, ResVal);
4044 } else if (MVT::isInteger(VT)) {
4045 unsigned AssertOp = ISD::AssertSext;
4047 AssertOp = ISD::AssertZext;
4048 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4049 DAG.getValueType(VT));
4050 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4052 assert(MVT::isFloatingPoint(VT));
4053 if (getTypeAction(VT) == Expand)
4054 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4056 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
4059 } else if (RetTys.size() == 3) {
4060 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4061 Res.getValue(0), Res.getValue(1));
4064 assert(0 && "Case not handled yet!");
4068 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4071 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4072 assert(0 && "LowerOperation not implemented for this target!");
4077 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4078 SelectionDAG &DAG) {
4079 assert(0 && "CustomPromoteOperation not implemented for this target!");
4084 /// getMemsetValue - Vectorized representation of the memset value
4086 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
4087 SelectionDAG &DAG) {
4088 MVT::ValueType CurVT = VT;
4089 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4090 uint64_t Val = C->getValue() & 255;
4092 while (CurVT != MVT::i8) {
4093 Val = (Val << Shift) | Val;
4095 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4097 return DAG.getConstant(Val, VT);
4099 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4101 while (CurVT != MVT::i8) {
4103 DAG.getNode(ISD::OR, VT,
4104 DAG.getNode(ISD::SHL, VT, Value,
4105 DAG.getConstant(Shift, MVT::i8)), Value);
4107 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4114 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4115 /// used when a memcpy is turned into a memset when the source is a constant
4117 static SDOperand getMemsetStringVal(MVT::ValueType VT,
4118 SelectionDAG &DAG, TargetLowering &TLI,
4119 std::string &Str, unsigned Offset) {
4121 unsigned MSB = MVT::getSizeInBits(VT) / 8;
4122 if (TLI.isLittleEndian())
4123 Offset = Offset + MSB - 1;
4124 for (unsigned i = 0; i != MSB; ++i) {
4125 Val = (Val << 8) | (unsigned char)Str[Offset];
4126 Offset += TLI.isLittleEndian() ? -1 : 1;
4128 return DAG.getConstant(Val, VT);
4131 /// getMemBasePlusOffset - Returns base and offset node for the
4132 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4133 SelectionDAG &DAG, TargetLowering &TLI) {
4134 MVT::ValueType VT = Base.getValueType();
4135 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4138 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
4139 /// to replace the memset / memcpy is below the threshold. It also returns the
4140 /// types of the sequence of memory ops to perform memset / memcpy.
4141 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4142 unsigned Limit, uint64_t Size,
4143 unsigned Align, TargetLowering &TLI) {
4146 if (TLI.allowsUnalignedMemoryAccesses()) {
4149 switch (Align & 7) {
4165 MVT::ValueType LVT = MVT::i64;
4166 while (!TLI.isTypeLegal(LVT))
4167 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4168 assert(MVT::isInteger(LVT));
4173 unsigned NumMemOps = 0;
4175 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4176 while (VTSize > Size) {
4177 VT = (MVT::ValueType)((unsigned)VT - 1);
4180 assert(MVT::isInteger(VT));
4182 if (++NumMemOps > Limit)
4184 MemOps.push_back(VT);
4191 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
4192 SDOperand Op1 = getValue(I.getOperand(1));
4193 SDOperand Op2 = getValue(I.getOperand(2));
4194 SDOperand Op3 = getValue(I.getOperand(3));
4195 SDOperand Op4 = getValue(I.getOperand(4));
4196 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4197 if (Align == 0) Align = 1;
4199 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4200 std::vector<MVT::ValueType> MemOps;
4202 // Expand memset / memcpy to a series of load / store ops
4203 // if the size operand falls below a certain threshold.
4204 SmallVector<SDOperand, 8> OutChains;
4206 default: break; // Do nothing for now.
4208 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4209 Size->getValue(), Align, TLI)) {
4210 unsigned NumMemOps = MemOps.size();
4211 unsigned Offset = 0;
4212 for (unsigned i = 0; i < NumMemOps; i++) {
4213 MVT::ValueType VT = MemOps[i];
4214 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4215 SDOperand Value = getMemsetValue(Op2, VT, DAG);
4216 SDOperand Store = DAG.getStore(getRoot(), Value,
4217 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
4218 I.getOperand(1), Offset);
4219 OutChains.push_back(Store);
4226 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4227 Size->getValue(), Align, TLI)) {
4228 unsigned NumMemOps = MemOps.size();
4229 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
4230 GlobalAddressSDNode *G = NULL;
4232 bool CopyFromStr = false;
4234 if (Op2.getOpcode() == ISD::GlobalAddress)
4235 G = cast<GlobalAddressSDNode>(Op2);
4236 else if (Op2.getOpcode() == ISD::ADD &&
4237 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4238 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4239 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
4240 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
4243 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
4244 if (GV && GV->isConstant()) {
4245 Str = GV->getStringValue(false);
4253 for (unsigned i = 0; i < NumMemOps; i++) {
4254 MVT::ValueType VT = MemOps[i];
4255 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4256 SDOperand Value, Chain, Store;
4259 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4262 DAG.getStore(Chain, Value,
4263 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4264 I.getOperand(1), DstOff);
4266 Value = DAG.getLoad(VT, getRoot(),
4267 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
4268 I.getOperand(2), SrcOff);
4269 Chain = Value.getValue(1);
4271 DAG.getStore(Chain, Value,
4272 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4273 I.getOperand(1), DstOff);
4275 OutChains.push_back(Store);
4284 if (!OutChains.empty()) {
4285 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4286 &OutChains[0], OutChains.size()));
4291 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
4294 //===----------------------------------------------------------------------===//
4295 // SelectionDAGISel code
4296 //===----------------------------------------------------------------------===//
4298 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4299 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4302 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4303 AU.addRequired<AliasAnalysis>();
4304 AU.setPreservesAll();
4309 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4310 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4311 RegMap = MF.getSSARegMap();
4312 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4314 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4316 if (ExceptionHandling)
4317 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4318 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4319 // Mark landing pad.
4320 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4322 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4323 SelectBasicBlock(I, MF, FuncInfo);
4325 // Add function live-ins to entry block live-in set.
4326 BasicBlock *EntryBB = &Fn.getEntryBlock();
4327 BB = FuncInfo.MBBMap[EntryBB];
4328 if (!MF.livein_empty())
4329 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4330 E = MF.livein_end(); I != E; ++I)
4331 BB->addLiveIn(I->first);
4334 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4335 "Not all catch info was assigned to a landing pad!");
4341 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4343 SDOperand Op = getValue(V);
4344 assert((Op.getOpcode() != ISD::CopyFromReg ||
4345 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4346 "Copy from a reg to the same reg!");
4348 // If this type is not legal, we must make sure to not create an invalid
4350 MVT::ValueType SrcVT = Op.getValueType();
4351 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
4352 if (SrcVT == DestVT) {
4353 return DAG.getCopyToReg(getRoot(), Reg, Op);
4354 } else if (MVT::isVector(SrcVT)) {
4355 // Handle copies from generic vectors to registers.
4356 MVT::ValueType ElementVT, LegalElementVT;
4357 unsigned NE = TLI.getVectorTypeBreakdown(SrcVT,
4358 ElementVT, LegalElementVT);
4359 uint64_t SrcVL = MVT::getVectorNumElements(SrcVT);
4361 // Loop over all of the elements of the resultant vector,
4362 // EXTRACT_VECTOR_ELT'ing or EXTRACT_SUBVECTOR'ing them, converting them
4363 // to LegalElementVT, then copying them into output registers.
4364 SmallVector<SDOperand, 8> OutChains;
4365 SDOperand Root = getRoot();
4366 for (unsigned i = 0; i != NE; ++i) {
4367 SDOperand Elt = MVT::isVector(ElementVT) ?
4368 DAG.getNode(ISD::EXTRACT_SUBVECTOR, ElementVT,
4369 Op, DAG.getConstant(i * (SrcVL / NE), TLI.getPointerTy())) :
4370 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, ElementVT,
4371 Op, DAG.getConstant(i, TLI.getPointerTy()));
4372 if (ElementVT == LegalElementVT) {
4373 // Elements are legal.
4374 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4375 } else if (LegalElementVT > ElementVT) {
4376 // Elements are promoted.
4377 if (MVT::isFloatingPoint(LegalElementVT))
4378 Elt = DAG.getNode(ISD::FP_EXTEND, LegalElementVT, Elt);
4380 Elt = DAG.getNode(ISD::ANY_EXTEND, LegalElementVT, Elt);
4381 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4383 // Elements are expanded.
4384 // The src value is expanded into multiple registers.
4385 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, LegalElementVT,
4386 Elt, DAG.getConstant(0, TLI.getPointerTy()));
4387 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, LegalElementVT,
4388 Elt, DAG.getConstant(1, TLI.getPointerTy()));
4389 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4390 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4393 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4394 &OutChains[0], OutChains.size());
4395 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
4396 // The src value is promoted to the register.
4397 if (MVT::isFloatingPoint(SrcVT))
4398 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4400 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
4401 return DAG.getCopyToReg(getRoot(), Reg, Op);
4403 DestVT = TLI.getTypeToExpandTo(SrcVT);
4404 unsigned NumVals = TLI.getNumRegisters(SrcVT);
4406 return DAG.getCopyToReg(getRoot(), Reg,
4407 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4408 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
4409 // The src value is expanded into multiple registers.
4410 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4411 Op, DAG.getConstant(0, TLI.getPointerTy()));
4412 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4413 Op, DAG.getConstant(1, TLI.getPointerTy()));
4414 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
4415 return DAG.getCopyToReg(Op, Reg+1, Hi);
4419 void SelectionDAGISel::
4420 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
4421 std::vector<SDOperand> &UnorderedChains) {
4422 // If this is the entry block, emit arguments.
4423 Function &F = *LLVMBB->getParent();
4424 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4425 SDOperand OldRoot = SDL.DAG.getRoot();
4426 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4429 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4431 if (!AI->use_empty()) {
4432 SDL.setValue(AI, Args[a]);
4434 // If this argument is live outside of the entry block, insert a copy from
4435 // whereever we got it to the vreg that other BB's will reference it as.
4436 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4437 if (VMI != FuncInfo.ValueMap.end()) {
4438 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
4439 UnorderedChains.push_back(Copy);
4443 // Finally, if the target has anything special to do, allow it to do so.
4444 // FIXME: this should insert code into the DAG!
4445 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4448 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4449 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4450 assert(!FLI.MBBMap[SrcBB]->isLandingPad() &&
4451 "Copying catch info out of a landing pad!");
4452 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4453 if (isFilterOrSelector(I)) {
4454 // Apply the catch info to DestBB.
4455 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4457 FLI.CatchInfoFound.insert(I);
4462 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4463 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4464 FunctionLoweringInfo &FuncInfo) {
4465 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
4467 std::vector<SDOperand> UnorderedChains;
4469 // Lower any arguments needed in this block if this is the entry block.
4470 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4471 LowerArguments(LLVMBB, SDL, UnorderedChains);
4473 BB = FuncInfo.MBBMap[LLVMBB];
4474 SDL.setCurrentBasicBlock(BB);
4476 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4478 if (ExceptionHandling && MMI && BB->isLandingPad()) {
4479 // Add a label to mark the beginning of the landing pad. Deletion of the
4480 // landing pad can thus be detected via the MachineModuleInfo.
4481 unsigned LabelID = MMI->addLandingPad(BB);
4482 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4483 DAG.getConstant(LabelID, MVT::i32)));
4485 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4486 // function and list of typeids logically belong to the invoke (or, if you
4487 // like, the basic block containing the invoke), and need to be associated
4488 // with it in the dwarf exception handling tables. Currently however the
4489 // information is provided by intrinsics (eh.filter and eh.selector) that
4490 // can be moved to unexpected places by the optimizers: if the unwind edge
4491 // is critical, then breaking it can result in the intrinsics being in the
4492 // successor of the landing pad, not the landing pad itself. This results
4493 // in exceptions not being caught because no typeids are associated with
4494 // the invoke. This may not be the only way things can go wrong, but it
4495 // is the only way we try to work around for the moment.
4496 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4498 if (Br && Br->isUnconditional()) { // Critical edge?
4499 BasicBlock::iterator I, E;
4500 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4501 if (isFilterOrSelector(I))
4505 // No catch info found - try to extract some from the successor.
4506 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
4510 // Lower all of the non-terminator instructions.
4511 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4515 // Ensure that all instructions which are used outside of their defining
4516 // blocks are available as virtual registers. Invoke is handled elsewhere.
4517 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4518 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
4519 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4520 if (VMI != FuncInfo.ValueMap.end())
4521 UnorderedChains.push_back(
4522 SDL.CopyValueToVirtualRegister(I, VMI->second));
4525 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4526 // ensure constants are generated when needed. Remember the virtual registers
4527 // that need to be added to the Machine PHI nodes as input. We cannot just
4528 // directly add them, because expansion might result in multiple MBB's for one
4529 // BB. As such, the start of the BB might correspond to a different MBB than
4532 TerminatorInst *TI = LLVMBB->getTerminator();
4534 // Emit constants only once even if used by multiple PHI nodes.
4535 std::map<Constant*, unsigned> ConstantsOut;
4537 // Vector bool would be better, but vector<bool> is really slow.
4538 std::vector<unsigned char> SuccsHandled;
4539 if (TI->getNumSuccessors())
4540 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4542 // Check successor nodes PHI nodes that expect a constant to be available from
4544 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4545 BasicBlock *SuccBB = TI->getSuccessor(succ);
4546 if (!isa<PHINode>(SuccBB->begin())) continue;
4547 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4549 // If this terminator has multiple identical successors (common for
4550 // switches), only handle each succ once.
4551 unsigned SuccMBBNo = SuccMBB->getNumber();
4552 if (SuccsHandled[SuccMBBNo]) continue;
4553 SuccsHandled[SuccMBBNo] = true;
4555 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4558 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4559 // nodes and Machine PHI nodes, but the incoming operands have not been
4561 for (BasicBlock::iterator I = SuccBB->begin();
4562 (PN = dyn_cast<PHINode>(I)); ++I) {
4563 // Ignore dead phi's.
4564 if (PN->use_empty()) continue;
4567 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4569 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4570 unsigned &RegOut = ConstantsOut[C];
4572 RegOut = FuncInfo.CreateRegForValue(C);
4573 UnorderedChains.push_back(
4574 SDL.CopyValueToVirtualRegister(C, RegOut));
4578 Reg = FuncInfo.ValueMap[PHIOp];
4580 assert(isa<AllocaInst>(PHIOp) &&
4581 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4582 "Didn't codegen value into a register!??");
4583 Reg = FuncInfo.CreateRegForValue(PHIOp);
4584 UnorderedChains.push_back(
4585 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4589 // Remember that this register needs to added to the machine PHI node as
4590 // the input for this MBB.
4591 MVT::ValueType VT = TLI.getValueType(PN->getType());
4592 unsigned NumRegisters = TLI.getNumRegisters(VT);
4593 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4594 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4597 ConstantsOut.clear();
4599 // Turn all of the unordered chains into one factored node.
4600 if (!UnorderedChains.empty()) {
4601 SDOperand Root = SDL.getRoot();
4602 if (Root.getOpcode() != ISD::EntryToken) {
4603 unsigned i = 0, e = UnorderedChains.size();
4604 for (; i != e; ++i) {
4605 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4606 if (UnorderedChains[i].Val->getOperand(0) == Root)
4607 break; // Don't add the root if we already indirectly depend on it.
4611 UnorderedChains.push_back(Root);
4613 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4614 &UnorderedChains[0], UnorderedChains.size()));
4617 // Lower the terminator after the copies are emitted.
4618 SDL.visit(*LLVMBB->getTerminator());
4620 // Copy over any CaseBlock records that may now exist due to SwitchInst
4621 // lowering, as well as any jump table information.
4622 SwitchCases.clear();
4623 SwitchCases = SDL.SwitchCases;
4625 JTCases = SDL.JTCases;
4626 BitTestCases.clear();
4627 BitTestCases = SDL.BitTestCases;
4629 // Make sure the root of the DAG is up-to-date.
4630 DAG.setRoot(SDL.getRoot());
4633 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4634 // Get alias analysis for load/store combining.
4635 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4637 // Run the DAG combiner in pre-legalize mode.
4638 DAG.Combine(false, AA);
4640 DOUT << "Lowered selection DAG:\n";
4643 // Second step, hack on the DAG until it only uses operations and types that
4644 // the target supports.
4647 DOUT << "Legalized selection DAG:\n";
4650 // Run the DAG combiner in post-legalize mode.
4651 DAG.Combine(true, AA);
4653 if (ViewISelDAGs) DAG.viewGraph();
4655 // Third, instruction select all of the operations to machine code, adding the
4656 // code to the MachineBasicBlock.
4657 InstructionSelectBasicBlock(DAG);
4659 DOUT << "Selected machine code:\n";
4663 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4664 FunctionLoweringInfo &FuncInfo) {
4665 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4667 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4670 // First step, lower LLVM code to some DAG. This DAG may use operations and
4671 // types that are not supported by the target.
4672 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4674 // Second step, emit the lowered DAG as machine code.
4675 CodeGenAndEmitDAG(DAG);
4678 DOUT << "Total amount of phi nodes to update: "
4679 << PHINodesToUpdate.size() << "\n";
4680 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4681 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4682 << ", " << PHINodesToUpdate[i].second << ")\n";);
4684 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4685 // PHI nodes in successors.
4686 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4687 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4688 MachineInstr *PHI = PHINodesToUpdate[i].first;
4689 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4690 "This is not a machine PHI node that we are updating!");
4691 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4692 PHI->addMachineBasicBlockOperand(BB);
4697 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4698 // Lower header first, if it wasn't already lowered
4699 if (!BitTestCases[i].Emitted) {
4700 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4702 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4703 // Set the current basic block to the mbb we wish to insert the code into
4704 BB = BitTestCases[i].Parent;
4705 HSDL.setCurrentBasicBlock(BB);
4707 HSDL.visitBitTestHeader(BitTestCases[i]);
4708 HSDAG.setRoot(HSDL.getRoot());
4709 CodeGenAndEmitDAG(HSDAG);
4712 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4713 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4715 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4716 // Set the current basic block to the mbb we wish to insert the code into
4717 BB = BitTestCases[i].Cases[j].ThisBB;
4718 BSDL.setCurrentBasicBlock(BB);
4721 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4722 BitTestCases[i].Reg,
4723 BitTestCases[i].Cases[j]);
4725 BSDL.visitBitTestCase(BitTestCases[i].Default,
4726 BitTestCases[i].Reg,
4727 BitTestCases[i].Cases[j]);
4730 BSDAG.setRoot(BSDL.getRoot());
4731 CodeGenAndEmitDAG(BSDAG);
4735 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4736 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4737 MachineBasicBlock *PHIBB = PHI->getParent();
4738 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4739 "This is not a machine PHI node that we are updating!");
4740 // This is "default" BB. We have two jumps to it. From "header" BB and
4741 // from last "case" BB.
4742 if (PHIBB == BitTestCases[i].Default) {
4743 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4744 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
4745 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4746 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4748 // One of "cases" BB.
4749 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4750 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4751 if (cBB->succ_end() !=
4752 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4753 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4754 PHI->addMachineBasicBlockOperand(cBB);
4760 // If the JumpTable record is filled in, then we need to emit a jump table.
4761 // Updating the PHI nodes is tricky in this case, since we need to determine
4762 // whether the PHI is a successor of the range check MBB or the jump table MBB
4763 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4764 // Lower header first, if it wasn't already lowered
4765 if (!JTCases[i].first.Emitted) {
4766 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4768 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4769 // Set the current basic block to the mbb we wish to insert the code into
4770 BB = JTCases[i].first.HeaderBB;
4771 HSDL.setCurrentBasicBlock(BB);
4773 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4774 HSDAG.setRoot(HSDL.getRoot());
4775 CodeGenAndEmitDAG(HSDAG);
4778 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4780 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
4781 // Set the current basic block to the mbb we wish to insert the code into
4782 BB = JTCases[i].second.MBB;
4783 JSDL.setCurrentBasicBlock(BB);
4785 JSDL.visitJumpTable(JTCases[i].second);
4786 JSDAG.setRoot(JSDL.getRoot());
4787 CodeGenAndEmitDAG(JSDAG);
4790 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4791 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4792 MachineBasicBlock *PHIBB = PHI->getParent();
4793 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4794 "This is not a machine PHI node that we are updating!");
4795 // "default" BB. We can go there only from header BB.
4796 if (PHIBB == JTCases[i].second.Default) {
4797 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4798 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
4800 // JT BB. Just iterate over successors here
4801 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4802 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4803 PHI->addMachineBasicBlockOperand(BB);
4808 // If the switch block involved a branch to one of the actual successors, we
4809 // need to update PHI nodes in that block.
4810 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4811 MachineInstr *PHI = PHINodesToUpdate[i].first;
4812 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4813 "This is not a machine PHI node that we are updating!");
4814 if (BB->isSuccessor(PHI->getParent())) {
4815 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4816 PHI->addMachineBasicBlockOperand(BB);
4820 // If we generated any switch lowering information, build and codegen any
4821 // additional DAGs necessary.
4822 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4823 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4825 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4827 // Set the current basic block to the mbb we wish to insert the code into
4828 BB = SwitchCases[i].ThisBB;
4829 SDL.setCurrentBasicBlock(BB);
4832 SDL.visitSwitchCase(SwitchCases[i]);
4833 SDAG.setRoot(SDL.getRoot());
4834 CodeGenAndEmitDAG(SDAG);
4836 // Handle any PHI nodes in successors of this chunk, as if we were coming
4837 // from the original BB before switch expansion. Note that PHI nodes can
4838 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4839 // handle them the right number of times.
4840 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4841 for (MachineBasicBlock::iterator Phi = BB->begin();
4842 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4843 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4844 for (unsigned pn = 0; ; ++pn) {
4845 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4846 if (PHINodesToUpdate[pn].first == Phi) {
4847 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4848 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4854 // Don't process RHS if same block as LHS.
4855 if (BB == SwitchCases[i].FalseBB)
4856 SwitchCases[i].FalseBB = 0;
4858 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4859 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4860 SwitchCases[i].FalseBB = 0;
4862 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4867 //===----------------------------------------------------------------------===//
4868 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4869 /// target node in the graph.
4870 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4871 if (ViewSchedDAGs) DAG.viewGraph();
4873 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4877 RegisterScheduler::setDefault(Ctor);
4880 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4886 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4887 return new HazardRecognizer();
4890 //===----------------------------------------------------------------------===//
4891 // Helper functions used by the generated instruction selector.
4892 //===----------------------------------------------------------------------===//
4893 // Calls to these methods are generated by tblgen.
4895 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4896 /// the dag combiner simplified the 255, we still want to match. RHS is the
4897 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4898 /// specified in the .td file (e.g. 255).
4899 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4900 int64_t DesiredMaskS) {
4901 uint64_t ActualMask = RHS->getValue();
4902 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4904 // If the actual mask exactly matches, success!
4905 if (ActualMask == DesiredMask)
4908 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4909 if (ActualMask & ~DesiredMask)
4912 // Otherwise, the DAG Combiner may have proven that the value coming in is
4913 // either already zero or is not demanded. Check for known zero input bits.
4914 uint64_t NeededMask = DesiredMask & ~ActualMask;
4915 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
4918 // TODO: check to see if missing bits are just not demanded.
4920 // Otherwise, this pattern doesn't match.
4924 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4925 /// the dag combiner simplified the 255, we still want to match. RHS is the
4926 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4927 /// specified in the .td file (e.g. 255).
4928 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4929 int64_t DesiredMaskS) {
4930 uint64_t ActualMask = RHS->getValue();
4931 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4933 // If the actual mask exactly matches, success!
4934 if (ActualMask == DesiredMask)
4937 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4938 if (ActualMask & ~DesiredMask)
4941 // Otherwise, the DAG Combiner may have proven that the value coming in is
4942 // either already zero or is not demanded. Check for known zero input bits.
4943 uint64_t NeededMask = DesiredMask & ~ActualMask;
4945 uint64_t KnownZero, KnownOne;
4946 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4948 // If all the missing bits in the or are already known to be set, match!
4949 if ((NeededMask & KnownOne) == NeededMask)
4952 // TODO: check to see if missing bits are just not demanded.
4954 // Otherwise, this pattern doesn't match.
4959 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4960 /// by tblgen. Others should not call it.
4961 void SelectionDAGISel::
4962 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4963 std::vector<SDOperand> InOps;
4964 std::swap(InOps, Ops);
4966 Ops.push_back(InOps[0]); // input chain.
4967 Ops.push_back(InOps[1]); // input asm string.
4969 unsigned i = 2, e = InOps.size();
4970 if (InOps[e-1].getValueType() == MVT::Flag)
4971 --e; // Don't process a flag operand if it is here.
4974 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4975 if ((Flags & 7) != 4 /*MEM*/) {
4976 // Just skip over this operand, copying the operands verbatim.
4977 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4978 i += (Flags >> 3) + 1;
4980 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4981 // Otherwise, this is a memory operand. Ask the target to select it.
4982 std::vector<SDOperand> SelOps;
4983 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4984 cerr << "Could not match memory address. Inline asm failure!\n";
4988 // Add this to the output node.
4989 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4990 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4992 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4997 // Add the flag input back if present.
4998 if (e != InOps.size())
4999 Ops.push_back(InOps.back());
5002 char SelectionDAGISel::ID = 0;