1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Collector.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SchedulerRegistry.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetFrameInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Compiler.h"
53 ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
56 ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
59 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
60 cl::desc("Pop up a window to show SUnit dags after they are processed"));
62 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
65 //===---------------------------------------------------------------------===//
67 /// RegisterScheduler class - Track the registration of instruction schedulers.
69 //===---------------------------------------------------------------------===//
70 MachinePassRegistry RegisterScheduler::Registry;
72 //===---------------------------------------------------------------------===//
74 /// ISHeuristic command line option for instruction schedulers.
76 //===---------------------------------------------------------------------===//
78 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
80 ISHeuristic("pre-RA-sched",
81 cl::init(&createDefaultScheduler),
82 cl::desc("Instruction schedulers available (before register"
85 static RegisterScheduler
86 defaultListDAGScheduler("default", " Best scheduler for the target",
87 createDefaultScheduler);
90 namespace { struct SDISelAsmOperandInfo; }
93 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
94 /// MVT::ValueTypes that represent all the individual underlying
95 /// non-aggregate types that comprise it.
96 static void ComputeValueVTs(const TargetLowering &TLI,
98 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
99 // Given a struct type, recursively traverse the elements.
100 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
101 for (StructType::element_iterator EI = STy->element_begin(),
102 EB = STy->element_end();
104 ComputeValueVTs(TLI, *EI, ValueVTs);
107 // Given an array type, recursively traverse the elements.
108 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
109 const Type *EltTy = ATy->getElementType();
110 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
111 ComputeValueVTs(TLI, EltTy, ValueVTs);
114 // Base case: we can get an MVT::ValueType for this LLVM IR type.
115 MVT::ValueType VT = TLI.getValueType(Ty);
116 ValueVTs.push_back(VT);
119 /// RegsForValue - This struct represents the physical registers that a
120 /// particular value is assigned and the type information about the value.
121 /// This is needed because values can be promoted into larger registers and
122 /// expanded into multiple smaller registers than the value.
123 struct VISIBILITY_HIDDEN RegsForValue {
124 /// TLI - The TargetLowering object.
125 const TargetLowering *TLI;
127 /// Regs - This list holds the register (for legal and promoted values)
128 /// or register set (for expanded values) that the value should be assigned
130 std::vector<unsigned> Regs;
132 /// RegVTs - The value types of the registers. This is the same size
133 /// as ValueVTs; every register contributing to a given value must
134 /// have the same type. When Regs contains all virtual registers, the
135 /// contents of RegVTs is redundant with TLI's getRegisterType member
136 /// function, however when Regs contains physical registers, it is
137 /// necessary to have a separate record of the types.
139 SmallVector<MVT::ValueType, 4> RegVTs;
141 /// ValueVTs - The value types of the values, which may be promoted
142 /// or synthesized from one or more registers.
143 SmallVector<MVT::ValueType, 4> ValueVTs;
145 RegsForValue() : TLI(0) {}
147 RegsForValue(const TargetLowering &tli,
148 unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
149 : TLI(&tli), Regs(1, Reg), RegVTs(1, regvt), ValueVTs(1, valuevt) {}
150 RegsForValue(const TargetLowering &tli,
151 const std::vector<unsigned> ®s,
152 MVT::ValueType regvt, MVT::ValueType valuevt)
153 : TLI(&tli), Regs(regs), RegVTs(1, regvt), ValueVTs(1, valuevt) {}
154 RegsForValue(const TargetLowering &tli,
155 const std::vector<unsigned> ®s,
156 const SmallVector<MVT::ValueType, 4> ®vts,
157 const SmallVector<MVT::ValueType, 4> &valuevts)
158 : TLI(&tli), Regs(regs), RegVTs(regvts), ValueVTs(valuevts) {}
159 RegsForValue(const TargetLowering &tli,
160 unsigned Reg, const Type *Ty) : TLI(&tli) {
161 ComputeValueVTs(tli, Ty, ValueVTs);
163 for (unsigned Value = 0; Value != ValueVTs.size(); ++Value) {
164 MVT::ValueType ValueVT = ValueVTs[Value];
165 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
166 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
167 for (unsigned i = 0; i != NumRegs; ++i)
168 Regs.push_back(Reg + i);
169 RegVTs.push_back(RegisterVT);
174 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
175 /// this value and returns the result as a ValueVTs value. This uses
176 /// Chain/Flag as the input and updates them for the output Chain/Flag.
177 /// If the Flag pointer is NULL, no flag is used.
178 SDOperand getCopyFromRegs(SelectionDAG &DAG,
179 SDOperand &Chain, SDOperand *Flag) const;
181 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
182 /// specified value into the registers specified by this object. This uses
183 /// Chain/Flag as the input and updates them for the output Chain/Flag.
184 /// If the Flag pointer is NULL, no flag is used.
185 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
186 SDOperand &Chain, SDOperand *Flag) const;
188 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
189 /// operand list. This adds the code marker and includes the number of
190 /// values added into it.
191 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
192 std::vector<SDOperand> &Ops) const;
197 //===--------------------------------------------------------------------===//
198 /// createDefaultScheduler - This creates an instruction scheduler appropriate
200 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
202 MachineBasicBlock *BB) {
203 TargetLowering &TLI = IS->getTargetLowering();
205 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
206 return createTDListDAGScheduler(IS, DAG, BB);
208 assert(TLI.getSchedulingPreference() ==
209 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
210 return createBURRListDAGScheduler(IS, DAG, BB);
215 //===--------------------------------------------------------------------===//
216 /// FunctionLoweringInfo - This contains information that is global to a
217 /// function that is used when lowering a region of the function.
218 class FunctionLoweringInfo {
223 MachineRegisterInfo &RegInfo;
225 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
227 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
228 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
230 /// ValueMap - Since we emit code for the function a basic block at a time,
231 /// we must remember which virtual registers hold the values for
232 /// cross-basic-block values.
233 DenseMap<const Value*, unsigned> ValueMap;
235 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
236 /// the entry block. This allows the allocas to be efficiently referenced
237 /// anywhere in the function.
238 std::map<const AllocaInst*, int> StaticAllocaMap;
241 SmallSet<Instruction*, 8> CatchInfoLost;
242 SmallSet<Instruction*, 8> CatchInfoFound;
245 unsigned MakeReg(MVT::ValueType VT) {
246 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
249 /// isExportedInst - Return true if the specified value is an instruction
250 /// exported from its block.
251 bool isExportedInst(const Value *V) {
252 return ValueMap.count(V);
255 unsigned CreateRegForValue(const Value *V);
257 unsigned InitializeRegForValue(const Value *V) {
258 unsigned &R = ValueMap[V];
259 assert(R == 0 && "Already initialized this value register!");
260 return R = CreateRegForValue(V);
265 /// isSelector - Return true if this instruction is a call to the
266 /// eh.selector intrinsic.
267 static bool isSelector(Instruction *I) {
268 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
269 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
270 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
274 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
275 /// PHI nodes or outside of the basic block that defines it, or used by a
276 /// switch or atomic instruction, which may expand to multiple basic blocks.
277 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
278 if (isa<PHINode>(I)) return true;
279 BasicBlock *BB = I->getParent();
280 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
281 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
282 // FIXME: Remove switchinst special case.
283 isa<SwitchInst>(*UI))
288 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
289 /// entry block, return true. This includes arguments used by switches, since
290 /// the switch may expand into multiple basic blocks.
291 static bool isOnlyUsedInEntryBlock(Argument *A) {
292 BasicBlock *Entry = A->getParent()->begin();
293 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
294 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
295 return false; // Use not in entry block.
299 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
300 Function &fn, MachineFunction &mf)
301 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
303 // Create a vreg for each argument register that is not dead and is used
304 // outside of the entry block for the function.
305 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
307 if (!isOnlyUsedInEntryBlock(AI))
308 InitializeRegForValue(AI);
310 // Initialize the mapping of values to registers. This is only set up for
311 // instruction values that are used outside of the block that defines
313 Function::iterator BB = Fn.begin(), EB = Fn.end();
314 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
315 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
316 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
317 const Type *Ty = AI->getAllocatedType();
318 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
320 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
323 TySize *= CUI->getZExtValue(); // Get total allocated size.
324 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
325 StaticAllocaMap[AI] =
326 MF.getFrameInfo()->CreateStackObject(TySize, Align);
329 for (; BB != EB; ++BB)
330 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
331 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
332 if (!isa<AllocaInst>(I) ||
333 !StaticAllocaMap.count(cast<AllocaInst>(I)))
334 InitializeRegForValue(I);
336 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
337 // also creates the initial PHI MachineInstrs, though none of the input
338 // operands are populated.
339 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
340 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
342 MF.getBasicBlockList().push_back(MBB);
344 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
347 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
348 if (PN->use_empty()) continue;
350 MVT::ValueType VT = TLI.getValueType(PN->getType());
351 unsigned NumRegisters = TLI.getNumRegisters(VT);
352 unsigned PHIReg = ValueMap[PN];
353 assert(PHIReg && "PHI node does not have an assigned virtual register!");
354 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
355 for (unsigned i = 0; i != NumRegisters; ++i)
356 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
361 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
362 /// the correctly promoted or expanded types. Assign these registers
363 /// consecutive vreg numbers and return the first assigned number.
364 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
365 const Type *Ty = V->getType();
366 SmallVector<MVT::ValueType, 4> ValueVTs;
367 ComputeValueVTs(TLI, Ty, ValueVTs);
369 unsigned FirstReg = 0;
370 for (unsigned Value = 0; Value != ValueVTs.size(); ++Value) {
371 MVT::ValueType ValueVT = ValueVTs[Value];
372 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
373 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
375 for (unsigned i = 0; i != NumRegs; ++i) {
376 unsigned R = MakeReg(RegisterVT);
377 if (!FirstReg) FirstReg = R;
383 //===----------------------------------------------------------------------===//
384 /// SelectionDAGLowering - This is the common target-independent lowering
385 /// implementation that is parameterized by a TargetLowering object.
386 /// Also, targets can overload any lowering method.
389 class SelectionDAGLowering {
390 MachineBasicBlock *CurMBB;
392 DenseMap<const Value*, SDOperand> NodeMap;
394 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
395 /// them up and then emit token factor nodes when possible. This allows us to
396 /// get simple disambiguation between loads without worrying about alias
398 std::vector<SDOperand> PendingLoads;
400 /// PendingExports - CopyToReg nodes that copy values to virtual registers
401 /// for export to other blocks need to be emitted before any terminator
402 /// instruction, but they have no other ordering requirements. We bunch them
403 /// up and the emit a single tokenfactor for them just before terminator
405 std::vector<SDOperand> PendingExports;
407 /// Case - A struct to record the Value for a switch case, and the
408 /// case's target basic block.
412 MachineBasicBlock* BB;
414 Case() : Low(0), High(0), BB(0) { }
415 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
416 Low(low), High(high), BB(bb) { }
417 uint64_t size() const {
418 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
419 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
420 return (rHigh - rLow + 1ULL);
426 MachineBasicBlock* BB;
429 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
430 Mask(mask), BB(bb), Bits(bits) { }
433 typedef std::vector<Case> CaseVector;
434 typedef std::vector<CaseBits> CaseBitsVector;
435 typedef CaseVector::iterator CaseItr;
436 typedef std::pair<CaseItr, CaseItr> CaseRange;
438 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
439 /// of conditional branches.
441 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
442 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
444 /// CaseBB - The MBB in which to emit the compare and branch
445 MachineBasicBlock *CaseBB;
446 /// LT, GE - If nonzero, we know the current case value must be less-than or
447 /// greater-than-or-equal-to these Constants.
450 /// Range - A pair of iterators representing the range of case values to be
451 /// processed at this point in the binary search tree.
455 typedef std::vector<CaseRec> CaseRecVector;
457 /// The comparison function for sorting the switch case values in the vector.
458 /// WARNING: Case ranges should be disjoint!
460 bool operator () (const Case& C1, const Case& C2) {
461 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
462 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
463 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
464 return CI1->getValue().slt(CI2->getValue());
469 bool operator () (const CaseBits& C1, const CaseBits& C2) {
470 return C1.Bits > C2.Bits;
474 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
477 // TLI - This is information that describes the available target features we
478 // need for lowering. This indicates when operations are unavailable,
479 // implemented with a libcall, etc.
482 const TargetData *TD;
485 /// SwitchCases - Vector of CaseBlock structures used to communicate
486 /// SwitchInst code generation information.
487 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
488 /// JTCases - Vector of JumpTable structures used to communicate
489 /// SwitchInst code generation information.
490 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
491 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
493 /// FuncInfo - Information about the function as a whole.
495 FunctionLoweringInfo &FuncInfo;
497 /// GCI - Garbage collection metadata for the function.
498 CollectorMetadata *GCI;
500 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
502 FunctionLoweringInfo &funcinfo,
503 CollectorMetadata *gci)
504 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
505 FuncInfo(funcinfo), GCI(gci) {
508 /// getRoot - Return the current virtual root of the Selection DAG,
509 /// flushing any PendingLoad items. This must be done before emitting
510 /// a store or any other node that may need to be ordered after any
511 /// prior load instructions.
513 SDOperand getRoot() {
514 if (PendingLoads.empty())
515 return DAG.getRoot();
517 if (PendingLoads.size() == 1) {
518 SDOperand Root = PendingLoads[0];
520 PendingLoads.clear();
524 // Otherwise, we have to make a token factor node.
525 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
526 &PendingLoads[0], PendingLoads.size());
527 PendingLoads.clear();
532 /// getControlRoot - Similar to getRoot, but instead of flushing all the
533 /// PendingLoad items, flush all the PendingExports items. It is necessary
534 /// to do this before emitting a terminator instruction.
536 SDOperand getControlRoot() {
537 SDOperand Root = DAG.getRoot();
539 if (PendingExports.empty())
542 // Turn all of the CopyToReg chains into one factored node.
543 if (Root.getOpcode() != ISD::EntryToken) {
544 unsigned i = 0, e = PendingExports.size();
545 for (; i != e; ++i) {
546 assert(PendingExports[i].Val->getNumOperands() > 1);
547 if (PendingExports[i].Val->getOperand(0) == Root)
548 break; // Don't add the root if we already indirectly depend on it.
552 PendingExports.push_back(Root);
555 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
557 PendingExports.size());
558 PendingExports.clear();
563 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
565 void visit(Instruction &I) { visit(I.getOpcode(), I); }
567 void visit(unsigned Opcode, User &I) {
568 // Note: this doesn't use InstVisitor, because it has to work with
569 // ConstantExpr's in addition to instructions.
571 default: assert(0 && "Unknown instruction type encountered!");
573 // Build the switch statement using the Instruction.def file.
574 #define HANDLE_INST(NUM, OPCODE, CLASS) \
575 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
576 #include "llvm/Instruction.def"
580 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
582 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
583 const Value *SV, SDOperand Root,
584 bool isVolatile, unsigned Alignment);
586 SDOperand getValue(const Value *V);
588 void setValue(const Value *V, SDOperand NewN) {
589 SDOperand &N = NodeMap[V];
590 assert(N.Val == 0 && "Already set a value for this node!");
594 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
595 std::set<unsigned> &OutputRegs,
596 std::set<unsigned> &InputRegs);
598 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
599 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
601 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
602 void ExportFromCurrentBlock(Value *V);
603 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
604 MachineBasicBlock *LandingPad = NULL);
606 // Terminator instructions.
607 void visitRet(ReturnInst &I);
608 void visitBr(BranchInst &I);
609 void visitSwitch(SwitchInst &I);
610 void visitUnreachable(UnreachableInst &I) { /* noop */ }
612 // Helpers for visitSwitch
613 bool handleSmallSwitchRange(CaseRec& CR,
614 CaseRecVector& WorkList,
616 MachineBasicBlock* Default);
617 bool handleJTSwitchCase(CaseRec& CR,
618 CaseRecVector& WorkList,
620 MachineBasicBlock* Default);
621 bool handleBTSplitSwitchCase(CaseRec& CR,
622 CaseRecVector& WorkList,
624 MachineBasicBlock* Default);
625 bool handleBitTestsSwitchCase(CaseRec& CR,
626 CaseRecVector& WorkList,
628 MachineBasicBlock* Default);
629 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
630 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
631 void visitBitTestCase(MachineBasicBlock* NextMBB,
633 SelectionDAGISel::BitTestCase &B);
634 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
635 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
636 SelectionDAGISel::JumpTableHeader &JTH);
638 // These all get lowered before this pass.
639 void visitInvoke(InvokeInst &I);
640 void visitUnwind(UnwindInst &I);
642 void visitBinary(User &I, unsigned OpCode);
643 void visitShift(User &I, unsigned Opcode);
644 void visitAdd(User &I) {
645 if (I.getType()->isFPOrFPVector())
646 visitBinary(I, ISD::FADD);
648 visitBinary(I, ISD::ADD);
650 void visitSub(User &I);
651 void visitMul(User &I) {
652 if (I.getType()->isFPOrFPVector())
653 visitBinary(I, ISD::FMUL);
655 visitBinary(I, ISD::MUL);
657 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
658 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
659 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
660 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
661 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
662 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
663 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
664 void visitOr (User &I) { visitBinary(I, ISD::OR); }
665 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
666 void visitShl (User &I) { visitShift(I, ISD::SHL); }
667 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
668 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
669 void visitICmp(User &I);
670 void visitFCmp(User &I);
671 // Visit the conversion instructions
672 void visitTrunc(User &I);
673 void visitZExt(User &I);
674 void visitSExt(User &I);
675 void visitFPTrunc(User &I);
676 void visitFPExt(User &I);
677 void visitFPToUI(User &I);
678 void visitFPToSI(User &I);
679 void visitUIToFP(User &I);
680 void visitSIToFP(User &I);
681 void visitPtrToInt(User &I);
682 void visitIntToPtr(User &I);
683 void visitBitCast(User &I);
685 void visitExtractElement(User &I);
686 void visitInsertElement(User &I);
687 void visitShuffleVector(User &I);
689 void visitGetElementPtr(User &I);
690 void visitSelect(User &I);
692 void visitMalloc(MallocInst &I);
693 void visitFree(FreeInst &I);
694 void visitAlloca(AllocaInst &I);
695 void visitLoad(LoadInst &I);
696 void visitStore(StoreInst &I);
697 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
698 void visitCall(CallInst &I);
699 void visitInlineAsm(CallSite CS);
700 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
701 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
703 void visitVAStart(CallInst &I);
704 void visitVAArg(VAArgInst &I);
705 void visitVAEnd(CallInst &I);
706 void visitVACopy(CallInst &I);
708 void visitGetResult(GetResultInst &I);
710 void visitUserOp1(Instruction &I) {
711 assert(0 && "UserOp1 should not exist at instruction selection time!");
714 void visitUserOp2(Instruction &I) {
715 assert(0 && "UserOp2 should not exist at instruction selection time!");
719 } // end namespace llvm
722 /// getCopyFromParts - Create a value that contains the specified legal parts
723 /// combined into the value they represent. If the parts combine to a type
724 /// larger then ValueVT then AssertOp can be used to specify whether the extra
725 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
726 /// (ISD::AssertSext).
727 static SDOperand getCopyFromParts(SelectionDAG &DAG,
728 const SDOperand *Parts,
730 MVT::ValueType PartVT,
731 MVT::ValueType ValueVT,
732 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
733 assert(NumParts > 0 && "No parts to assemble!");
734 TargetLowering &TLI = DAG.getTargetLoweringInfo();
735 SDOperand Val = Parts[0];
738 // Assemble the value from multiple parts.
739 if (!MVT::isVector(ValueVT)) {
740 unsigned PartBits = MVT::getSizeInBits(PartVT);
741 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
743 // Assemble the power of 2 part.
744 unsigned RoundParts = NumParts & (NumParts - 1) ?
745 1 << Log2_32(NumParts) : NumParts;
746 unsigned RoundBits = PartBits * RoundParts;
747 MVT::ValueType RoundVT = RoundBits == ValueBits ?
748 ValueVT : MVT::getIntegerType(RoundBits);
751 if (RoundParts > 2) {
752 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
753 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
754 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
760 if (TLI.isBigEndian())
762 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
764 if (RoundParts < NumParts) {
765 // Assemble the trailing non-power-of-2 part.
766 unsigned OddParts = NumParts - RoundParts;
767 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
768 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
770 // Combine the round and odd parts.
772 if (TLI.isBigEndian())
774 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
775 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
776 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
777 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
778 TLI.getShiftAmountTy()));
779 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
780 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
783 // Handle a multi-element vector.
784 MVT::ValueType IntermediateVT, RegisterVT;
785 unsigned NumIntermediates;
787 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
790 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
791 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
792 assert(RegisterVT == Parts[0].getValueType() &&
793 "Part type doesn't match part!");
795 // Assemble the parts into intermediate operands.
796 SmallVector<SDOperand, 8> Ops(NumIntermediates);
797 if (NumIntermediates == NumParts) {
798 // If the register was not expanded, truncate or copy the value,
800 for (unsigned i = 0; i != NumParts; ++i)
801 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
802 PartVT, IntermediateVT);
803 } else if (NumParts > 0) {
804 // If the intermediate type was expanded, build the intermediate operands
806 assert(NumParts % NumIntermediates == 0 &&
807 "Must expand into a divisible number of parts!");
808 unsigned Factor = NumParts / NumIntermediates;
809 for (unsigned i = 0; i != NumIntermediates; ++i)
810 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
811 PartVT, IntermediateVT);
814 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
816 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
817 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
818 ValueVT, &Ops[0], NumIntermediates);
822 // There is now one part, held in Val. Correct it to match ValueVT.
823 PartVT = Val.getValueType();
825 if (PartVT == ValueVT)
828 if (MVT::isVector(PartVT)) {
829 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
830 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
833 if (MVT::isVector(ValueVT)) {
834 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
835 MVT::getVectorNumElements(ValueVT) == 1 &&
836 "Only trivial scalar-to-vector conversions should get here!");
837 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
840 if (MVT::isInteger(PartVT) &&
841 MVT::isInteger(ValueVT)) {
842 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
843 // For a truncate, see if we have any information to
844 // indicate whether the truncated bits will always be
845 // zero or sign-extension.
846 if (AssertOp != ISD::DELETED_NODE)
847 Val = DAG.getNode(AssertOp, PartVT, Val,
848 DAG.getValueType(ValueVT));
849 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
851 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
855 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
856 if (ValueVT < Val.getValueType())
857 // FP_ROUND's are always exact here.
858 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
859 DAG.getIntPtrConstant(1));
860 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
863 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
864 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
866 assert(0 && "Unknown mismatch!");
870 /// getCopyToParts - Create a series of nodes that contain the specified value
871 /// split into legal parts. If the parts contain more bits than Val, then, for
872 /// integers, ExtendKind can be used to specify how to generate the extra bits.
873 static void getCopyToParts(SelectionDAG &DAG,
877 MVT::ValueType PartVT,
878 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
879 TargetLowering &TLI = DAG.getTargetLoweringInfo();
880 MVT::ValueType PtrVT = TLI.getPointerTy();
881 MVT::ValueType ValueVT = Val.getValueType();
882 unsigned PartBits = MVT::getSizeInBits(PartVT);
883 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
888 if (!MVT::isVector(ValueVT)) {
889 if (PartVT == ValueVT) {
890 assert(NumParts == 1 && "No-op copy with multiple parts!");
895 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
896 // If the parts cover more bits than the value has, promote the value.
897 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
898 assert(NumParts == 1 && "Do not know what to promote to!");
899 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
900 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
901 ValueVT = MVT::getIntegerType(NumParts * PartBits);
902 Val = DAG.getNode(ExtendKind, ValueVT, Val);
904 assert(0 && "Unknown mismatch!");
906 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
907 // Different types of the same size.
908 assert(NumParts == 1 && PartVT != ValueVT);
909 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
910 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
911 // If the parts cover less bits than value has, truncate the value.
912 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
913 ValueVT = MVT::getIntegerType(NumParts * PartBits);
914 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
916 assert(0 && "Unknown mismatch!");
920 // The value may have changed - recompute ValueVT.
921 ValueVT = Val.getValueType();
922 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
923 "Failed to tile the value with PartVT!");
926 assert(PartVT == ValueVT && "Type conversion failed!");
931 // Expand the value into multiple parts.
932 if (NumParts & (NumParts - 1)) {
933 // The number of parts is not a power of 2. Split off and copy the tail.
934 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
935 "Do not know what to expand to!");
936 unsigned RoundParts = 1 << Log2_32(NumParts);
937 unsigned RoundBits = RoundParts * PartBits;
938 unsigned OddParts = NumParts - RoundParts;
939 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
940 DAG.getConstant(RoundBits,
941 TLI.getShiftAmountTy()));
942 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
943 if (TLI.isBigEndian())
944 // The odd parts were reversed by getCopyToParts - unreverse them.
945 std::reverse(Parts + RoundParts, Parts + NumParts);
946 NumParts = RoundParts;
947 ValueVT = MVT::getIntegerType(NumParts * PartBits);
948 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
951 // The number of parts is a power of 2. Repeatedly bisect the value using
953 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
954 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
956 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
957 for (unsigned i = 0; i < NumParts; i += StepSize) {
958 unsigned ThisBits = StepSize * PartBits / 2;
959 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
960 SDOperand &Part0 = Parts[i];
961 SDOperand &Part1 = Parts[i+StepSize/2];
963 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
964 DAG.getConstant(1, PtrVT));
965 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
966 DAG.getConstant(0, PtrVT));
968 if (ThisBits == PartBits && ThisVT != PartVT) {
969 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
970 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
975 if (TLI.isBigEndian())
976 std::reverse(Parts, Parts + NumParts);
983 if (PartVT != ValueVT) {
984 if (MVT::isVector(PartVT)) {
985 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
987 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
988 MVT::getVectorNumElements(ValueVT) == 1 &&
989 "Only trivial vector-to-scalar conversions should get here!");
990 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
991 DAG.getConstant(0, PtrVT));
999 // Handle a multi-element vector.
1000 MVT::ValueType IntermediateVT, RegisterVT;
1001 unsigned NumIntermediates;
1003 DAG.getTargetLoweringInfo()
1004 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1006 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1008 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1009 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1011 // Split the vector into intermediate operands.
1012 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1013 for (unsigned i = 0; i != NumIntermediates; ++i)
1014 if (MVT::isVector(IntermediateVT))
1015 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1016 IntermediateVT, Val,
1017 DAG.getConstant(i * (NumElements / NumIntermediates),
1020 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1021 IntermediateVT, Val,
1022 DAG.getConstant(i, PtrVT));
1024 // Split the intermediate operands into legal parts.
1025 if (NumParts == NumIntermediates) {
1026 // If the register was not expanded, promote or copy the value,
1028 for (unsigned i = 0; i != NumParts; ++i)
1029 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1030 } else if (NumParts > 0) {
1031 // If the intermediate type was expanded, split each the value into
1033 assert(NumParts % NumIntermediates == 0 &&
1034 "Must expand into a divisible number of parts!");
1035 unsigned Factor = NumParts / NumIntermediates;
1036 for (unsigned i = 0; i != NumIntermediates; ++i)
1037 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1042 SDOperand SelectionDAGLowering::getValue(const Value *V) {
1043 SDOperand &N = NodeMap[V];
1044 if (N.Val) return N;
1046 const Type *VTy = V->getType();
1047 MVT::ValueType VT = TLI.getValueType(VTy, true);
1048 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1049 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1050 visit(CE->getOpcode(), *CE);
1051 SDOperand N1 = NodeMap[V];
1052 assert(N1.Val && "visit didn't populate the ValueMap!");
1054 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
1055 return N = DAG.getGlobalAddress(GV, VT);
1056 } else if (isa<ConstantPointerNull>(C)) {
1057 return N = DAG.getConstant(0, TLI.getPointerTy());
1058 } else if (isa<UndefValue>(C)) {
1059 if (!isa<VectorType>(VTy))
1060 return N = DAG.getNode(ISD::UNDEF, VT);
1062 // Create a BUILD_VECTOR of undef nodes.
1063 const VectorType *PTy = cast<VectorType>(VTy);
1064 unsigned NumElements = PTy->getNumElements();
1065 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1067 SmallVector<SDOperand, 8> Ops;
1068 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
1070 // Create a VConstant node with generic Vector type.
1071 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
1072 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
1073 &Ops[0], Ops.size());
1074 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1075 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1076 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
1077 unsigned NumElements = PTy->getNumElements();
1078 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1080 // Now that we know the number and type of the elements, push a
1081 // Constant or ConstantFP node onto the ops list for each element of
1082 // the vector constant.
1083 SmallVector<SDOperand, 8> Ops;
1084 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1085 for (unsigned i = 0; i != NumElements; ++i)
1086 Ops.push_back(getValue(CP->getOperand(i)));
1088 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1090 if (MVT::isFloatingPoint(PVT))
1091 Op = DAG.getConstantFP(0, PVT);
1093 Op = DAG.getConstant(0, PVT);
1094 Ops.assign(NumElements, Op);
1097 // Create a BUILD_VECTOR node.
1098 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
1099 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
1102 // Canonicalize all constant ints to be unsigned.
1103 return N = DAG.getConstant(cast<ConstantInt>(C)->getValue(),VT);
1107 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1108 std::map<const AllocaInst*, int>::iterator SI =
1109 FuncInfo.StaticAllocaMap.find(AI);
1110 if (SI != FuncInfo.StaticAllocaMap.end())
1111 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1114 unsigned InReg = FuncInfo.ValueMap[V];
1115 assert(InReg && "Value not in map!");
1117 RegsForValue RFV(TLI, InReg, VTy);
1118 SDOperand Chain = DAG.getEntryNode();
1120 return RFV.getCopyFromRegs(DAG, Chain, NULL);
1124 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1125 if (I.getNumOperands() == 0) {
1126 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1129 SmallVector<SDOperand, 8> NewValues;
1130 NewValues.push_back(getControlRoot());
1131 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1132 SDOperand RetOp = getValue(I.getOperand(i));
1133 MVT::ValueType VT = RetOp.getValueType();
1135 // FIXME: C calling convention requires the return type to be promoted to
1136 // at least 32-bit. But this is not necessary for non-C calling conventions.
1137 if (MVT::isInteger(VT)) {
1138 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1139 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1143 unsigned NumParts = TLI.getNumRegisters(VT);
1144 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1145 SmallVector<SDOperand, 4> Parts(NumParts);
1146 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1148 const Function *F = I.getParent()->getParent();
1149 if (F->paramHasAttr(0, ParamAttr::SExt))
1150 ExtendKind = ISD::SIGN_EXTEND;
1151 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1152 ExtendKind = ISD::ZERO_EXTEND;
1154 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1156 for (unsigned i = 0; i < NumParts; ++i) {
1157 NewValues.push_back(Parts[i]);
1158 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1161 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1162 &NewValues[0], NewValues.size()));
1165 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1166 /// the current basic block, add it to ValueMap now so that we'll get a
1168 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1169 // No need to export constants.
1170 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1172 // Already exported?
1173 if (FuncInfo.isExportedInst(V)) return;
1175 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1176 CopyValueToVirtualRegister(V, Reg);
1179 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1180 const BasicBlock *FromBB) {
1181 // The operands of the setcc have to be in this block. We don't know
1182 // how to export them from some other block.
1183 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1184 // Can export from current BB.
1185 if (VI->getParent() == FromBB)
1188 // Is already exported, noop.
1189 return FuncInfo.isExportedInst(V);
1192 // If this is an argument, we can export it if the BB is the entry block or
1193 // if it is already exported.
1194 if (isa<Argument>(V)) {
1195 if (FromBB == &FromBB->getParent()->getEntryBlock())
1198 // Otherwise, can only export this if it is already exported.
1199 return FuncInfo.isExportedInst(V);
1202 // Otherwise, constants can always be exported.
1206 static bool InBlock(const Value *V, const BasicBlock *BB) {
1207 if (const Instruction *I = dyn_cast<Instruction>(V))
1208 return I->getParent() == BB;
1212 /// FindMergedConditions - If Cond is an expression like
1213 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1214 MachineBasicBlock *TBB,
1215 MachineBasicBlock *FBB,
1216 MachineBasicBlock *CurBB,
1218 // If this node is not part of the or/and tree, emit it as a branch.
1219 Instruction *BOp = dyn_cast<Instruction>(Cond);
1221 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1222 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1223 BOp->getParent() != CurBB->getBasicBlock() ||
1224 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1225 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1226 const BasicBlock *BB = CurBB->getBasicBlock();
1228 // If the leaf of the tree is a comparison, merge the condition into
1230 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1231 // The operands of the cmp have to be in this block. We don't know
1232 // how to export them from some other block. If this is the first block
1233 // of the sequence, no exporting is needed.
1235 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1236 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1237 BOp = cast<Instruction>(Cond);
1238 ISD::CondCode Condition;
1239 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1240 switch (IC->getPredicate()) {
1241 default: assert(0 && "Unknown icmp predicate opcode!");
1242 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1243 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1244 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1245 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1246 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1247 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1248 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1249 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1250 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1251 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1253 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1254 ISD::CondCode FPC, FOC;
1255 switch (FC->getPredicate()) {
1256 default: assert(0 && "Unknown fcmp predicate opcode!");
1257 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1258 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1259 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1260 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1261 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1262 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1263 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1264 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1265 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1266 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1267 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1268 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1269 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1270 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1271 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1272 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1274 if (FiniteOnlyFPMath())
1279 Condition = ISD::SETEQ; // silence warning.
1280 assert(0 && "Unknown compare instruction");
1283 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1284 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1285 SwitchCases.push_back(CB);
1289 // Create a CaseBlock record representing this branch.
1290 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1291 NULL, TBB, FBB, CurBB);
1292 SwitchCases.push_back(CB);
1297 // Create TmpBB after CurBB.
1298 MachineFunction::iterator BBI = CurBB;
1299 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1300 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1302 if (Opc == Instruction::Or) {
1303 // Codegen X | Y as:
1311 // Emit the LHS condition.
1312 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1314 // Emit the RHS condition into TmpBB.
1315 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1317 assert(Opc == Instruction::And && "Unknown merge op!");
1318 // Codegen X & Y as:
1325 // This requires creation of TmpBB after CurBB.
1327 // Emit the LHS condition.
1328 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1330 // Emit the RHS condition into TmpBB.
1331 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1335 /// If the set of cases should be emitted as a series of branches, return true.
1336 /// If we should emit this as a bunch of and/or'd together conditions, return
1339 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1340 if (Cases.size() != 2) return true;
1342 // If this is two comparisons of the same values or'd or and'd together, they
1343 // will get folded into a single comparison, so don't emit two blocks.
1344 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1345 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1346 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1347 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1354 void SelectionDAGLowering::visitBr(BranchInst &I) {
1355 // Update machine-CFG edges.
1356 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1358 // Figure out which block is immediately after the current one.
1359 MachineBasicBlock *NextBlock = 0;
1360 MachineFunction::iterator BBI = CurMBB;
1361 if (++BBI != CurMBB->getParent()->end())
1364 if (I.isUnconditional()) {
1365 // If this is not a fall-through branch, emit the branch.
1366 if (Succ0MBB != NextBlock)
1367 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1368 DAG.getBasicBlock(Succ0MBB)));
1370 // Update machine-CFG edges.
1371 CurMBB->addSuccessor(Succ0MBB);
1375 // If this condition is one of the special cases we handle, do special stuff
1377 Value *CondVal = I.getCondition();
1378 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1380 // If this is a series of conditions that are or'd or and'd together, emit
1381 // this as a sequence of branches instead of setcc's with and/or operations.
1382 // For example, instead of something like:
1395 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1396 if (BOp->hasOneUse() &&
1397 (BOp->getOpcode() == Instruction::And ||
1398 BOp->getOpcode() == Instruction::Or)) {
1399 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1400 // If the compares in later blocks need to use values not currently
1401 // exported from this block, export them now. This block should always
1402 // be the first entry.
1403 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1405 // Allow some cases to be rejected.
1406 if (ShouldEmitAsBranches(SwitchCases)) {
1407 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1408 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1409 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1412 // Emit the branch for this block.
1413 visitSwitchCase(SwitchCases[0]);
1414 SwitchCases.erase(SwitchCases.begin());
1418 // Okay, we decided not to do this, remove any inserted MBB's and clear
1420 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1421 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1423 SwitchCases.clear();
1427 // Create a CaseBlock record representing this branch.
1428 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1429 NULL, Succ0MBB, Succ1MBB, CurMBB);
1430 // Use visitSwitchCase to actually insert the fast branch sequence for this
1432 visitSwitchCase(CB);
1435 /// visitSwitchCase - Emits the necessary code to represent a single node in
1436 /// the binary search tree resulting from lowering a switch instruction.
1437 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1439 SDOperand CondLHS = getValue(CB.CmpLHS);
1441 // Build the setcc now.
1442 if (CB.CmpMHS == NULL) {
1443 // Fold "(X == true)" to X and "(X == false)" to !X to
1444 // handle common cases produced by branch lowering.
1445 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1447 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1448 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1449 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1451 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1453 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1455 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1456 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1458 SDOperand CmpOp = getValue(CB.CmpMHS);
1459 MVT::ValueType VT = CmpOp.getValueType();
1461 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1462 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1464 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1465 Cond = DAG.getSetCC(MVT::i1, SUB,
1466 DAG.getConstant(High-Low, VT), ISD::SETULE);
1471 // Set NextBlock to be the MBB immediately after the current one, if any.
1472 // This is used to avoid emitting unnecessary branches to the next block.
1473 MachineBasicBlock *NextBlock = 0;
1474 MachineFunction::iterator BBI = CurMBB;
1475 if (++BBI != CurMBB->getParent()->end())
1478 // If the lhs block is the next block, invert the condition so that we can
1479 // fall through to the lhs instead of the rhs block.
1480 if (CB.TrueBB == NextBlock) {
1481 std::swap(CB.TrueBB, CB.FalseBB);
1482 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1483 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1485 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1486 DAG.getBasicBlock(CB.TrueBB));
1487 if (CB.FalseBB == NextBlock)
1488 DAG.setRoot(BrCond);
1490 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1491 DAG.getBasicBlock(CB.FalseBB)));
1492 // Update successor info
1493 CurMBB->addSuccessor(CB.TrueBB);
1494 CurMBB->addSuccessor(CB.FalseBB);
1497 /// visitJumpTable - Emit JumpTable node in the current MBB
1498 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1499 // Emit the code for the jump table
1500 assert(JT.Reg != -1U && "Should lower JT Header first!");
1501 MVT::ValueType PTy = TLI.getPointerTy();
1502 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1503 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1504 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1509 /// visitJumpTableHeader - This function emits necessary code to produce index
1510 /// in the JumpTable from switch case.
1511 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1512 SelectionDAGISel::JumpTableHeader &JTH) {
1513 // Subtract the lowest switch case value from the value being switched on
1514 // and conditional branch to default mbb if the result is greater than the
1515 // difference between smallest and largest cases.
1516 SDOperand SwitchOp = getValue(JTH.SValue);
1517 MVT::ValueType VT = SwitchOp.getValueType();
1518 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1519 DAG.getConstant(JTH.First, VT));
1521 // The SDNode we just created, which holds the value being switched on
1522 // minus the the smallest case value, needs to be copied to a virtual
1523 // register so it can be used as an index into the jump table in a
1524 // subsequent basic block. This value may be smaller or larger than the
1525 // target's pointer type, and therefore require extension or truncating.
1526 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
1527 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1529 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1531 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1532 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1533 JT.Reg = JumpTableReg;
1535 // Emit the range check for the jump table, and branch to the default
1536 // block for the switch statement if the value being switched on exceeds
1537 // the largest case in the switch.
1538 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1539 DAG.getConstant(JTH.Last-JTH.First,VT),
1542 // Set NextBlock to be the MBB immediately after the current one, if any.
1543 // This is used to avoid emitting unnecessary branches to the next block.
1544 MachineBasicBlock *NextBlock = 0;
1545 MachineFunction::iterator BBI = CurMBB;
1546 if (++BBI != CurMBB->getParent()->end())
1549 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1550 DAG.getBasicBlock(JT.Default));
1552 if (JT.MBB == NextBlock)
1553 DAG.setRoot(BrCond);
1555 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1556 DAG.getBasicBlock(JT.MBB)));
1561 /// visitBitTestHeader - This function emits necessary code to produce value
1562 /// suitable for "bit tests"
1563 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1564 // Subtract the minimum value
1565 SDOperand SwitchOp = getValue(B.SValue);
1566 MVT::ValueType VT = SwitchOp.getValueType();
1567 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1568 DAG.getConstant(B.First, VT));
1571 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1572 DAG.getConstant(B.Range, VT),
1576 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
1577 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1579 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1581 // Make desired shift
1582 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1583 DAG.getConstant(1, TLI.getPointerTy()),
1586 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1587 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1590 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1591 DAG.getBasicBlock(B.Default));
1593 // Set NextBlock to be the MBB immediately after the current one, if any.
1594 // This is used to avoid emitting unnecessary branches to the next block.
1595 MachineBasicBlock *NextBlock = 0;
1596 MachineFunction::iterator BBI = CurMBB;
1597 if (++BBI != CurMBB->getParent()->end())
1600 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1601 if (MBB == NextBlock)
1602 DAG.setRoot(BrRange);
1604 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1605 DAG.getBasicBlock(MBB)));
1607 CurMBB->addSuccessor(B.Default);
1608 CurMBB->addSuccessor(MBB);
1613 /// visitBitTestCase - this function produces one "bit test"
1614 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1616 SelectionDAGISel::BitTestCase &B) {
1617 // Emit bit tests and jumps
1618 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
1620 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1622 DAG.getConstant(B.Mask,
1623 TLI.getPointerTy()));
1624 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1625 DAG.getConstant(0, TLI.getPointerTy()),
1627 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1628 AndCmp, DAG.getBasicBlock(B.TargetBB));
1630 // Set NextBlock to be the MBB immediately after the current one, if any.
1631 // This is used to avoid emitting unnecessary branches to the next block.
1632 MachineBasicBlock *NextBlock = 0;
1633 MachineFunction::iterator BBI = CurMBB;
1634 if (++BBI != CurMBB->getParent()->end())
1637 if (NextMBB == NextBlock)
1640 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1641 DAG.getBasicBlock(NextMBB)));
1643 CurMBB->addSuccessor(B.TargetBB);
1644 CurMBB->addSuccessor(NextMBB);
1649 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1650 // Retrieve successors.
1651 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1652 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1654 if (isa<InlineAsm>(I.getCalledValue()))
1657 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1659 // If the value of the invoke is used outside of its defining block, make it
1660 // available as a virtual register.
1661 if (!I.use_empty()) {
1662 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1663 if (VMI != FuncInfo.ValueMap.end())
1664 CopyValueToVirtualRegister(&I, VMI->second);
1667 // Drop into normal successor.
1668 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1669 DAG.getBasicBlock(Return)));
1671 // Update successor info
1672 CurMBB->addSuccessor(Return);
1673 CurMBB->addSuccessor(LandingPad);
1676 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1679 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1680 /// small case ranges).
1681 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1682 CaseRecVector& WorkList,
1684 MachineBasicBlock* Default) {
1685 Case& BackCase = *(CR.Range.second-1);
1687 // Size is the number of Cases represented by this range.
1688 unsigned Size = CR.Range.second - CR.Range.first;
1692 // Get the MachineFunction which holds the current MBB. This is used when
1693 // inserting any additional MBBs necessary to represent the switch.
1694 MachineFunction *CurMF = CurMBB->getParent();
1696 // Figure out which block is immediately after the current one.
1697 MachineBasicBlock *NextBlock = 0;
1698 MachineFunction::iterator BBI = CR.CaseBB;
1700 if (++BBI != CurMBB->getParent()->end())
1703 // TODO: If any two of the cases has the same destination, and if one value
1704 // is the same as the other, but has one bit unset that the other has set,
1705 // use bit manipulation to do two compares at once. For example:
1706 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1708 // Rearrange the case blocks so that the last one falls through if possible.
1709 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1710 // The last case block won't fall through into 'NextBlock' if we emit the
1711 // branches in this order. See if rearranging a case value would help.
1712 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1713 if (I->BB == NextBlock) {
1714 std::swap(*I, BackCase);
1720 // Create a CaseBlock record representing a conditional branch to
1721 // the Case's target mbb if the value being switched on SV is equal
1723 MachineBasicBlock *CurBlock = CR.CaseBB;
1724 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1725 MachineBasicBlock *FallThrough;
1727 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1728 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1730 // If the last case doesn't match, go to the default block.
1731 FallThrough = Default;
1734 Value *RHS, *LHS, *MHS;
1736 if (I->High == I->Low) {
1737 // This is just small small case range :) containing exactly 1 case
1739 LHS = SV; RHS = I->High; MHS = NULL;
1742 LHS = I->Low; MHS = SV; RHS = I->High;
1744 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1745 I->BB, FallThrough, CurBlock);
1747 // If emitting the first comparison, just call visitSwitchCase to emit the
1748 // code into the current block. Otherwise, push the CaseBlock onto the
1749 // vector to be later processed by SDISel, and insert the node's MBB
1750 // before the next MBB.
1751 if (CurBlock == CurMBB)
1752 visitSwitchCase(CB);
1754 SwitchCases.push_back(CB);
1756 CurBlock = FallThrough;
1762 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1763 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1764 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1767 /// handleJTSwitchCase - Emit jumptable for current switch case range
1768 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1769 CaseRecVector& WorkList,
1771 MachineBasicBlock* Default) {
1772 Case& FrontCase = *CR.Range.first;
1773 Case& BackCase = *(CR.Range.second-1);
1775 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1776 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1779 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1783 if (!areJTsAllowed(TLI) || TSize <= 3)
1786 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1790 DOUT << "Lowering jump table\n"
1791 << "First entry: " << First << ". Last entry: " << Last << "\n"
1792 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1794 // Get the MachineFunction which holds the current MBB. This is used when
1795 // inserting any additional MBBs necessary to represent the switch.
1796 MachineFunction *CurMF = CurMBB->getParent();
1798 // Figure out which block is immediately after the current one.
1799 MachineBasicBlock *NextBlock = 0;
1800 MachineFunction::iterator BBI = CR.CaseBB;
1802 if (++BBI != CurMBB->getParent()->end())
1805 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1807 // Create a new basic block to hold the code for loading the address
1808 // of the jump table, and jumping to it. Update successor information;
1809 // we will either branch to the default case for the switch, or the jump
1811 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1812 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1813 CR.CaseBB->addSuccessor(Default);
1814 CR.CaseBB->addSuccessor(JumpTableBB);
1816 // Build a vector of destination BBs, corresponding to each target
1817 // of the jump table. If the value of the jump table slot corresponds to
1818 // a case statement, push the case's BB onto the vector, otherwise, push
1820 std::vector<MachineBasicBlock*> DestBBs;
1821 int64_t TEI = First;
1822 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1823 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1824 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1826 if ((Low <= TEI) && (TEI <= High)) {
1827 DestBBs.push_back(I->BB);
1831 DestBBs.push_back(Default);
1835 // Update successor info. Add one edge to each unique successor.
1836 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1837 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1838 E = DestBBs.end(); I != E; ++I) {
1839 if (!SuccsHandled[(*I)->getNumber()]) {
1840 SuccsHandled[(*I)->getNumber()] = true;
1841 JumpTableBB->addSuccessor(*I);
1845 // Create a jump table index for this jump table, or return an existing
1847 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1849 // Set the jump table information so that we can codegen it as a second
1850 // MachineBasicBlock
1851 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1852 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1853 (CR.CaseBB == CurMBB));
1854 if (CR.CaseBB == CurMBB)
1855 visitJumpTableHeader(JT, JTH);
1857 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1862 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1864 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1865 CaseRecVector& WorkList,
1867 MachineBasicBlock* Default) {
1868 // Get the MachineFunction which holds the current MBB. This is used when
1869 // inserting any additional MBBs necessary to represent the switch.
1870 MachineFunction *CurMF = CurMBB->getParent();
1872 // Figure out which block is immediately after the current one.
1873 MachineBasicBlock *NextBlock = 0;
1874 MachineFunction::iterator BBI = CR.CaseBB;
1876 if (++BBI != CurMBB->getParent()->end())
1879 Case& FrontCase = *CR.Range.first;
1880 Case& BackCase = *(CR.Range.second-1);
1881 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1883 // Size is the number of Cases represented by this range.
1884 unsigned Size = CR.Range.second - CR.Range.first;
1886 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1887 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1889 CaseItr Pivot = CR.Range.first + Size/2;
1891 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1892 // (heuristically) allow us to emit JumpTable's later.
1894 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1898 uint64_t LSize = FrontCase.size();
1899 uint64_t RSize = TSize-LSize;
1900 DOUT << "Selecting best pivot: \n"
1901 << "First: " << First << ", Last: " << Last <<"\n"
1902 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1903 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1905 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1906 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1907 assert((RBegin-LEnd>=1) && "Invalid case distance");
1908 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1909 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1910 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1911 // Should always split in some non-trivial place
1913 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1914 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1915 << "Metric: " << Metric << "\n";
1916 if (FMetric < Metric) {
1919 DOUT << "Current metric set to: " << FMetric << "\n";
1925 if (areJTsAllowed(TLI)) {
1926 // If our case is dense we *really* should handle it earlier!
1927 assert((FMetric > 0) && "Should handle dense range earlier!");
1929 Pivot = CR.Range.first + Size/2;
1932 CaseRange LHSR(CR.Range.first, Pivot);
1933 CaseRange RHSR(Pivot, CR.Range.second);
1934 Constant *C = Pivot->Low;
1935 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1937 // We know that we branch to the LHS if the Value being switched on is
1938 // less than the Pivot value, C. We use this to optimize our binary
1939 // tree a bit, by recognizing that if SV is greater than or equal to the
1940 // LHS's Case Value, and that Case Value is exactly one less than the
1941 // Pivot's Value, then we can branch directly to the LHS's Target,
1942 // rather than creating a leaf node for it.
1943 if ((LHSR.second - LHSR.first) == 1 &&
1944 LHSR.first->High == CR.GE &&
1945 cast<ConstantInt>(C)->getSExtValue() ==
1946 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1947 TrueBB = LHSR.first->BB;
1949 TrueBB = new MachineBasicBlock(LLVMBB);
1950 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1951 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1954 // Similar to the optimization above, if the Value being switched on is
1955 // known to be less than the Constant CR.LT, and the current Case Value
1956 // is CR.LT - 1, then we can branch directly to the target block for
1957 // the current Case Value, rather than emitting a RHS leaf node for it.
1958 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1959 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1960 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1961 FalseBB = RHSR.first->BB;
1963 FalseBB = new MachineBasicBlock(LLVMBB);
1964 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1965 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1968 // Create a CaseBlock record representing a conditional branch to
1969 // the LHS node if the value being switched on SV is less than C.
1970 // Otherwise, branch to LHS.
1971 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1972 TrueBB, FalseBB, CR.CaseBB);
1974 if (CR.CaseBB == CurMBB)
1975 visitSwitchCase(CB);
1977 SwitchCases.push_back(CB);
1982 /// handleBitTestsSwitchCase - if current case range has few destination and
1983 /// range span less, than machine word bitwidth, encode case range into series
1984 /// of masks and emit bit tests with these masks.
1985 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1986 CaseRecVector& WorkList,
1988 MachineBasicBlock* Default){
1989 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
1991 Case& FrontCase = *CR.Range.first;
1992 Case& BackCase = *(CR.Range.second-1);
1994 // Get the MachineFunction which holds the current MBB. This is used when
1995 // inserting any additional MBBs necessary to represent the switch.
1996 MachineFunction *CurMF = CurMBB->getParent();
1998 unsigned numCmps = 0;
1999 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2001 // Single case counts one, case range - two.
2002 if (I->Low == I->High)
2008 // Count unique destinations
2009 SmallSet<MachineBasicBlock*, 4> Dests;
2010 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2011 Dests.insert(I->BB);
2012 if (Dests.size() > 3)
2013 // Don't bother the code below, if there are too much unique destinations
2016 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2017 << "Total number of comparisons: " << numCmps << "\n";
2019 // Compute span of values.
2020 Constant* minValue = FrontCase.Low;
2021 Constant* maxValue = BackCase.High;
2022 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2023 cast<ConstantInt>(minValue)->getSExtValue();
2024 DOUT << "Compare range: " << range << "\n"
2025 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2026 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2028 if (range>=IntPtrBits ||
2029 (!(Dests.size() == 1 && numCmps >= 3) &&
2030 !(Dests.size() == 2 && numCmps >= 5) &&
2031 !(Dests.size() >= 3 && numCmps >= 6)))
2034 DOUT << "Emitting bit tests\n";
2035 int64_t lowBound = 0;
2037 // Optimize the case where all the case values fit in a
2038 // word without having to subtract minValue. In this case,
2039 // we can optimize away the subtraction.
2040 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2041 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
2042 range = cast<ConstantInt>(maxValue)->getSExtValue();
2044 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2047 CaseBitsVector CasesBits;
2048 unsigned i, count = 0;
2050 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2051 MachineBasicBlock* Dest = I->BB;
2052 for (i = 0; i < count; ++i)
2053 if (Dest == CasesBits[i].BB)
2057 assert((count < 3) && "Too much destinations to test!");
2058 CasesBits.push_back(CaseBits(0, Dest, 0));
2062 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2063 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2065 for (uint64_t j = lo; j <= hi; j++) {
2066 CasesBits[i].Mask |= 1ULL << j;
2067 CasesBits[i].Bits++;
2071 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2073 SelectionDAGISel::BitTestInfo BTC;
2075 // Figure out which block is immediately after the current one.
2076 MachineFunction::iterator BBI = CR.CaseBB;
2079 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2082 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2083 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2084 << ", BB: " << CasesBits[i].BB << "\n";
2086 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2087 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2088 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2093 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2094 -1U, (CR.CaseBB == CurMBB),
2095 CR.CaseBB, Default, BTC);
2097 if (CR.CaseBB == CurMBB)
2098 visitBitTestHeader(BTB);
2100 BitTestCases.push_back(BTB);
2106 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2107 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2108 const SwitchInst& SI) {
2109 unsigned numCmps = 0;
2111 // Start with "simple" cases
2112 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2113 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2114 Cases.push_back(Case(SI.getSuccessorValue(i),
2115 SI.getSuccessorValue(i),
2118 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2120 // Merge case into clusters
2121 if (Cases.size()>=2)
2122 // Must recompute end() each iteration because it may be
2123 // invalidated by erase if we hold on to it
2124 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2125 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2126 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2127 MachineBasicBlock* nextBB = J->BB;
2128 MachineBasicBlock* currentBB = I->BB;
2130 // If the two neighboring cases go to the same destination, merge them
2131 // into a single case.
2132 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2140 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2141 if (I->Low != I->High)
2142 // A range counts double, since it requires two compares.
2149 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2150 // Figure out which block is immediately after the current one.
2151 MachineBasicBlock *NextBlock = 0;
2152 MachineFunction::iterator BBI = CurMBB;
2154 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2156 // If there is only the default destination, branch to it if it is not the
2157 // next basic block. Otherwise, just fall through.
2158 if (SI.getNumOperands() == 2) {
2159 // Update machine-CFG edges.
2161 // If this is not a fall-through branch, emit the branch.
2162 if (Default != NextBlock)
2163 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2164 DAG.getBasicBlock(Default)));
2166 CurMBB->addSuccessor(Default);
2170 // If there are any non-default case statements, create a vector of Cases
2171 // representing each one, and sort the vector so that we can efficiently
2172 // create a binary search tree from them.
2174 unsigned numCmps = Clusterify(Cases, SI);
2175 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2176 << ". Total compares: " << numCmps << "\n";
2178 // Get the Value to be switched on and default basic blocks, which will be
2179 // inserted into CaseBlock records, representing basic blocks in the binary
2181 Value *SV = SI.getOperand(0);
2183 // Push the initial CaseRec onto the worklist
2184 CaseRecVector WorkList;
2185 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2187 while (!WorkList.empty()) {
2188 // Grab a record representing a case range to process off the worklist
2189 CaseRec CR = WorkList.back();
2190 WorkList.pop_back();
2192 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2195 // If the range has few cases (two or less) emit a series of specific
2197 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2200 // If the switch has more than 5 blocks, and at least 40% dense, and the
2201 // target supports indirect branches, then emit a jump table rather than
2202 // lowering the switch to a binary tree of conditional branches.
2203 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2206 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2207 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2208 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2213 void SelectionDAGLowering::visitSub(User &I) {
2214 // -0.0 - X --> fneg
2215 const Type *Ty = I.getType();
2216 if (isa<VectorType>(Ty)) {
2217 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2218 const VectorType *DestTy = cast<VectorType>(I.getType());
2219 const Type *ElTy = DestTy->getElementType();
2220 if (ElTy->isFloatingPoint()) {
2221 unsigned VL = DestTy->getNumElements();
2222 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2223 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2225 SDOperand Op2 = getValue(I.getOperand(1));
2226 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2232 if (Ty->isFloatingPoint()) {
2233 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2234 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2235 SDOperand Op2 = getValue(I.getOperand(1));
2236 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2241 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2244 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2245 SDOperand Op1 = getValue(I.getOperand(0));
2246 SDOperand Op2 = getValue(I.getOperand(1));
2248 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2251 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2252 SDOperand Op1 = getValue(I.getOperand(0));
2253 SDOperand Op2 = getValue(I.getOperand(1));
2255 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2256 MVT::getSizeInBits(Op2.getValueType()))
2257 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2258 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2259 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2261 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2264 void SelectionDAGLowering::visitICmp(User &I) {
2265 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2266 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2267 predicate = IC->getPredicate();
2268 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2269 predicate = ICmpInst::Predicate(IC->getPredicate());
2270 SDOperand Op1 = getValue(I.getOperand(0));
2271 SDOperand Op2 = getValue(I.getOperand(1));
2272 ISD::CondCode Opcode;
2273 switch (predicate) {
2274 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2275 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2276 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2277 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2278 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2279 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2280 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2281 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2282 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2283 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2285 assert(!"Invalid ICmp predicate value");
2286 Opcode = ISD::SETEQ;
2289 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2292 void SelectionDAGLowering::visitFCmp(User &I) {
2293 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2294 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2295 predicate = FC->getPredicate();
2296 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2297 predicate = FCmpInst::Predicate(FC->getPredicate());
2298 SDOperand Op1 = getValue(I.getOperand(0));
2299 SDOperand Op2 = getValue(I.getOperand(1));
2300 ISD::CondCode Condition, FOC, FPC;
2301 switch (predicate) {
2302 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2303 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2304 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2305 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2306 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2307 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2308 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2309 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2310 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2311 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2312 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2313 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2314 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2315 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2316 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2317 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2319 assert(!"Invalid FCmp predicate value");
2320 FOC = FPC = ISD::SETFALSE;
2323 if (FiniteOnlyFPMath())
2327 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2330 void SelectionDAGLowering::visitSelect(User &I) {
2331 SDOperand Cond = getValue(I.getOperand(0));
2332 SDOperand TrueVal = getValue(I.getOperand(1));
2333 SDOperand FalseVal = getValue(I.getOperand(2));
2334 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2335 TrueVal, FalseVal));
2339 void SelectionDAGLowering::visitTrunc(User &I) {
2340 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2341 SDOperand N = getValue(I.getOperand(0));
2342 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2343 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2346 void SelectionDAGLowering::visitZExt(User &I) {
2347 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2348 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2349 SDOperand N = getValue(I.getOperand(0));
2350 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2351 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2354 void SelectionDAGLowering::visitSExt(User &I) {
2355 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2356 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2357 SDOperand N = getValue(I.getOperand(0));
2358 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2359 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2362 void SelectionDAGLowering::visitFPTrunc(User &I) {
2363 // FPTrunc is never a no-op cast, no need to check
2364 SDOperand N = getValue(I.getOperand(0));
2365 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2366 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2369 void SelectionDAGLowering::visitFPExt(User &I){
2370 // FPTrunc is never a no-op cast, no need to check
2371 SDOperand N = getValue(I.getOperand(0));
2372 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2373 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2376 void SelectionDAGLowering::visitFPToUI(User &I) {
2377 // FPToUI is never a no-op cast, no need to check
2378 SDOperand N = getValue(I.getOperand(0));
2379 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2380 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2383 void SelectionDAGLowering::visitFPToSI(User &I) {
2384 // FPToSI is never a no-op cast, no need to check
2385 SDOperand N = getValue(I.getOperand(0));
2386 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2387 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2390 void SelectionDAGLowering::visitUIToFP(User &I) {
2391 // UIToFP is never a no-op cast, no need to check
2392 SDOperand N = getValue(I.getOperand(0));
2393 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2394 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2397 void SelectionDAGLowering::visitSIToFP(User &I){
2398 // UIToFP is never a no-op cast, no need to check
2399 SDOperand N = getValue(I.getOperand(0));
2400 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2401 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2404 void SelectionDAGLowering::visitPtrToInt(User &I) {
2405 // What to do depends on the size of the integer and the size of the pointer.
2406 // We can either truncate, zero extend, or no-op, accordingly.
2407 SDOperand N = getValue(I.getOperand(0));
2408 MVT::ValueType SrcVT = N.getValueType();
2409 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2411 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2412 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2414 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2415 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2416 setValue(&I, Result);
2419 void SelectionDAGLowering::visitIntToPtr(User &I) {
2420 // What to do depends on the size of the integer and the size of the pointer.
2421 // We can either truncate, zero extend, or no-op, accordingly.
2422 SDOperand N = getValue(I.getOperand(0));
2423 MVT::ValueType SrcVT = N.getValueType();
2424 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2425 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2426 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2428 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2429 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2432 void SelectionDAGLowering::visitBitCast(User &I) {
2433 SDOperand N = getValue(I.getOperand(0));
2434 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2436 // BitCast assures us that source and destination are the same size so this
2437 // is either a BIT_CONVERT or a no-op.
2438 if (DestVT != N.getValueType())
2439 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2441 setValue(&I, N); // noop cast.
2444 void SelectionDAGLowering::visitInsertElement(User &I) {
2445 SDOperand InVec = getValue(I.getOperand(0));
2446 SDOperand InVal = getValue(I.getOperand(1));
2447 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2448 getValue(I.getOperand(2)));
2450 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2451 TLI.getValueType(I.getType()),
2452 InVec, InVal, InIdx));
2455 void SelectionDAGLowering::visitExtractElement(User &I) {
2456 SDOperand InVec = getValue(I.getOperand(0));
2457 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2458 getValue(I.getOperand(1)));
2459 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2460 TLI.getValueType(I.getType()), InVec, InIdx));
2463 void SelectionDAGLowering::visitShuffleVector(User &I) {
2464 SDOperand V1 = getValue(I.getOperand(0));
2465 SDOperand V2 = getValue(I.getOperand(1));
2466 SDOperand Mask = getValue(I.getOperand(2));
2468 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2469 TLI.getValueType(I.getType()),
2474 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2475 SDOperand N = getValue(I.getOperand(0));
2476 const Type *Ty = I.getOperand(0)->getType();
2478 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2481 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2482 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2485 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2486 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2487 DAG.getIntPtrConstant(Offset));
2489 Ty = StTy->getElementType(Field);
2491 Ty = cast<SequentialType>(Ty)->getElementType();
2493 // If this is a constant subscript, handle it quickly.
2494 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2495 if (CI->getZExtValue() == 0) continue;
2497 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2498 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2499 DAG.getIntPtrConstant(Offs));
2503 // N = N + Idx * ElementSize;
2504 uint64_t ElementSize = TD->getABITypeSize(Ty);
2505 SDOperand IdxN = getValue(Idx);
2507 // If the index is smaller or larger than intptr_t, truncate or extend
2509 if (IdxN.getValueType() < N.getValueType()) {
2510 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2511 } else if (IdxN.getValueType() > N.getValueType())
2512 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2514 // If this is a multiply by a power of two, turn it into a shl
2515 // immediately. This is a very common case.
2516 if (isPowerOf2_64(ElementSize)) {
2517 unsigned Amt = Log2_64(ElementSize);
2518 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2519 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2520 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2524 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2525 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2526 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2532 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2533 // If this is a fixed sized alloca in the entry block of the function,
2534 // allocate it statically on the stack.
2535 if (FuncInfo.StaticAllocaMap.count(&I))
2536 return; // getValue will auto-populate this.
2538 const Type *Ty = I.getAllocatedType();
2539 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2541 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2544 SDOperand AllocSize = getValue(I.getArraySize());
2545 MVT::ValueType IntPtr = TLI.getPointerTy();
2546 if (IntPtr < AllocSize.getValueType())
2547 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2548 else if (IntPtr > AllocSize.getValueType())
2549 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2551 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2552 DAG.getIntPtrConstant(TySize));
2554 // Handle alignment. If the requested alignment is less than or equal to
2555 // the stack alignment, ignore it. If the size is greater than or equal to
2556 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2557 unsigned StackAlign =
2558 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2559 if (Align <= StackAlign)
2562 // Round the size of the allocation up to the stack alignment size
2563 // by add SA-1 to the size.
2564 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2565 DAG.getIntPtrConstant(StackAlign-1));
2566 // Mask out the low bits for alignment purposes.
2567 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2568 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2570 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2571 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2573 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2575 DAG.setRoot(DSA.getValue(1));
2577 // Inform the Frame Information that we have just allocated a variable-sized
2579 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2582 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2583 SDOperand Ptr = getValue(I.getOperand(0));
2589 // Do not serialize non-volatile loads against each other.
2590 Root = DAG.getRoot();
2593 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2594 Root, I.isVolatile(), I.getAlignment()));
2597 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2598 const Value *SV, SDOperand Root,
2600 unsigned Alignment) {
2602 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2603 isVolatile, Alignment);
2606 DAG.setRoot(L.getValue(1));
2608 PendingLoads.push_back(L.getValue(1));
2614 void SelectionDAGLowering::visitStore(StoreInst &I) {
2615 Value *SrcV = I.getOperand(0);
2616 SDOperand Src = getValue(SrcV);
2617 SDOperand Ptr = getValue(I.getOperand(1));
2618 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2619 I.isVolatile(), I.getAlignment()));
2622 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2624 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2625 unsigned Intrinsic) {
2626 bool HasChain = !I.doesNotAccessMemory();
2627 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2629 // Build the operand list.
2630 SmallVector<SDOperand, 8> Ops;
2631 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2633 // We don't need to serialize loads against other loads.
2634 Ops.push_back(DAG.getRoot());
2636 Ops.push_back(getRoot());
2640 // Add the intrinsic ID as an integer operand.
2641 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2643 // Add all operands of the call to the operand list.
2644 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2645 SDOperand Op = getValue(I.getOperand(i));
2646 assert(TLI.isTypeLegal(Op.getValueType()) &&
2647 "Intrinsic uses a non-legal type?");
2651 std::vector<MVT::ValueType> VTs;
2652 if (I.getType() != Type::VoidTy) {
2653 MVT::ValueType VT = TLI.getValueType(I.getType());
2654 if (MVT::isVector(VT)) {
2655 const VectorType *DestTy = cast<VectorType>(I.getType());
2656 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2658 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2659 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2662 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2666 VTs.push_back(MVT::Other);
2668 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2673 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2674 &Ops[0], Ops.size());
2675 else if (I.getType() != Type::VoidTy)
2676 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2677 &Ops[0], Ops.size());
2679 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2680 &Ops[0], Ops.size());
2683 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2685 PendingLoads.push_back(Chain);
2689 if (I.getType() != Type::VoidTy) {
2690 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2691 MVT::ValueType VT = TLI.getValueType(PTy);
2692 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2694 setValue(&I, Result);
2698 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2699 static GlobalVariable *ExtractTypeInfo (Value *V) {
2700 V = IntrinsicInst::StripPointerCasts(V);
2701 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2702 assert ((GV || isa<ConstantPointerNull>(V)) &&
2703 "TypeInfo must be a global variable or NULL");
2707 /// addCatchInfo - Extract the personality and type infos from an eh.selector
2708 /// call, and add them to the specified machine basic block.
2709 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2710 MachineBasicBlock *MBB) {
2711 // Inform the MachineModuleInfo of the personality for this landing pad.
2712 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2713 assert(CE->getOpcode() == Instruction::BitCast &&
2714 isa<Function>(CE->getOperand(0)) &&
2715 "Personality should be a function");
2716 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2718 // Gather all the type infos for this landing pad and pass them along to
2719 // MachineModuleInfo.
2720 std::vector<GlobalVariable *> TyInfo;
2721 unsigned N = I.getNumOperands();
2723 for (unsigned i = N - 1; i > 2; --i) {
2724 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2725 unsigned FilterLength = CI->getZExtValue();
2726 unsigned FirstCatch = i + FilterLength + !FilterLength;
2727 assert (FirstCatch <= N && "Invalid filter length");
2729 if (FirstCatch < N) {
2730 TyInfo.reserve(N - FirstCatch);
2731 for (unsigned j = FirstCatch; j < N; ++j)
2732 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2733 MMI->addCatchTypeInfo(MBB, TyInfo);
2737 if (!FilterLength) {
2739 MMI->addCleanup(MBB);
2742 TyInfo.reserve(FilterLength - 1);
2743 for (unsigned j = i + 1; j < FirstCatch; ++j)
2744 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2745 MMI->addFilterTypeInfo(MBB, TyInfo);
2754 TyInfo.reserve(N - 3);
2755 for (unsigned j = 3; j < N; ++j)
2756 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2757 MMI->addCatchTypeInfo(MBB, TyInfo);
2761 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2762 /// we want to emit this as a call to a named external function, return the name
2763 /// otherwise lower it and return null.
2765 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2766 switch (Intrinsic) {
2768 // By default, turn this into a target intrinsic node.
2769 visitTargetIntrinsic(I, Intrinsic);
2771 case Intrinsic::vastart: visitVAStart(I); return 0;
2772 case Intrinsic::vaend: visitVAEnd(I); return 0;
2773 case Intrinsic::vacopy: visitVACopy(I); return 0;
2774 case Intrinsic::returnaddress:
2775 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2776 getValue(I.getOperand(1))));
2778 case Intrinsic::frameaddress:
2779 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2780 getValue(I.getOperand(1))));
2782 case Intrinsic::setjmp:
2783 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2785 case Intrinsic::longjmp:
2786 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2788 case Intrinsic::memcpy_i32:
2789 case Intrinsic::memcpy_i64: {
2790 SDOperand Op1 = getValue(I.getOperand(1));
2791 SDOperand Op2 = getValue(I.getOperand(2));
2792 SDOperand Op3 = getValue(I.getOperand(3));
2793 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2794 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2795 I.getOperand(1), 0, I.getOperand(2), 0));
2798 case Intrinsic::memset_i32:
2799 case Intrinsic::memset_i64: {
2800 SDOperand Op1 = getValue(I.getOperand(1));
2801 SDOperand Op2 = getValue(I.getOperand(2));
2802 SDOperand Op3 = getValue(I.getOperand(3));
2803 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2804 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2805 I.getOperand(1), 0));
2808 case Intrinsic::memmove_i32:
2809 case Intrinsic::memmove_i64: {
2810 SDOperand Op1 = getValue(I.getOperand(1));
2811 SDOperand Op2 = getValue(I.getOperand(2));
2812 SDOperand Op3 = getValue(I.getOperand(3));
2813 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2815 // If the source and destination are known to not be aliases, we can
2816 // lower memmove as memcpy.
2817 uint64_t Size = -1ULL;
2818 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2819 Size = C->getValue();
2820 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2821 AliasAnalysis::NoAlias) {
2822 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2823 I.getOperand(1), 0, I.getOperand(2), 0));
2827 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2828 I.getOperand(1), 0, I.getOperand(2), 0));
2831 case Intrinsic::dbg_stoppoint: {
2832 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2833 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2834 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2838 Ops[1] = getValue(SPI.getLineValue());
2839 Ops[2] = getValue(SPI.getColumnValue());
2841 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2842 assert(DD && "Not a debug information descriptor");
2843 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2845 Ops[3] = DAG.getString(CompileUnit->getFileName());
2846 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2848 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2853 case Intrinsic::dbg_region_start: {
2854 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2855 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2856 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2857 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2858 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2859 DAG.getConstant(LabelID, MVT::i32),
2860 DAG.getConstant(0, MVT::i32)));
2865 case Intrinsic::dbg_region_end: {
2866 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2867 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2868 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2869 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2870 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2871 DAG.getConstant(LabelID, MVT::i32),
2872 DAG.getConstant(0, MVT::i32)));
2877 case Intrinsic::dbg_func_start: {
2878 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2880 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2881 Value *SP = FSI.getSubprogram();
2882 if (SP && MMI->Verify(SP)) {
2883 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2884 // what (most?) gdb expects.
2885 DebugInfoDesc *DD = MMI->getDescFor(SP);
2886 assert(DD && "Not a debug information descriptor");
2887 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2888 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2889 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2890 CompileUnit->getFileName());
2891 // Record the source line but does create a label. It will be emitted
2892 // at asm emission time.
2893 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
2898 case Intrinsic::dbg_declare: {
2899 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2900 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2901 Value *Variable = DI.getVariable();
2902 if (MMI && Variable && MMI->Verify(Variable))
2903 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2904 getValue(DI.getAddress()), getValue(Variable)));
2908 case Intrinsic::eh_exception: {
2909 if (!CurMBB->isLandingPad()) {
2910 // FIXME: Mark exception register as live in. Hack for PR1508.
2911 unsigned Reg = TLI.getExceptionAddressRegister();
2912 if (Reg) CurMBB->addLiveIn(Reg);
2914 // Insert the EXCEPTIONADDR instruction.
2915 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2917 Ops[0] = DAG.getRoot();
2918 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2920 DAG.setRoot(Op.getValue(1));
2924 case Intrinsic::eh_selector_i32:
2925 case Intrinsic::eh_selector_i64: {
2926 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2927 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2928 MVT::i32 : MVT::i64);
2931 if (CurMBB->isLandingPad())
2932 addCatchInfo(I, MMI, CurMBB);
2935 FuncInfo.CatchInfoLost.insert(&I);
2937 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2938 unsigned Reg = TLI.getExceptionSelectorRegister();
2939 if (Reg) CurMBB->addLiveIn(Reg);
2942 // Insert the EHSELECTION instruction.
2943 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2945 Ops[0] = getValue(I.getOperand(1));
2947 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2949 DAG.setRoot(Op.getValue(1));
2951 setValue(&I, DAG.getConstant(0, VT));
2957 case Intrinsic::eh_typeid_for_i32:
2958 case Intrinsic::eh_typeid_for_i64: {
2959 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2960 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2961 MVT::i32 : MVT::i64);
2964 // Find the type id for the given typeinfo.
2965 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
2967 unsigned TypeID = MMI->getTypeIDFor(GV);
2968 setValue(&I, DAG.getConstant(TypeID, VT));
2970 // Return something different to eh_selector.
2971 setValue(&I, DAG.getConstant(1, VT));
2977 case Intrinsic::eh_return: {
2978 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2981 MMI->setCallsEHReturn(true);
2982 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2985 getValue(I.getOperand(1)),
2986 getValue(I.getOperand(2))));
2988 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2994 case Intrinsic::eh_unwind_init: {
2995 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2996 MMI->setCallsUnwindInit(true);
3002 case Intrinsic::eh_dwarf_cfa: {
3003 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3005 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3006 CfaArg = DAG.getNode(ISD::TRUNCATE,
3007 TLI.getPointerTy(), getValue(I.getOperand(1)));
3009 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3010 TLI.getPointerTy(), getValue(I.getOperand(1)));
3012 SDOperand Offset = DAG.getNode(ISD::ADD,
3014 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3015 TLI.getPointerTy()),
3017 setValue(&I, DAG.getNode(ISD::ADD,
3019 DAG.getNode(ISD::FRAMEADDR,
3022 TLI.getPointerTy())),
3027 case Intrinsic::sqrt:
3028 setValue(&I, DAG.getNode(ISD::FSQRT,
3029 getValue(I.getOperand(1)).getValueType(),
3030 getValue(I.getOperand(1))));
3032 case Intrinsic::powi:
3033 setValue(&I, DAG.getNode(ISD::FPOWI,
3034 getValue(I.getOperand(1)).getValueType(),
3035 getValue(I.getOperand(1)),
3036 getValue(I.getOperand(2))));
3038 case Intrinsic::sin:
3039 setValue(&I, DAG.getNode(ISD::FSIN,
3040 getValue(I.getOperand(1)).getValueType(),
3041 getValue(I.getOperand(1))));
3043 case Intrinsic::cos:
3044 setValue(&I, DAG.getNode(ISD::FCOS,
3045 getValue(I.getOperand(1)).getValueType(),
3046 getValue(I.getOperand(1))));
3048 case Intrinsic::pow:
3049 setValue(&I, DAG.getNode(ISD::FPOW,
3050 getValue(I.getOperand(1)).getValueType(),
3051 getValue(I.getOperand(1)),
3052 getValue(I.getOperand(2))));
3054 case Intrinsic::pcmarker: {
3055 SDOperand Tmp = getValue(I.getOperand(1));
3056 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3059 case Intrinsic::readcyclecounter: {
3060 SDOperand Op = getRoot();
3061 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3062 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3065 DAG.setRoot(Tmp.getValue(1));
3068 case Intrinsic::part_select: {
3069 // Currently not implemented: just abort
3070 assert(0 && "part_select intrinsic not implemented");
3073 case Intrinsic::part_set: {
3074 // Currently not implemented: just abort
3075 assert(0 && "part_set intrinsic not implemented");
3078 case Intrinsic::bswap:
3079 setValue(&I, DAG.getNode(ISD::BSWAP,
3080 getValue(I.getOperand(1)).getValueType(),
3081 getValue(I.getOperand(1))));
3083 case Intrinsic::cttz: {
3084 SDOperand Arg = getValue(I.getOperand(1));
3085 MVT::ValueType Ty = Arg.getValueType();
3086 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3087 setValue(&I, result);
3090 case Intrinsic::ctlz: {
3091 SDOperand Arg = getValue(I.getOperand(1));
3092 MVT::ValueType Ty = Arg.getValueType();
3093 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3094 setValue(&I, result);
3097 case Intrinsic::ctpop: {
3098 SDOperand Arg = getValue(I.getOperand(1));
3099 MVT::ValueType Ty = Arg.getValueType();
3100 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3101 setValue(&I, result);
3104 case Intrinsic::stacksave: {
3105 SDOperand Op = getRoot();
3106 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3107 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3109 DAG.setRoot(Tmp.getValue(1));
3112 case Intrinsic::stackrestore: {
3113 SDOperand Tmp = getValue(I.getOperand(1));
3114 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3117 case Intrinsic::var_annotation:
3118 // Discard annotate attributes
3121 case Intrinsic::init_trampoline: {
3123 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3127 Ops[1] = getValue(I.getOperand(1));
3128 Ops[2] = getValue(I.getOperand(2));
3129 Ops[3] = getValue(I.getOperand(3));
3130 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3131 Ops[5] = DAG.getSrcValue(F);
3133 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3134 DAG.getNodeValueTypes(TLI.getPointerTy(),
3139 DAG.setRoot(Tmp.getValue(1));
3143 case Intrinsic::gcroot:
3145 Value *Alloca = I.getOperand(1);
3146 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3148 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3149 GCI->addStackRoot(FI->getIndex(), TypeMap);
3153 case Intrinsic::gcread:
3154 case Intrinsic::gcwrite:
3155 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3158 case Intrinsic::flt_rounds: {
3159 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3163 case Intrinsic::trap: {
3164 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3167 case Intrinsic::prefetch: {
3170 Ops[1] = getValue(I.getOperand(1));
3171 Ops[2] = getValue(I.getOperand(2));
3172 Ops[3] = getValue(I.getOperand(3));
3173 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3177 case Intrinsic::memory_barrier: {
3180 for (int x = 1; x < 6; ++x)
3181 Ops[x] = getValue(I.getOperand(x));
3183 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3186 case Intrinsic::atomic_lcs: {
3187 SDOperand Root = getRoot();
3188 SDOperand O3 = getValue(I.getOperand(3));
3189 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3190 getValue(I.getOperand(1)),
3191 getValue(I.getOperand(2)),
3192 O3, O3.getValueType());
3194 DAG.setRoot(L.getValue(1));
3197 case Intrinsic::atomic_las: {
3198 SDOperand Root = getRoot();
3199 SDOperand O2 = getValue(I.getOperand(2));
3200 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root,
3201 getValue(I.getOperand(1)),
3202 O2, O2.getValueType());
3204 DAG.setRoot(L.getValue(1));
3207 case Intrinsic::atomic_swap: {
3208 SDOperand Root = getRoot();
3209 SDOperand O2 = getValue(I.getOperand(2));
3210 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root,
3211 getValue(I.getOperand(1)),
3212 O2, O2.getValueType());
3214 DAG.setRoot(L.getValue(1));
3222 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3224 MachineBasicBlock *LandingPad) {
3225 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3226 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3227 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3228 unsigned BeginLabel = 0, EndLabel = 0;
3230 TargetLowering::ArgListTy Args;
3231 TargetLowering::ArgListEntry Entry;
3232 Args.reserve(CS.arg_size());
3233 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3235 SDOperand ArgNode = getValue(*i);
3236 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3238 unsigned attrInd = i - CS.arg_begin() + 1;
3239 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3240 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3241 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3242 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3243 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3244 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3245 Entry.Alignment = CS.getParamAlignment(attrInd);
3246 Args.push_back(Entry);
3249 if (LandingPad && MMI) {
3250 // Insert a label before the invoke call to mark the try range. This can be
3251 // used to detect deletion of the invoke via the MachineModuleInfo.
3252 BeginLabel = MMI->NextLabelID();
3253 // Both PendingLoads and PendingExports must be flushed here;
3254 // this call might not return.
3256 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
3257 DAG.getConstant(BeginLabel, MVT::i32),
3258 DAG.getConstant(1, MVT::i32)));
3261 std::pair<SDOperand,SDOperand> Result =
3262 TLI.LowerCallTo(getRoot(), CS.getType(),
3263 CS.paramHasAttr(0, ParamAttr::SExt),
3264 CS.paramHasAttr(0, ParamAttr::ZExt),
3265 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3267 if (CS.getType() != Type::VoidTy)
3268 setValue(CS.getInstruction(), Result.first);
3269 DAG.setRoot(Result.second);
3271 if (LandingPad && MMI) {
3272 // Insert a label at the end of the invoke call to mark the try range. This
3273 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3274 EndLabel = MMI->NextLabelID();
3275 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3276 DAG.getConstant(EndLabel, MVT::i32),
3277 DAG.getConstant(1, MVT::i32)));
3279 // Inform MachineModuleInfo of range.
3280 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3285 void SelectionDAGLowering::visitCall(CallInst &I) {
3286 const char *RenameFn = 0;
3287 if (Function *F = I.getCalledFunction()) {
3288 if (F->isDeclaration()) {
3289 if (unsigned IID = F->getIntrinsicID()) {
3290 RenameFn = visitIntrinsicCall(I, IID);
3296 // Check for well-known libc/libm calls. If the function is internal, it
3297 // can't be a library call.
3298 unsigned NameLen = F->getNameLen();
3299 if (!F->hasInternalLinkage() && NameLen) {
3300 const char *NameStr = F->getNameStart();
3301 if (NameStr[0] == 'c' &&
3302 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3303 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3304 if (I.getNumOperands() == 3 && // Basic sanity checks.
3305 I.getOperand(1)->getType()->isFloatingPoint() &&
3306 I.getType() == I.getOperand(1)->getType() &&
3307 I.getType() == I.getOperand(2)->getType()) {
3308 SDOperand LHS = getValue(I.getOperand(1));
3309 SDOperand RHS = getValue(I.getOperand(2));
3310 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3314 } else if (NameStr[0] == 'f' &&
3315 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3316 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3317 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3318 if (I.getNumOperands() == 2 && // Basic sanity checks.
3319 I.getOperand(1)->getType()->isFloatingPoint() &&
3320 I.getType() == I.getOperand(1)->getType()) {
3321 SDOperand Tmp = getValue(I.getOperand(1));
3322 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3325 } else if (NameStr[0] == 's' &&
3326 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3327 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3328 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3329 if (I.getNumOperands() == 2 && // Basic sanity checks.
3330 I.getOperand(1)->getType()->isFloatingPoint() &&
3331 I.getType() == I.getOperand(1)->getType()) {
3332 SDOperand Tmp = getValue(I.getOperand(1));
3333 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3336 } else if (NameStr[0] == 'c' &&
3337 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3338 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3339 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3340 if (I.getNumOperands() == 2 && // Basic sanity checks.
3341 I.getOperand(1)->getType()->isFloatingPoint() &&
3342 I.getType() == I.getOperand(1)->getType()) {
3343 SDOperand Tmp = getValue(I.getOperand(1));
3344 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3349 } else if (isa<InlineAsm>(I.getOperand(0))) {
3356 Callee = getValue(I.getOperand(0));
3358 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3360 LowerCallTo(&I, Callee, I.isTailCall());
3364 void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3365 if (isa<UndefValue>(I.getOperand(0))) {
3366 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3367 setValue(&I, Undef);
3369 SDOperand Call = getValue(I.getOperand(0));
3371 // To add support for individual return values with aggregate types,
3372 // we'd need a way to take a getresult index and determine which
3373 // values of the Call SDNode are associated with it.
3374 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3375 "Individual return values must not be aggregates!");
3377 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3382 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3383 /// this value and returns the result as a ValueVT value. This uses
3384 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3385 /// If the Flag pointer is NULL, no flag is used.
3386 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3387 SDOperand &Chain, SDOperand *Flag)const{
3388 // Assemble the legal parts into the final values.
3389 SmallVector<SDOperand, 4> Values(ValueVTs.size());
3390 for (unsigned Value = 0, Part = 0; Value != ValueVTs.size(); ++Value) {
3391 // Copy the legal parts from the registers.
3392 MVT::ValueType ValueVT = ValueVTs[Value];
3393 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3394 MVT::ValueType RegisterVT = RegVTs[Value];
3396 SmallVector<SDOperand, 8> Parts(NumRegs);
3397 for (unsigned i = 0; i != NumRegs; ++i) {
3398 SDOperand P = Flag ?
3399 DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag) :
3400 DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3401 Chain = P.getValue(1);
3403 *Flag = P.getValue(2);
3407 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3411 return DAG.getNode(ISD::MERGE_VALUES,
3412 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3413 &Values[0], ValueVTs.size());
3416 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3417 /// specified value into the registers specified by this object. This uses
3418 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3419 /// If the Flag pointer is NULL, no flag is used.
3420 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3421 SDOperand &Chain, SDOperand *Flag) const {
3422 // Get the list of the values's legal parts.
3423 unsigned NumRegs = Regs.size();
3424 SmallVector<SDOperand, 8> Parts(NumRegs);
3425 for (unsigned Value = 0, Part = 0; Value != ValueVTs.size(); ++Value) {
3426 MVT::ValueType ValueVT = ValueVTs[Value];
3427 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3428 MVT::ValueType RegisterVT = RegVTs[Value];
3430 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3431 &Parts[Part], NumParts, RegisterVT);
3435 // Copy the parts into the registers.
3436 SmallVector<SDOperand, 8> Chains(NumRegs);
3437 for (unsigned i = 0; i != NumRegs; ++i) {
3438 SDOperand Part = Flag ?
3439 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) :
3440 DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3441 Chains[i] = Part.getValue(0);
3443 *Flag = Part.getValue(1);
3445 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3448 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3449 /// operand list. This adds the code marker and includes the number of
3450 /// values added into it.
3451 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3452 std::vector<SDOperand> &Ops) const {
3453 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3454 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3455 for (unsigned Value = 0, Reg = 0; Value != ValueVTs.size(); ++Value) {
3456 MVT::ValueType ValueVT = ValueVTs[Value];
3457 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3458 MVT::ValueType RegisterVT = RegVTs[Value];
3459 for (unsigned i = 0; i != NumRegs; ++i) {
3460 SDOperand RegOp = DAG.getRegister(Regs[Reg+i], RegisterVT);
3461 Ops.push_back(RegOp);
3467 /// isAllocatableRegister - If the specified register is safe to allocate,
3468 /// i.e. it isn't a stack pointer or some other special register, return the
3469 /// register class for the register. Otherwise, return null.
3470 static const TargetRegisterClass *
3471 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3472 const TargetLowering &TLI,
3473 const TargetRegisterInfo *TRI) {
3474 MVT::ValueType FoundVT = MVT::Other;
3475 const TargetRegisterClass *FoundRC = 0;
3476 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3477 E = TRI->regclass_end(); RCI != E; ++RCI) {
3478 MVT::ValueType ThisVT = MVT::Other;
3480 const TargetRegisterClass *RC = *RCI;
3481 // If none of the the value types for this register class are valid, we
3482 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3483 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3485 if (TLI.isTypeLegal(*I)) {
3486 // If we have already found this register in a different register class,
3487 // choose the one with the largest VT specified. For example, on
3488 // PowerPC, we favor f64 register classes over f32.
3489 if (FoundVT == MVT::Other ||
3490 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3497 if (ThisVT == MVT::Other) continue;
3499 // NOTE: This isn't ideal. In particular, this might allocate the
3500 // frame pointer in functions that need it (due to them not being taken
3501 // out of allocation, because a variable sized allocation hasn't been seen
3502 // yet). This is a slight code pessimization, but should still work.
3503 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3504 E = RC->allocation_order_end(MF); I != E; ++I)
3506 // We found a matching register class. Keep looking at others in case
3507 // we find one with larger registers that this physreg is also in.
3518 /// AsmOperandInfo - This contains information for each constraint that we are
3520 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3521 /// CallOperand - If this is the result output operand or a clobber
3522 /// this is null, otherwise it is the incoming operand to the CallInst.
3523 /// This gets modified as the asm is processed.
3524 SDOperand CallOperand;
3526 /// AssignedRegs - If this is a register or register class operand, this
3527 /// contains the set of register corresponding to the operand.
3528 RegsForValue AssignedRegs;
3530 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3531 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3534 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3535 /// busy in OutputRegs/InputRegs.
3536 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3537 std::set<unsigned> &OutputRegs,
3538 std::set<unsigned> &InputRegs,
3539 const TargetRegisterInfo &TRI) const {
3541 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3542 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3545 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3546 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3551 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3553 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3554 const TargetRegisterInfo &TRI) {
3555 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3557 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3558 for (; *Aliases; ++Aliases)
3559 Regs.insert(*Aliases);
3562 } // end anon namespace.
3565 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3566 /// specified operand. We prefer to assign virtual registers, to allow the
3567 /// register allocator handle the assignment process. However, if the asm uses
3568 /// features that we can't model on machineinstrs, we have SDISel do the
3569 /// allocation. This produces generally horrible, but correct, code.
3571 /// OpInfo describes the operand.
3572 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3573 /// or any explicitly clobbered registers.
3574 /// Input and OutputRegs are the set of already allocated physical registers.
3576 void SelectionDAGLowering::
3577 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3578 std::set<unsigned> &OutputRegs,
3579 std::set<unsigned> &InputRegs) {
3580 // Compute whether this value requires an input register, an output register,
3582 bool isOutReg = false;
3583 bool isInReg = false;
3584 switch (OpInfo.Type) {
3585 case InlineAsm::isOutput:
3588 // If this is an early-clobber output, or if there is an input
3589 // constraint that matches this, we need to reserve the input register
3590 // so no other inputs allocate to it.
3591 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3593 case InlineAsm::isInput:
3597 case InlineAsm::isClobber:
3604 MachineFunction &MF = DAG.getMachineFunction();
3605 std::vector<unsigned> Regs;
3607 // If this is a constraint for a single physreg, or a constraint for a
3608 // register class, find it.
3609 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3610 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3611 OpInfo.ConstraintVT);
3613 unsigned NumRegs = 1;
3614 if (OpInfo.ConstraintVT != MVT::Other)
3615 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3616 MVT::ValueType RegVT;
3617 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3620 // If this is a constraint for a specific physical register, like {r17},
3622 if (PhysReg.first) {
3623 if (OpInfo.ConstraintVT == MVT::Other)
3624 ValueVT = *PhysReg.second->vt_begin();
3626 // Get the actual register value type. This is important, because the user
3627 // may have asked for (e.g.) the AX register in i32 type. We need to
3628 // remember that AX is actually i16 to get the right extension.
3629 RegVT = *PhysReg.second->vt_begin();
3631 // This is a explicit reference to a physical register.
3632 Regs.push_back(PhysReg.first);
3634 // If this is an expanded reference, add the rest of the regs to Regs.
3636 TargetRegisterClass::iterator I = PhysReg.second->begin();
3637 TargetRegisterClass::iterator E = PhysReg.second->end();
3638 for (; *I != PhysReg.first; ++I)
3639 assert(I != E && "Didn't find reg!");
3641 // Already added the first reg.
3643 for (; NumRegs; --NumRegs, ++I) {
3644 assert(I != E && "Ran out of registers to allocate!");
3648 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3649 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3650 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3654 // Otherwise, if this was a reference to an LLVM register class, create vregs
3655 // for this reference.
3656 std::vector<unsigned> RegClassRegs;
3657 const TargetRegisterClass *RC = PhysReg.second;
3659 // If this is an early clobber or tied register, our regalloc doesn't know
3660 // how to maintain the constraint. If it isn't, go ahead and create vreg
3661 // and let the regalloc do the right thing.
3662 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3663 // If there is some other early clobber and this is an input register,
3664 // then we are forced to pre-allocate the input reg so it doesn't
3665 // conflict with the earlyclobber.
3666 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3667 RegVT = *PhysReg.second->vt_begin();
3669 if (OpInfo.ConstraintVT == MVT::Other)
3672 // Create the appropriate number of virtual registers.
3673 MachineRegisterInfo &RegInfo = MF.getRegInfo();
3674 for (; NumRegs; --NumRegs)
3675 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
3677 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3681 // Otherwise, we can't allocate it. Let the code below figure out how to
3682 // maintain these constraints.
3683 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3686 // This is a reference to a register class that doesn't directly correspond
3687 // to an LLVM register class. Allocate NumRegs consecutive, available,
3688 // registers from the class.
3689 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3690 OpInfo.ConstraintVT);
3693 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3694 unsigned NumAllocated = 0;
3695 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3696 unsigned Reg = RegClassRegs[i];
3697 // See if this register is available.
3698 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3699 (isInReg && InputRegs.count(Reg))) { // Already used.
3700 // Make sure we find consecutive registers.
3705 // Check to see if this register is allocatable (i.e. don't give out the
3708 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
3709 if (!RC) { // Couldn't allocate this register.
3710 // Reset NumAllocated to make sure we return consecutive registers.
3716 // Okay, this register is good, we can use it.
3719 // If we allocated enough consecutive registers, succeed.
3720 if (NumAllocated == NumRegs) {
3721 unsigned RegStart = (i-NumAllocated)+1;
3722 unsigned RegEnd = i+1;
3723 // Mark all of the allocated registers used.
3724 for (unsigned i = RegStart; i != RegEnd; ++i)
3725 Regs.push_back(RegClassRegs[i]);
3727 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
3728 OpInfo.ConstraintVT);
3729 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3734 // Otherwise, we couldn't allocate enough registers for this.
3739 /// visitInlineAsm - Handle a call to an InlineAsm object.
3741 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3742 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3744 /// ConstraintOperands - Information about all of the constraints.
3745 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
3747 SDOperand Chain = getRoot();
3750 std::set<unsigned> OutputRegs, InputRegs;
3752 // Do a prepass over the constraints, canonicalizing them, and building up the
3753 // ConstraintOperands list.
3754 std::vector<InlineAsm::ConstraintInfo>
3755 ConstraintInfos = IA->ParseConstraints();
3757 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3758 // constraint. If so, we can't let the register allocator allocate any input
3759 // registers, because it will not know to avoid the earlyclobbered output reg.
3760 bool SawEarlyClobber = false;
3762 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3763 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3764 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3765 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
3767 MVT::ValueType OpVT = MVT::Other;
3769 // Compute the value type for each operand.
3770 switch (OpInfo.Type) {
3771 case InlineAsm::isOutput:
3772 if (!OpInfo.isIndirect) {
3773 // The return value of the call is this value. As such, there is no
3774 // corresponding argument.
3775 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3776 OpVT = TLI.getValueType(CS.getType());
3778 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3781 case InlineAsm::isInput:
3782 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3784 case InlineAsm::isClobber:
3789 // If this is an input or an indirect output, process the call argument.
3790 // BasicBlocks are labels, currently appearing only in asm's.
3791 if (OpInfo.CallOperandVal) {
3792 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3793 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
3795 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3796 const Type *OpTy = OpInfo.CallOperandVal->getType();
3797 // If this is an indirect operand, the operand is a pointer to the
3799 if (OpInfo.isIndirect)
3800 OpTy = cast<PointerType>(OpTy)->getElementType();
3802 // If OpTy is not a first-class value, it may be a struct/union that we
3803 // can tile with integers.
3804 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3805 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3813 OpTy = IntegerType::get(BitSize);
3818 OpVT = TLI.getValueType(OpTy, true);
3822 OpInfo.ConstraintVT = OpVT;
3824 // Compute the constraint code and ConstraintType to use.
3825 TLI.ComputeConstraintToUse(OpInfo);
3827 // Keep track of whether we see an earlyclobber.
3828 SawEarlyClobber |= OpInfo.isEarlyClobber;
3830 // If we see a clobber of a register, it is an early clobber.
3831 if (!SawEarlyClobber &&
3832 OpInfo.Type == InlineAsm::isClobber &&
3833 OpInfo.ConstraintType == TargetLowering::C_Register) {
3834 // Note that we want to ignore things that we don't trick here, like
3835 // dirflag, fpsr, flags, etc.
3836 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3837 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3838 OpInfo.ConstraintVT);
3839 if (PhysReg.first || PhysReg.second) {
3840 // This is a register we know of.
3841 SawEarlyClobber = true;
3845 // If this is a memory input, and if the operand is not indirect, do what we
3846 // need to to provide an address for the memory input.
3847 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3848 !OpInfo.isIndirect) {
3849 assert(OpInfo.Type == InlineAsm::isInput &&
3850 "Can only indirectify direct input operands!");
3852 // Memory operands really want the address of the value. If we don't have
3853 // an indirect input, put it in the constpool if we can, otherwise spill
3854 // it to a stack slot.
3856 // If the operand is a float, integer, or vector constant, spill to a
3857 // constant pool entry to get its address.
3858 Value *OpVal = OpInfo.CallOperandVal;
3859 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3860 isa<ConstantVector>(OpVal)) {
3861 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3862 TLI.getPointerTy());
3864 // Otherwise, create a stack slot and emit a store to it before the
3866 const Type *Ty = OpVal->getType();
3867 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
3868 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3869 MachineFunction &MF = DAG.getMachineFunction();
3870 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3871 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3872 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3873 OpInfo.CallOperand = StackSlot;
3876 // There is no longer a Value* corresponding to this operand.
3877 OpInfo.CallOperandVal = 0;
3878 // It is now an indirect operand.
3879 OpInfo.isIndirect = true;
3882 // If this constraint is for a specific register, allocate it before
3884 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3885 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3887 ConstraintInfos.clear();
3890 // Second pass - Loop over all of the operands, assigning virtual or physregs
3891 // to registerclass operands.
3892 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3893 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3895 // C_Register operands have already been allocated, Other/Memory don't need
3897 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3898 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3901 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3902 std::vector<SDOperand> AsmNodeOperands;
3903 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3904 AsmNodeOperands.push_back(
3905 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3908 // Loop over all of the inputs, copying the operand values into the
3909 // appropriate registers and processing the output regs.
3910 RegsForValue RetValRegs;
3912 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3913 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3915 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3916 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3918 switch (OpInfo.Type) {
3919 case InlineAsm::isOutput: {
3920 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3921 OpInfo.ConstraintType != TargetLowering::C_Register) {
3922 // Memory output, or 'other' output (e.g. 'X' constraint).
3923 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3925 // Add information to the INLINEASM node to know about this output.
3926 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3927 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3928 TLI.getPointerTy()));
3929 AsmNodeOperands.push_back(OpInfo.CallOperand);
3933 // Otherwise, this is a register or register class output.
3935 // Copy the output from the appropriate register. Find a register that
3937 if (OpInfo.AssignedRegs.Regs.empty()) {
3938 cerr << "Couldn't allocate output reg for contraint '"
3939 << OpInfo.ConstraintCode << "'!\n";
3943 if (!OpInfo.isIndirect) {
3944 // This is the result value of the call.
3945 assert(RetValRegs.Regs.empty() &&
3946 "Cannot have multiple output constraints yet!");
3947 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3948 RetValRegs = OpInfo.AssignedRegs;
3950 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
3951 OpInfo.CallOperandVal));
3954 // Add information to the INLINEASM node to know that this register is
3956 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3960 case InlineAsm::isInput: {
3961 SDOperand InOperandVal = OpInfo.CallOperand;
3963 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
3964 // If this is required to match an output register we have already set,
3965 // just use its register.
3966 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
3968 // Scan until we find the definition we already emitted of this operand.
3969 // When we find it, create a RegsForValue operand.
3970 unsigned CurOp = 2; // The first operand.
3971 for (; OperandNo; --OperandNo) {
3972 // Advance to the next operand.
3974 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3975 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3976 (NumOps & 7) == 4 /*MEM*/) &&
3977 "Skipped past definitions?");
3978 CurOp += (NumOps>>3)+1;
3982 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3983 if ((NumOps & 7) == 2 /*REGDEF*/) {
3984 // Add NumOps>>3 registers to MatchedRegs.
3985 RegsForValue MatchedRegs;
3986 MatchedRegs.TLI = &TLI;
3987 MatchedRegs.ValueVTs.resize(1, InOperandVal.getValueType());
3988 MatchedRegs.RegVTs.resize(1, AsmNodeOperands[CurOp+1].getValueType());
3989 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3991 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3992 MatchedRegs.Regs.push_back(Reg);
3995 // Use the produced MatchedRegs object to
3996 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
3997 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4000 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4001 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4002 // Add information to the INLINEASM node to know about this input.
4003 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4004 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4005 TLI.getPointerTy()));
4006 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4011 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4012 assert(!OpInfo.isIndirect &&
4013 "Don't know how to handle indirect other inputs yet!");
4015 std::vector<SDOperand> Ops;
4016 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4019 cerr << "Invalid operand for inline asm constraint '"
4020 << OpInfo.ConstraintCode << "'!\n";
4024 // Add information to the INLINEASM node to know about this input.
4025 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4026 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4027 TLI.getPointerTy()));
4028 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4030 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4031 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4032 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4033 "Memory operands expect pointer values");
4035 // Add information to the INLINEASM node to know about this input.
4036 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4037 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4038 TLI.getPointerTy()));
4039 AsmNodeOperands.push_back(InOperandVal);
4043 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4044 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4045 "Unknown constraint type!");
4046 assert(!OpInfo.isIndirect &&
4047 "Don't know how to handle indirect register inputs yet!");
4049 // Copy the input into the appropriate registers.
4050 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4051 "Couldn't allocate input reg!");
4053 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4055 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4059 case InlineAsm::isClobber: {
4060 // Add the clobbered value to the operand list, so that the register
4061 // allocator is aware that the physreg got clobbered.
4062 if (!OpInfo.AssignedRegs.Regs.empty())
4063 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4070 // Finish up input operands.
4071 AsmNodeOperands[0] = Chain;
4072 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4074 Chain = DAG.getNode(ISD::INLINEASM,
4075 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4076 &AsmNodeOperands[0], AsmNodeOperands.size());
4077 Flag = Chain.getValue(1);
4079 // If this asm returns a register value, copy the result from that register
4080 // and set it as the value of the call.
4081 if (!RetValRegs.Regs.empty()) {
4082 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4084 // If the result of the inline asm is a vector, it may have the wrong
4085 // width/num elts. Make sure to convert it to the right type with
4087 if (MVT::isVector(Val.getValueType())) {
4088 const VectorType *VTy = cast<VectorType>(CS.getType());
4089 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
4091 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
4094 setValue(CS.getInstruction(), Val);
4097 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4099 // Process indirect outputs, first output all of the flagged copies out of
4101 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4102 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4103 Value *Ptr = IndirectStoresToEmit[i].second;
4104 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4105 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4108 // Emit the non-flagged stores from the physregs.
4109 SmallVector<SDOperand, 8> OutChains;
4110 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4111 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4112 getValue(StoresToEmit[i].second),
4113 StoresToEmit[i].second, 0));
4114 if (!OutChains.empty())
4115 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4116 &OutChains[0], OutChains.size());
4121 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4122 SDOperand Src = getValue(I.getOperand(0));
4124 MVT::ValueType IntPtr = TLI.getPointerTy();
4126 if (IntPtr < Src.getValueType())
4127 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4128 else if (IntPtr > Src.getValueType())
4129 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4131 // Scale the source by the type size.
4132 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4133 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4134 Src, DAG.getIntPtrConstant(ElementSize));
4136 TargetLowering::ArgListTy Args;
4137 TargetLowering::ArgListEntry Entry;
4139 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4140 Args.push_back(Entry);
4142 std::pair<SDOperand,SDOperand> Result =
4143 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4144 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4145 setValue(&I, Result.first); // Pointers always fit in registers
4146 DAG.setRoot(Result.second);
4149 void SelectionDAGLowering::visitFree(FreeInst &I) {
4150 TargetLowering::ArgListTy Args;
4151 TargetLowering::ArgListEntry Entry;
4152 Entry.Node = getValue(I.getOperand(0));
4153 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4154 Args.push_back(Entry);
4155 MVT::ValueType IntPtr = TLI.getPointerTy();
4156 std::pair<SDOperand,SDOperand> Result =
4157 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4158 CallingConv::C, true,
4159 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4160 DAG.setRoot(Result.second);
4163 // EmitInstrWithCustomInserter - This method should be implemented by targets
4164 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
4165 // instructions are special in various ways, which require special support to
4166 // insert. The specified MachineInstr is created but not inserted into any
4167 // basic blocks, and the scheduler passes ownership of it to this method.
4168 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4169 MachineBasicBlock *MBB) {
4170 cerr << "If a target marks an instruction with "
4171 << "'usesCustomDAGSchedInserter', it must implement "
4172 << "TargetLowering::EmitInstrWithCustomInserter!\n";
4177 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4178 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4179 getValue(I.getOperand(1)),
4180 DAG.getSrcValue(I.getOperand(1))));
4183 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4184 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4185 getValue(I.getOperand(0)),
4186 DAG.getSrcValue(I.getOperand(0)));
4188 DAG.setRoot(V.getValue(1));
4191 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4192 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4193 getValue(I.getOperand(1)),
4194 DAG.getSrcValue(I.getOperand(1))));
4197 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4198 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4199 getValue(I.getOperand(1)),
4200 getValue(I.getOperand(2)),
4201 DAG.getSrcValue(I.getOperand(1)),
4202 DAG.getSrcValue(I.getOperand(2))));
4205 /// TargetLowering::LowerArguments - This is the default LowerArguments
4206 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4207 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4208 /// integrated into SDISel.
4209 std::vector<SDOperand>
4210 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4211 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4212 std::vector<SDOperand> Ops;
4213 Ops.push_back(DAG.getRoot());
4214 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4215 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4217 // Add one result value for each formal argument.
4218 std::vector<MVT::ValueType> RetVals;
4220 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4222 MVT::ValueType VT = getValueType(I->getType());
4223 ISD::ArgFlagsTy Flags;
4224 unsigned OriginalAlignment =
4225 getTargetData()->getABITypeAlignment(I->getType());
4227 if (F.paramHasAttr(j, ParamAttr::ZExt))
4229 if (F.paramHasAttr(j, ParamAttr::SExt))
4231 if (F.paramHasAttr(j, ParamAttr::InReg))
4233 if (F.paramHasAttr(j, ParamAttr::StructRet))
4235 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4237 const PointerType *Ty = cast<PointerType>(I->getType());
4238 const Type *ElementTy = Ty->getElementType();
4239 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4240 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4241 // For ByVal, alignment should be passed from FE. BE will guess if
4242 // this info is not there but there are cases it cannot get right.
4243 if (F.getParamAlignment(j))
4244 FrameAlign = F.getParamAlignment(j);
4245 Flags.setByValAlign(FrameAlign);
4246 Flags.setByValSize(FrameSize);
4248 if (F.paramHasAttr(j, ParamAttr::Nest))
4250 Flags.setOrigAlign(OriginalAlignment);
4252 MVT::ValueType RegisterVT = getRegisterType(VT);
4253 unsigned NumRegs = getNumRegisters(VT);
4254 for (unsigned i = 0; i != NumRegs; ++i) {
4255 RetVals.push_back(RegisterVT);
4256 ISD::ArgFlagsTy MyFlags = Flags;
4257 if (NumRegs > 1 && i == 0)
4259 // if it isn't first piece, alignment must be 1
4261 MyFlags.setOrigAlign(1);
4262 Ops.push_back(DAG.getArgFlags(MyFlags));
4266 RetVals.push_back(MVT::Other);
4269 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4270 DAG.getVTList(&RetVals[0], RetVals.size()),
4271 &Ops[0], Ops.size()).Val;
4273 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4274 // allows exposing the loads that may be part of the argument access to the
4275 // first DAGCombiner pass.
4276 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4278 // The number of results should match up, except that the lowered one may have
4279 // an extra flag result.
4280 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4281 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4282 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4283 && "Lowering produced unexpected number of results!");
4284 Result = TmpRes.Val;
4286 unsigned NumArgRegs = Result->getNumValues() - 1;
4287 DAG.setRoot(SDOperand(Result, NumArgRegs));
4289 // Set up the return result vector.
4293 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4295 MVT::ValueType VT = getValueType(I->getType());
4296 MVT::ValueType PartVT = getRegisterType(VT);
4298 unsigned NumParts = getNumRegisters(VT);
4299 SmallVector<SDOperand, 4> Parts(NumParts);
4300 for (unsigned j = 0; j != NumParts; ++j)
4301 Parts[j] = SDOperand(Result, i++);
4303 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4304 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4305 AssertOp = ISD::AssertSext;
4306 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4307 AssertOp = ISD::AssertZext;
4309 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4312 assert(i == NumArgRegs && "Argument register count mismatch!");
4317 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4318 /// implementation, which just inserts an ISD::CALL node, which is later custom
4319 /// lowered by the target to something concrete. FIXME: When all targets are
4320 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4321 std::pair<SDOperand, SDOperand>
4322 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4323 bool RetSExt, bool RetZExt, bool isVarArg,
4324 unsigned CallingConv, bool isTailCall,
4326 ArgListTy &Args, SelectionDAG &DAG) {
4327 SmallVector<SDOperand, 32> Ops;
4328 Ops.push_back(Chain); // Op#0 - Chain
4329 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4330 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4331 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4332 Ops.push_back(Callee);
4334 // Handle all of the outgoing arguments.
4335 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4336 MVT::ValueType VT = getValueType(Args[i].Ty);
4337 SDOperand Op = Args[i].Node;
4338 ISD::ArgFlagsTy Flags;
4339 unsigned OriginalAlignment =
4340 getTargetData()->getABITypeAlignment(Args[i].Ty);
4346 if (Args[i].isInReg)
4350 if (Args[i].isByVal) {
4352 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4353 const Type *ElementTy = Ty->getElementType();
4354 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4355 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4356 // For ByVal, alignment should come from FE. BE will guess if this
4357 // info is not there but there are cases it cannot get right.
4358 if (Args[i].Alignment)
4359 FrameAlign = Args[i].Alignment;
4360 Flags.setByValAlign(FrameAlign);
4361 Flags.setByValSize(FrameSize);
4365 Flags.setOrigAlign(OriginalAlignment);
4367 MVT::ValueType PartVT = getRegisterType(VT);
4368 unsigned NumParts = getNumRegisters(VT);
4369 SmallVector<SDOperand, 4> Parts(NumParts);
4370 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4373 ExtendKind = ISD::SIGN_EXTEND;
4374 else if (Args[i].isZExt)
4375 ExtendKind = ISD::ZERO_EXTEND;
4377 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4379 for (unsigned i = 0; i != NumParts; ++i) {
4380 // if it isn't first piece, alignment must be 1
4381 ISD::ArgFlagsTy MyFlags = Flags;
4382 if (NumParts > 1 && i == 0)
4385 MyFlags.setOrigAlign(1);
4387 Ops.push_back(Parts[i]);
4388 Ops.push_back(DAG.getArgFlags(MyFlags));
4392 // Figure out the result value types. We start by making a list of
4393 // the potentially illegal return value types.
4394 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4395 SmallVector<MVT::ValueType, 4> RetTys;
4396 ComputeValueVTs(*this, RetTy, RetTys);
4398 // Then we translate that to a list of legal types.
4399 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4400 MVT::ValueType VT = RetTys[I];
4401 MVT::ValueType RegisterVT = getRegisterType(VT);
4402 unsigned NumRegs = getNumRegisters(VT);
4403 for (unsigned i = 0; i != NumRegs; ++i)
4404 LoweredRetTys.push_back(RegisterVT);
4407 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4409 // Create the CALL node.
4410 SDOperand Res = DAG.getNode(ISD::CALL,
4411 DAG.getVTList(&LoweredRetTys[0],
4412 LoweredRetTys.size()),
4413 &Ops[0], Ops.size());
4414 Chain = Res.getValue(LoweredRetTys.size() - 1);
4416 // Gather up the call result into a single value.
4417 if (RetTy != Type::VoidTy) {
4418 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4421 AssertOp = ISD::AssertSext;
4423 AssertOp = ISD::AssertZext;
4425 SmallVector<SDOperand, 4> ReturnValues;
4427 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4428 MVT::ValueType VT = RetTys[I];
4429 MVT::ValueType RegisterVT = getRegisterType(VT);
4430 unsigned NumRegs = getNumRegisters(VT);
4431 unsigned RegNoEnd = NumRegs + RegNo;
4432 SmallVector<SDOperand, 4> Results;
4433 for (; RegNo != RegNoEnd; ++RegNo)
4434 Results.push_back(Res.getValue(RegNo));
4435 SDOperand ReturnValue =
4436 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4438 ReturnValues.push_back(ReturnValue);
4440 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4441 DAG.getNode(ISD::MERGE_VALUES,
4442 DAG.getVTList(&RetTys[0], RetTys.size()),
4443 &ReturnValues[0], ReturnValues.size());
4446 return std::make_pair(Res, Chain);
4449 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4450 assert(0 && "LowerOperation not implemented for this target!");
4455 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4456 SelectionDAG &DAG) {
4457 assert(0 && "CustomPromoteOperation not implemented for this target!");
4462 //===----------------------------------------------------------------------===//
4463 // SelectionDAGISel code
4464 //===----------------------------------------------------------------------===//
4466 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4467 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4470 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4471 AU.addRequired<AliasAnalysis>();
4472 AU.addRequired<CollectorModuleMetadata>();
4473 AU.setPreservesAll();
4478 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4479 // Get alias analysis for load/store combining.
4480 AA = &getAnalysis<AliasAnalysis>();
4482 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4483 if (MF.getFunction()->hasCollector())
4484 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4487 RegInfo = &MF.getRegInfo();
4488 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4490 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4492 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4493 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4494 // Mark landing pad.
4495 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4497 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4498 SelectBasicBlock(I, MF, FuncInfo);
4500 // Add function live-ins to entry block live-in set.
4501 BasicBlock *EntryBB = &Fn.getEntryBlock();
4502 BB = FuncInfo.MBBMap[EntryBB];
4503 if (!RegInfo->livein_empty())
4504 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4505 E = RegInfo->livein_end(); I != E; ++I)
4506 BB->addLiveIn(I->first);
4509 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4510 "Not all catch info was assigned to a landing pad!");
4516 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4518 SDOperand Op = getValue(V);
4519 assert((Op.getOpcode() != ISD::CopyFromReg ||
4520 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4521 "Copy from a reg to the same reg!");
4522 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4524 RegsForValue RFV(TLI, Reg, V->getType());
4525 SDOperand Chain = DAG.getEntryNode();
4526 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4527 PendingExports.push_back(Chain);
4530 void SelectionDAGISel::
4531 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4532 // If this is the entry block, emit arguments.
4533 Function &F = *LLVMBB->getParent();
4534 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4535 SDOperand OldRoot = SDL.DAG.getRoot();
4536 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4539 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4541 if (!AI->use_empty()) {
4542 SDL.setValue(AI, Args[a]);
4544 // If this argument is live outside of the entry block, insert a copy from
4545 // whereever we got it to the vreg that other BB's will reference it as.
4546 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4547 if (VMI != FuncInfo.ValueMap.end()) {
4548 SDL.CopyValueToVirtualRegister(AI, VMI->second);
4552 // Finally, if the target has anything special to do, allow it to do so.
4553 // FIXME: this should insert code into the DAG!
4554 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4557 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4558 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4559 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4560 if (isSelector(I)) {
4561 // Apply the catch info to DestBB.
4562 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4564 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4565 FLI.CatchInfoFound.insert(I);
4570 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
4571 /// DAG and fixes their tailcall attribute operand.
4572 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4573 TargetLowering& TLI) {
4574 SDNode * Ret = NULL;
4575 SDOperand Terminator = DAG.getRoot();
4578 if (Terminator.getOpcode() == ISD::RET) {
4579 Ret = Terminator.Val;
4582 // Fix tail call attribute of CALL nodes.
4583 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4584 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4585 if (BI->getOpcode() == ISD::CALL) {
4586 SDOperand OpRet(Ret, 0);
4587 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4588 bool isMarkedTailCall =
4589 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4590 // If CALL node has tail call attribute set to true and the call is not
4591 // eligible (no RET or the target rejects) the attribute is fixed to
4592 // false. The TargetLowering::IsEligibleForTailCallOptimization function
4593 // must correctly identify tail call optimizable calls.
4594 if (isMarkedTailCall &&
4596 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) {
4597 SmallVector<SDOperand, 32> Ops;
4599 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4600 E=OpCall.Val->op_end(); I!=E; I++, idx++) {
4604 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4606 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4612 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4613 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4614 FunctionLoweringInfo &FuncInfo) {
4615 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
4617 // Lower any arguments needed in this block if this is the entry block.
4618 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4619 LowerArguments(LLVMBB, SDL);
4621 BB = FuncInfo.MBBMap[LLVMBB];
4622 SDL.setCurrentBasicBlock(BB);
4624 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4626 if (MMI && BB->isLandingPad()) {
4627 // Add a label to mark the beginning of the landing pad. Deletion of the
4628 // landing pad can thus be detected via the MachineModuleInfo.
4629 unsigned LabelID = MMI->addLandingPad(BB);
4630 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4631 DAG.getConstant(LabelID, MVT::i32),
4632 DAG.getConstant(1, MVT::i32)));
4634 // Mark exception register as live in.
4635 unsigned Reg = TLI.getExceptionAddressRegister();
4636 if (Reg) BB->addLiveIn(Reg);
4638 // Mark exception selector register as live in.
4639 Reg = TLI.getExceptionSelectorRegister();
4640 if (Reg) BB->addLiveIn(Reg);
4642 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4643 // function and list of typeids logically belong to the invoke (or, if you
4644 // like, the basic block containing the invoke), and need to be associated
4645 // with it in the dwarf exception handling tables. Currently however the
4646 // information is provided by an intrinsic (eh.selector) that can be moved
4647 // to unexpected places by the optimizers: if the unwind edge is critical,
4648 // then breaking it can result in the intrinsics being in the successor of
4649 // the landing pad, not the landing pad itself. This results in exceptions
4650 // not being caught because no typeids are associated with the invoke.
4651 // This may not be the only way things can go wrong, but it is the only way
4652 // we try to work around for the moment.
4653 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4655 if (Br && Br->isUnconditional()) { // Critical edge?
4656 BasicBlock::iterator I, E;
4657 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4662 // No catch info found - try to extract some from the successor.
4663 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
4667 // Lower all of the non-terminator instructions.
4668 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4672 // Ensure that all instructions which are used outside of their defining
4673 // blocks are available as virtual registers. Invoke is handled elsewhere.
4674 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4675 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
4676 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4677 if (VMI != FuncInfo.ValueMap.end())
4678 SDL.CopyValueToVirtualRegister(I, VMI->second);
4681 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4682 // ensure constants are generated when needed. Remember the virtual registers
4683 // that need to be added to the Machine PHI nodes as input. We cannot just
4684 // directly add them, because expansion might result in multiple MBB's for one
4685 // BB. As such, the start of the BB might correspond to a different MBB than
4688 TerminatorInst *TI = LLVMBB->getTerminator();
4690 // Emit constants only once even if used by multiple PHI nodes.
4691 std::map<Constant*, unsigned> ConstantsOut;
4693 // Vector bool would be better, but vector<bool> is really slow.
4694 std::vector<unsigned char> SuccsHandled;
4695 if (TI->getNumSuccessors())
4696 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4698 // Check successor nodes' PHI nodes that expect a constant to be available
4700 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4701 BasicBlock *SuccBB = TI->getSuccessor(succ);
4702 if (!isa<PHINode>(SuccBB->begin())) continue;
4703 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4705 // If this terminator has multiple identical successors (common for
4706 // switches), only handle each succ once.
4707 unsigned SuccMBBNo = SuccMBB->getNumber();
4708 if (SuccsHandled[SuccMBBNo]) continue;
4709 SuccsHandled[SuccMBBNo] = true;
4711 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4714 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4715 // nodes and Machine PHI nodes, but the incoming operands have not been
4717 for (BasicBlock::iterator I = SuccBB->begin();
4718 (PN = dyn_cast<PHINode>(I)); ++I) {
4719 // Ignore dead phi's.
4720 if (PN->use_empty()) continue;
4723 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4725 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4726 unsigned &RegOut = ConstantsOut[C];
4728 RegOut = FuncInfo.CreateRegForValue(C);
4729 SDL.CopyValueToVirtualRegister(C, RegOut);
4733 Reg = FuncInfo.ValueMap[PHIOp];
4735 assert(isa<AllocaInst>(PHIOp) &&
4736 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4737 "Didn't codegen value into a register!??");
4738 Reg = FuncInfo.CreateRegForValue(PHIOp);
4739 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
4743 // Remember that this register needs to added to the machine PHI node as
4744 // the input for this MBB.
4745 MVT::ValueType VT = TLI.getValueType(PN->getType());
4746 unsigned NumRegisters = TLI.getNumRegisters(VT);
4747 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4748 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4751 ConstantsOut.clear();
4753 // Lower the terminator after the copies are emitted.
4754 SDL.visit(*LLVMBB->getTerminator());
4756 // Copy over any CaseBlock records that may now exist due to SwitchInst
4757 // lowering, as well as any jump table information.
4758 SwitchCases.clear();
4759 SwitchCases = SDL.SwitchCases;
4761 JTCases = SDL.JTCases;
4762 BitTestCases.clear();
4763 BitTestCases = SDL.BitTestCases;
4765 // Make sure the root of the DAG is up-to-date.
4766 DAG.setRoot(SDL.getControlRoot());
4768 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4769 // with correct tailcall attribute so that the target can rely on the tailcall
4770 // attribute indicating whether the call is really eligible for tail call
4772 CheckDAGForTailCallsAndFixThem(DAG, TLI);
4775 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4776 DOUT << "Lowered selection DAG:\n";
4779 // Run the DAG combiner in pre-legalize mode.
4780 DAG.Combine(false, *AA);
4782 DOUT << "Optimized lowered selection DAG:\n";
4785 // Second step, hack on the DAG until it only uses operations and types that
4786 // the target supports.
4787 #if 0 // Enable this some day.
4788 DAG.LegalizeTypes();
4789 // Someday even later, enable a dag combine pass here.
4793 DOUT << "Legalized selection DAG:\n";
4796 // Run the DAG combiner in post-legalize mode.
4797 DAG.Combine(true, *AA);
4799 DOUT << "Optimized legalized selection DAG:\n";
4802 if (ViewISelDAGs) DAG.viewGraph();
4804 // Third, instruction select all of the operations to machine code, adding the
4805 // code to the MachineBasicBlock.
4806 InstructionSelectBasicBlock(DAG);
4808 DOUT << "Selected machine code:\n";
4812 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4813 FunctionLoweringInfo &FuncInfo) {
4814 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4816 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4819 // First step, lower LLVM code to some DAG. This DAG may use operations and
4820 // types that are not supported by the target.
4821 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4823 // Second step, emit the lowered DAG as machine code.
4824 CodeGenAndEmitDAG(DAG);
4827 DOUT << "Total amount of phi nodes to update: "
4828 << PHINodesToUpdate.size() << "\n";
4829 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4830 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4831 << ", " << PHINodesToUpdate[i].second << ")\n";);
4833 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4834 // PHI nodes in successors.
4835 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4836 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4837 MachineInstr *PHI = PHINodesToUpdate[i].first;
4838 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4839 "This is not a machine PHI node that we are updating!");
4840 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4842 PHI->addOperand(MachineOperand::CreateMBB(BB));
4847 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4848 // Lower header first, if it wasn't already lowered
4849 if (!BitTestCases[i].Emitted) {
4850 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4852 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
4853 // Set the current basic block to the mbb we wish to insert the code into
4854 BB = BitTestCases[i].Parent;
4855 HSDL.setCurrentBasicBlock(BB);
4857 HSDL.visitBitTestHeader(BitTestCases[i]);
4858 HSDAG.setRoot(HSDL.getRoot());
4859 CodeGenAndEmitDAG(HSDAG);
4862 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4863 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4865 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
4866 // Set the current basic block to the mbb we wish to insert the code into
4867 BB = BitTestCases[i].Cases[j].ThisBB;
4868 BSDL.setCurrentBasicBlock(BB);
4871 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4872 BitTestCases[i].Reg,
4873 BitTestCases[i].Cases[j]);
4875 BSDL.visitBitTestCase(BitTestCases[i].Default,
4876 BitTestCases[i].Reg,
4877 BitTestCases[i].Cases[j]);
4880 BSDAG.setRoot(BSDL.getRoot());
4881 CodeGenAndEmitDAG(BSDAG);
4885 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4886 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4887 MachineBasicBlock *PHIBB = PHI->getParent();
4888 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4889 "This is not a machine PHI node that we are updating!");
4890 // This is "default" BB. We have two jumps to it. From "header" BB and
4891 // from last "case" BB.
4892 if (PHIBB == BitTestCases[i].Default) {
4893 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4895 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
4896 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4898 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
4901 // One of "cases" BB.
4902 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4903 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4904 if (cBB->succ_end() !=
4905 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4906 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4908 PHI->addOperand(MachineOperand::CreateMBB(cBB));
4914 // If the JumpTable record is filled in, then we need to emit a jump table.
4915 // Updating the PHI nodes is tricky in this case, since we need to determine
4916 // whether the PHI is a successor of the range check MBB or the jump table MBB
4917 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4918 // Lower header first, if it wasn't already lowered
4919 if (!JTCases[i].first.Emitted) {
4920 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4922 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
4923 // Set the current basic block to the mbb we wish to insert the code into
4924 BB = JTCases[i].first.HeaderBB;
4925 HSDL.setCurrentBasicBlock(BB);
4927 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4928 HSDAG.setRoot(HSDL.getRoot());
4929 CodeGenAndEmitDAG(HSDAG);
4932 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4934 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
4935 // Set the current basic block to the mbb we wish to insert the code into
4936 BB = JTCases[i].second.MBB;
4937 JSDL.setCurrentBasicBlock(BB);
4939 JSDL.visitJumpTable(JTCases[i].second);
4940 JSDAG.setRoot(JSDL.getRoot());
4941 CodeGenAndEmitDAG(JSDAG);
4944 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4945 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4946 MachineBasicBlock *PHIBB = PHI->getParent();
4947 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4948 "This is not a machine PHI node that we are updating!");
4949 // "default" BB. We can go there only from header BB.
4950 if (PHIBB == JTCases[i].second.Default) {
4951 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4953 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
4955 // JT BB. Just iterate over successors here
4956 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4957 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4959 PHI->addOperand(MachineOperand::CreateMBB(BB));
4964 // If the switch block involved a branch to one of the actual successors, we
4965 // need to update PHI nodes in that block.
4966 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4967 MachineInstr *PHI = PHINodesToUpdate[i].first;
4968 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4969 "This is not a machine PHI node that we are updating!");
4970 if (BB->isSuccessor(PHI->getParent())) {
4971 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4973 PHI->addOperand(MachineOperand::CreateMBB(BB));
4977 // If we generated any switch lowering information, build and codegen any
4978 // additional DAGs necessary.
4979 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4980 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4982 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
4984 // Set the current basic block to the mbb we wish to insert the code into
4985 BB = SwitchCases[i].ThisBB;
4986 SDL.setCurrentBasicBlock(BB);
4989 SDL.visitSwitchCase(SwitchCases[i]);
4990 SDAG.setRoot(SDL.getRoot());
4991 CodeGenAndEmitDAG(SDAG);
4993 // Handle any PHI nodes in successors of this chunk, as if we were coming
4994 // from the original BB before switch expansion. Note that PHI nodes can
4995 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4996 // handle them the right number of times.
4997 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4998 for (MachineBasicBlock::iterator Phi = BB->begin();
4999 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5000 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5001 for (unsigned pn = 0; ; ++pn) {
5002 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5003 if (PHINodesToUpdate[pn].first == Phi) {
5004 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5006 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5012 // Don't process RHS if same block as LHS.
5013 if (BB == SwitchCases[i].FalseBB)
5014 SwitchCases[i].FalseBB = 0;
5016 // If we haven't handled the RHS, do so now. Otherwise, we're done.
5017 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5018 SwitchCases[i].FalseBB = 0;
5020 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5025 //===----------------------------------------------------------------------===//
5026 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5027 /// target node in the graph.
5028 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5029 if (ViewSchedDAGs) DAG.viewGraph();
5031 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5035 RegisterScheduler::setDefault(Ctor);
5038 ScheduleDAG *SL = Ctor(this, &DAG, BB);
5041 if (ViewSUnitDAGs) SL->viewGraph();
5047 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5048 return new HazardRecognizer();
5051 //===----------------------------------------------------------------------===//
5052 // Helper functions used by the generated instruction selector.
5053 //===----------------------------------------------------------------------===//
5054 // Calls to these methods are generated by tblgen.
5056 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
5057 /// the dag combiner simplified the 255, we still want to match. RHS is the
5058 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5059 /// specified in the .td file (e.g. 255).
5060 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5061 int64_t DesiredMaskS) const {
5062 const APInt &ActualMask = RHS->getAPIntValue();
5063 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5065 // If the actual mask exactly matches, success!
5066 if (ActualMask == DesiredMask)
5069 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5070 if (ActualMask.intersects(~DesiredMask))
5073 // Otherwise, the DAG Combiner may have proven that the value coming in is
5074 // either already zero or is not demanded. Check for known zero input bits.
5075 APInt NeededMask = DesiredMask & ~ActualMask;
5076 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5079 // TODO: check to see if missing bits are just not demanded.
5081 // Otherwise, this pattern doesn't match.
5085 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
5086 /// the dag combiner simplified the 255, we still want to match. RHS is the
5087 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5088 /// specified in the .td file (e.g. 255).
5089 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5090 int64_t DesiredMaskS) const {
5091 const APInt &ActualMask = RHS->getAPIntValue();
5092 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5094 // If the actual mask exactly matches, success!
5095 if (ActualMask == DesiredMask)
5098 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5099 if (ActualMask.intersects(~DesiredMask))
5102 // Otherwise, the DAG Combiner may have proven that the value coming in is
5103 // either already zero or is not demanded. Check for known zero input bits.
5104 APInt NeededMask = DesiredMask & ~ActualMask;
5106 APInt KnownZero, KnownOne;
5107 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5109 // If all the missing bits in the or are already known to be set, match!
5110 if ((NeededMask & KnownOne) == NeededMask)
5113 // TODO: check to see if missing bits are just not demanded.
5115 // Otherwise, this pattern doesn't match.
5120 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5121 /// by tblgen. Others should not call it.
5122 void SelectionDAGISel::
5123 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5124 std::vector<SDOperand> InOps;
5125 std::swap(InOps, Ops);
5127 Ops.push_back(InOps[0]); // input chain.
5128 Ops.push_back(InOps[1]); // input asm string.
5130 unsigned i = 2, e = InOps.size();
5131 if (InOps[e-1].getValueType() == MVT::Flag)
5132 --e; // Don't process a flag operand if it is here.
5135 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5136 if ((Flags & 7) != 4 /*MEM*/) {
5137 // Just skip over this operand, copying the operands verbatim.
5138 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5139 i += (Flags >> 3) + 1;
5141 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5142 // Otherwise, this is a memory operand. Ask the target to select it.
5143 std::vector<SDOperand> SelOps;
5144 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5145 cerr << "Could not match memory address. Inline asm failure!\n";
5149 // Add this to the output node.
5150 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5151 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5153 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5158 // Add the flag input back if present.
5159 if (e != InOps.size())
5160 Ops.push_back(InOps.back());
5163 char SelectionDAGISel::ID = 0;