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; }
92 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
93 /// MVT::ValueTypes that represent all the individual underlying
94 /// non-aggregate types that comprise it.
95 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
96 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
97 // Given a struct type, recursively traverse the elements.
98 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
99 for (StructType::element_iterator EI = STy->element_begin(),
100 EB = STy->element_end();
102 ComputeValueVTs(TLI, *EI, ValueVTs);
105 // Given an array type, recursively traverse the elements.
106 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
107 const Type *EltTy = ATy->getElementType();
108 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
109 ComputeValueVTs(TLI, EltTy, ValueVTs);
112 // Base case: we can get an MVT::ValueType for this LLVM IR type.
113 ValueVTs.push_back(TLI.getValueType(Ty));
117 /// RegsForValue - This struct represents the registers (physical or virtual)
118 /// that a particular set of values is assigned, and the type information about
119 /// the value. The most common situation is to represent one value at a time,
120 /// but struct or array values are handled element-wise as multiple values.
121 /// The splitting of aggregates is performed recursively, so that we never
122 /// have aggregate-typed registers. The values at this point do not necessarily
123 /// have legal types, so each value may require one or more registers of some
126 struct VISIBILITY_HIDDEN RegsForValue {
127 /// TLI - The TargetLowering object.
129 const TargetLowering *TLI;
131 /// ValueVTs - The value types of the values, which may not be legal, and
132 /// may need be promoted or synthesized from one or more registers.
134 SmallVector<MVT::ValueType, 4> ValueVTs;
136 /// RegVTs - The value types of the registers. This is the same size as
137 /// ValueVTs and it records, for each value, what the type of the assigned
138 /// register or registers are. (Individual values are never synthesized
139 /// from more than one type of register.)
141 /// With virtual registers, the contents of RegVTs is redundant with TLI's
142 /// getRegisterType member function, however when with physical registers
143 /// it is necessary to have a separate record of the types.
145 SmallVector<MVT::ValueType, 4> RegVTs;
147 /// Regs - This list holds the registers assigned to the values.
148 /// Each legal or promoted value requires one register, and each
149 /// expanded value requires multiple registers.
151 SmallVector<unsigned, 4> Regs;
153 RegsForValue() : TLI(0) {}
155 RegsForValue(const TargetLowering &tli,
156 unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
157 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(1, Reg) {}
158 RegsForValue(const TargetLowering &tli,
159 const SmallVector<unsigned, 4> ®s,
160 MVT::ValueType regvt, MVT::ValueType valuevt)
161 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
162 RegsForValue(const TargetLowering &tli,
163 const SmallVector<unsigned, 4> ®s,
164 const SmallVector<MVT::ValueType, 4> ®vts,
165 const SmallVector<MVT::ValueType, 4> &valuevts)
166 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
167 RegsForValue(const TargetLowering &tli,
168 unsigned Reg, const Type *Ty) : TLI(&tli) {
169 ComputeValueVTs(tli, Ty, ValueVTs);
171 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
172 MVT::ValueType ValueVT = ValueVTs[Value];
173 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
174 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
175 for (unsigned i = 0; i != NumRegs; ++i)
176 Regs.push_back(Reg + i);
177 RegVTs.push_back(RegisterVT);
182 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
183 /// this value and returns the result as a ValueVTs value. This uses
184 /// Chain/Flag as the input and updates them for the output Chain/Flag.
185 /// If the Flag pointer is NULL, no flag is used.
186 SDOperand getCopyFromRegs(SelectionDAG &DAG,
187 SDOperand &Chain, SDOperand *Flag) const;
189 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
190 /// specified value into the registers specified by this object. This uses
191 /// Chain/Flag as the input and updates them for the output Chain/Flag.
192 /// If the Flag pointer is NULL, no flag is used.
193 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
194 SDOperand &Chain, SDOperand *Flag) const;
196 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
197 /// operand list. This adds the code marker and includes the number of
198 /// values added into it.
199 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
200 std::vector<SDOperand> &Ops) const;
205 //===--------------------------------------------------------------------===//
206 /// createDefaultScheduler - This creates an instruction scheduler appropriate
208 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
210 MachineBasicBlock *BB) {
211 TargetLowering &TLI = IS->getTargetLowering();
213 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
214 return createTDListDAGScheduler(IS, DAG, BB);
216 assert(TLI.getSchedulingPreference() ==
217 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
218 return createBURRListDAGScheduler(IS, DAG, BB);
223 //===--------------------------------------------------------------------===//
224 /// FunctionLoweringInfo - This contains information that is global to a
225 /// function that is used when lowering a region of the function.
226 class FunctionLoweringInfo {
231 MachineRegisterInfo &RegInfo;
233 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
235 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
236 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
238 /// ValueMap - Since we emit code for the function a basic block at a time,
239 /// we must remember which virtual registers hold the values for
240 /// cross-basic-block values.
241 DenseMap<const Value*, unsigned> ValueMap;
243 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
244 /// the entry block. This allows the allocas to be efficiently referenced
245 /// anywhere in the function.
246 std::map<const AllocaInst*, int> StaticAllocaMap;
249 SmallSet<Instruction*, 8> CatchInfoLost;
250 SmallSet<Instruction*, 8> CatchInfoFound;
253 unsigned MakeReg(MVT::ValueType VT) {
254 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
257 /// isExportedInst - Return true if the specified value is an instruction
258 /// exported from its block.
259 bool isExportedInst(const Value *V) {
260 return ValueMap.count(V);
263 unsigned CreateRegForValue(const Value *V);
265 unsigned InitializeRegForValue(const Value *V) {
266 unsigned &R = ValueMap[V];
267 assert(R == 0 && "Already initialized this value register!");
268 return R = CreateRegForValue(V);
273 /// isSelector - Return true if this instruction is a call to the
274 /// eh.selector intrinsic.
275 static bool isSelector(Instruction *I) {
276 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
277 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
278 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
282 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
283 /// PHI nodes or outside of the basic block that defines it, or used by a
284 /// switch or atomic instruction, which may expand to multiple basic blocks.
285 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
286 if (isa<PHINode>(I)) return true;
287 BasicBlock *BB = I->getParent();
288 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
289 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
290 // FIXME: Remove switchinst special case.
291 isa<SwitchInst>(*UI))
296 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
297 /// entry block, return true. This includes arguments used by switches, since
298 /// the switch may expand into multiple basic blocks.
299 static bool isOnlyUsedInEntryBlock(Argument *A) {
300 BasicBlock *Entry = A->getParent()->begin();
301 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
302 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
303 return false; // Use not in entry block.
307 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
308 Function &fn, MachineFunction &mf)
309 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
311 // Create a vreg for each argument register that is not dead and is used
312 // outside of the entry block for the function.
313 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
315 if (!isOnlyUsedInEntryBlock(AI))
316 InitializeRegForValue(AI);
318 // Initialize the mapping of values to registers. This is only set up for
319 // instruction values that are used outside of the block that defines
321 Function::iterator BB = Fn.begin(), EB = Fn.end();
322 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
323 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
324 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
325 const Type *Ty = AI->getAllocatedType();
326 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
328 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
331 TySize *= CUI->getZExtValue(); // Get total allocated size.
332 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
333 StaticAllocaMap[AI] =
334 MF.getFrameInfo()->CreateStackObject(TySize, Align);
337 for (; BB != EB; ++BB)
338 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
339 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
340 if (!isa<AllocaInst>(I) ||
341 !StaticAllocaMap.count(cast<AllocaInst>(I)))
342 InitializeRegForValue(I);
344 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
345 // also creates the initial PHI MachineInstrs, though none of the input
346 // operands are populated.
347 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
348 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
350 MF.getBasicBlockList().push_back(MBB);
352 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
355 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
356 if (PN->use_empty()) continue;
358 MVT::ValueType VT = TLI.getValueType(PN->getType());
359 unsigned NumRegisters = TLI.getNumRegisters(VT);
360 unsigned PHIReg = ValueMap[PN];
361 assert(PHIReg && "PHI node does not have an assigned virtual register!");
362 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
363 for (unsigned i = 0; i != NumRegisters; ++i)
364 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
369 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
370 /// the correctly promoted or expanded types. Assign these registers
371 /// consecutive vreg numbers and return the first assigned number.
373 /// In the case that the given value has struct or array type, this function
374 /// will assign registers for each member or element.
376 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
377 SmallVector<MVT::ValueType, 4> ValueVTs;
378 ComputeValueVTs(TLI, V->getType(), ValueVTs);
380 unsigned FirstReg = 0;
381 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
382 MVT::ValueType ValueVT = ValueVTs[Value];
383 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
385 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
386 for (unsigned i = 0; i != NumRegs; ++i) {
387 unsigned R = MakeReg(RegisterVT);
388 if (!FirstReg) FirstReg = R;
394 //===----------------------------------------------------------------------===//
395 /// SelectionDAGLowering - This is the common target-independent lowering
396 /// implementation that is parameterized by a TargetLowering object.
397 /// Also, targets can overload any lowering method.
400 class SelectionDAGLowering {
401 MachineBasicBlock *CurMBB;
403 DenseMap<const Value*, SDOperand> NodeMap;
405 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
406 /// them up and then emit token factor nodes when possible. This allows us to
407 /// get simple disambiguation between loads without worrying about alias
409 std::vector<SDOperand> PendingLoads;
411 /// PendingExports - CopyToReg nodes that copy values to virtual registers
412 /// for export to other blocks need to be emitted before any terminator
413 /// instruction, but they have no other ordering requirements. We bunch them
414 /// up and the emit a single tokenfactor for them just before terminator
416 std::vector<SDOperand> PendingExports;
418 /// Case - A struct to record the Value for a switch case, and the
419 /// case's target basic block.
423 MachineBasicBlock* BB;
425 Case() : Low(0), High(0), BB(0) { }
426 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
427 Low(low), High(high), BB(bb) { }
428 uint64_t size() const {
429 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
430 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
431 return (rHigh - rLow + 1ULL);
437 MachineBasicBlock* BB;
440 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
441 Mask(mask), BB(bb), Bits(bits) { }
444 typedef std::vector<Case> CaseVector;
445 typedef std::vector<CaseBits> CaseBitsVector;
446 typedef CaseVector::iterator CaseItr;
447 typedef std::pair<CaseItr, CaseItr> CaseRange;
449 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
450 /// of conditional branches.
452 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
453 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
455 /// CaseBB - The MBB in which to emit the compare and branch
456 MachineBasicBlock *CaseBB;
457 /// LT, GE - If nonzero, we know the current case value must be less-than or
458 /// greater-than-or-equal-to these Constants.
461 /// Range - A pair of iterators representing the range of case values to be
462 /// processed at this point in the binary search tree.
466 typedef std::vector<CaseRec> CaseRecVector;
468 /// The comparison function for sorting the switch case values in the vector.
469 /// WARNING: Case ranges should be disjoint!
471 bool operator () (const Case& C1, const Case& C2) {
472 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
473 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
474 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
475 return CI1->getValue().slt(CI2->getValue());
480 bool operator () (const CaseBits& C1, const CaseBits& C2) {
481 return C1.Bits > C2.Bits;
485 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
488 // TLI - This is information that describes the available target features we
489 // need for lowering. This indicates when operations are unavailable,
490 // implemented with a libcall, etc.
493 const TargetData *TD;
496 /// SwitchCases - Vector of CaseBlock structures used to communicate
497 /// SwitchInst code generation information.
498 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
499 /// JTCases - Vector of JumpTable structures used to communicate
500 /// SwitchInst code generation information.
501 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
502 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
504 /// FuncInfo - Information about the function as a whole.
506 FunctionLoweringInfo &FuncInfo;
508 /// GCI - Garbage collection metadata for the function.
509 CollectorMetadata *GCI;
511 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
513 FunctionLoweringInfo &funcinfo,
514 CollectorMetadata *gci)
515 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
516 FuncInfo(funcinfo), GCI(gci) {
519 /// getRoot - Return the current virtual root of the Selection DAG,
520 /// flushing any PendingLoad items. This must be done before emitting
521 /// a store or any other node that may need to be ordered after any
522 /// prior load instructions.
524 SDOperand getRoot() {
525 if (PendingLoads.empty())
526 return DAG.getRoot();
528 if (PendingLoads.size() == 1) {
529 SDOperand Root = PendingLoads[0];
531 PendingLoads.clear();
535 // Otherwise, we have to make a token factor node.
536 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
537 &PendingLoads[0], PendingLoads.size());
538 PendingLoads.clear();
543 /// getControlRoot - Similar to getRoot, but instead of flushing all the
544 /// PendingLoad items, flush all the PendingExports items. It is necessary
545 /// to do this before emitting a terminator instruction.
547 SDOperand getControlRoot() {
548 SDOperand Root = DAG.getRoot();
550 if (PendingExports.empty())
553 // Turn all of the CopyToReg chains into one factored node.
554 if (Root.getOpcode() != ISD::EntryToken) {
555 unsigned i = 0, e = PendingExports.size();
556 for (; i != e; ++i) {
557 assert(PendingExports[i].Val->getNumOperands() > 1);
558 if (PendingExports[i].Val->getOperand(0) == Root)
559 break; // Don't add the root if we already indirectly depend on it.
563 PendingExports.push_back(Root);
566 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
568 PendingExports.size());
569 PendingExports.clear();
574 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
576 void visit(Instruction &I) { visit(I.getOpcode(), I); }
578 void visit(unsigned Opcode, User &I) {
579 // Note: this doesn't use InstVisitor, because it has to work with
580 // ConstantExpr's in addition to instructions.
582 default: assert(0 && "Unknown instruction type encountered!");
584 // Build the switch statement using the Instruction.def file.
585 #define HANDLE_INST(NUM, OPCODE, CLASS) \
586 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
587 #include "llvm/Instruction.def"
591 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
593 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
594 const Value *SV, SDOperand Root,
595 bool isVolatile, unsigned Alignment);
597 SDOperand getValue(const Value *V);
599 void setValue(const Value *V, SDOperand NewN) {
600 SDOperand &N = NodeMap[V];
601 assert(N.Val == 0 && "Already set a value for this node!");
605 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
606 std::set<unsigned> &OutputRegs,
607 std::set<unsigned> &InputRegs);
609 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
610 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
612 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
613 void ExportFromCurrentBlock(Value *V);
614 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
615 MachineBasicBlock *LandingPad = NULL);
617 // Terminator instructions.
618 void visitRet(ReturnInst &I);
619 void visitBr(BranchInst &I);
620 void visitSwitch(SwitchInst &I);
621 void visitUnreachable(UnreachableInst &I) { /* noop */ }
623 // Helpers for visitSwitch
624 bool handleSmallSwitchRange(CaseRec& CR,
625 CaseRecVector& WorkList,
627 MachineBasicBlock* Default);
628 bool handleJTSwitchCase(CaseRec& CR,
629 CaseRecVector& WorkList,
631 MachineBasicBlock* Default);
632 bool handleBTSplitSwitchCase(CaseRec& CR,
633 CaseRecVector& WorkList,
635 MachineBasicBlock* Default);
636 bool handleBitTestsSwitchCase(CaseRec& CR,
637 CaseRecVector& WorkList,
639 MachineBasicBlock* Default);
640 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
641 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
642 void visitBitTestCase(MachineBasicBlock* NextMBB,
644 SelectionDAGISel::BitTestCase &B);
645 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
646 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
647 SelectionDAGISel::JumpTableHeader &JTH);
649 // These all get lowered before this pass.
650 void visitInvoke(InvokeInst &I);
651 void visitUnwind(UnwindInst &I);
653 void visitBinary(User &I, unsigned OpCode);
654 void visitShift(User &I, unsigned Opcode);
655 void visitAdd(User &I) {
656 if (I.getType()->isFPOrFPVector())
657 visitBinary(I, ISD::FADD);
659 visitBinary(I, ISD::ADD);
661 void visitSub(User &I);
662 void visitMul(User &I) {
663 if (I.getType()->isFPOrFPVector())
664 visitBinary(I, ISD::FMUL);
666 visitBinary(I, ISD::MUL);
668 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
669 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
670 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
671 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
672 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
673 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
674 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
675 void visitOr (User &I) { visitBinary(I, ISD::OR); }
676 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
677 void visitShl (User &I) { visitShift(I, ISD::SHL); }
678 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
679 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
680 void visitICmp(User &I);
681 void visitFCmp(User &I);
682 // Visit the conversion instructions
683 void visitTrunc(User &I);
684 void visitZExt(User &I);
685 void visitSExt(User &I);
686 void visitFPTrunc(User &I);
687 void visitFPExt(User &I);
688 void visitFPToUI(User &I);
689 void visitFPToSI(User &I);
690 void visitUIToFP(User &I);
691 void visitSIToFP(User &I);
692 void visitPtrToInt(User &I);
693 void visitIntToPtr(User &I);
694 void visitBitCast(User &I);
696 void visitExtractElement(User &I);
697 void visitInsertElement(User &I);
698 void visitShuffleVector(User &I);
700 void visitGetElementPtr(User &I);
701 void visitSelect(User &I);
703 void visitMalloc(MallocInst &I);
704 void visitFree(FreeInst &I);
705 void visitAlloca(AllocaInst &I);
706 void visitLoad(LoadInst &I);
707 void visitStore(StoreInst &I);
708 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
709 void visitCall(CallInst &I);
710 void visitInlineAsm(CallSite CS);
711 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
712 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
714 void visitVAStart(CallInst &I);
715 void visitVAArg(VAArgInst &I);
716 void visitVAEnd(CallInst &I);
717 void visitVACopy(CallInst &I);
719 void visitGetResult(GetResultInst &I);
721 void visitUserOp1(Instruction &I) {
722 assert(0 && "UserOp1 should not exist at instruction selection time!");
725 void visitUserOp2(Instruction &I) {
726 assert(0 && "UserOp2 should not exist at instruction selection time!");
730 } // end namespace llvm
733 /// getCopyFromParts - Create a value that contains the specified legal parts
734 /// combined into the value they represent. If the parts combine to a type
735 /// larger then ValueVT then AssertOp can be used to specify whether the extra
736 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
737 /// (ISD::AssertSext).
738 static SDOperand getCopyFromParts(SelectionDAG &DAG,
739 const SDOperand *Parts,
741 MVT::ValueType PartVT,
742 MVT::ValueType ValueVT,
743 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
744 assert(NumParts > 0 && "No parts to assemble!");
745 TargetLowering &TLI = DAG.getTargetLoweringInfo();
746 SDOperand Val = Parts[0];
749 // Assemble the value from multiple parts.
750 if (!MVT::isVector(ValueVT)) {
751 unsigned PartBits = MVT::getSizeInBits(PartVT);
752 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
754 // Assemble the power of 2 part.
755 unsigned RoundParts = NumParts & (NumParts - 1) ?
756 1 << Log2_32(NumParts) : NumParts;
757 unsigned RoundBits = PartBits * RoundParts;
758 MVT::ValueType RoundVT = RoundBits == ValueBits ?
759 ValueVT : MVT::getIntegerType(RoundBits);
762 if (RoundParts > 2) {
763 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
764 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
765 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
771 if (TLI.isBigEndian())
773 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
775 if (RoundParts < NumParts) {
776 // Assemble the trailing non-power-of-2 part.
777 unsigned OddParts = NumParts - RoundParts;
778 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
779 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
781 // Combine the round and odd parts.
783 if (TLI.isBigEndian())
785 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
786 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
787 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
788 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
789 TLI.getShiftAmountTy()));
790 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
791 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
794 // Handle a multi-element vector.
795 MVT::ValueType IntermediateVT, RegisterVT;
796 unsigned NumIntermediates;
798 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
801 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
802 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
803 assert(RegisterVT == Parts[0].getValueType() &&
804 "Part type doesn't match part!");
806 // Assemble the parts into intermediate operands.
807 SmallVector<SDOperand, 8> Ops(NumIntermediates);
808 if (NumIntermediates == NumParts) {
809 // If the register was not expanded, truncate or copy the value,
811 for (unsigned i = 0; i != NumParts; ++i)
812 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
813 PartVT, IntermediateVT);
814 } else if (NumParts > 0) {
815 // If the intermediate type was expanded, build the intermediate operands
817 assert(NumParts % NumIntermediates == 0 &&
818 "Must expand into a divisible number of parts!");
819 unsigned Factor = NumParts / NumIntermediates;
820 for (unsigned i = 0; i != NumIntermediates; ++i)
821 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
822 PartVT, IntermediateVT);
825 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
827 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
828 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
829 ValueVT, &Ops[0], NumIntermediates);
833 // There is now one part, held in Val. Correct it to match ValueVT.
834 PartVT = Val.getValueType();
836 if (PartVT == ValueVT)
839 if (MVT::isVector(PartVT)) {
840 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
841 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
844 if (MVT::isVector(ValueVT)) {
845 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
846 MVT::getVectorNumElements(ValueVT) == 1 &&
847 "Only trivial scalar-to-vector conversions should get here!");
848 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
851 if (MVT::isInteger(PartVT) &&
852 MVT::isInteger(ValueVT)) {
853 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
854 // For a truncate, see if we have any information to
855 // indicate whether the truncated bits will always be
856 // zero or sign-extension.
857 if (AssertOp != ISD::DELETED_NODE)
858 Val = DAG.getNode(AssertOp, PartVT, Val,
859 DAG.getValueType(ValueVT));
860 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
862 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
866 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
867 if (ValueVT < Val.getValueType())
868 // FP_ROUND's are always exact here.
869 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
870 DAG.getIntPtrConstant(1));
871 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
874 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
875 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
877 assert(0 && "Unknown mismatch!");
881 /// getCopyToParts - Create a series of nodes that contain the specified value
882 /// split into legal parts. If the parts contain more bits than Val, then, for
883 /// integers, ExtendKind can be used to specify how to generate the extra bits.
884 static void getCopyToParts(SelectionDAG &DAG,
888 MVT::ValueType PartVT,
889 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
890 TargetLowering &TLI = DAG.getTargetLoweringInfo();
891 MVT::ValueType PtrVT = TLI.getPointerTy();
892 MVT::ValueType ValueVT = Val.getValueType();
893 unsigned PartBits = MVT::getSizeInBits(PartVT);
894 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
899 if (!MVT::isVector(ValueVT)) {
900 if (PartVT == ValueVT) {
901 assert(NumParts == 1 && "No-op copy with multiple parts!");
906 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
907 // If the parts cover more bits than the value has, promote the value.
908 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
909 assert(NumParts == 1 && "Do not know what to promote to!");
910 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
911 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
912 ValueVT = MVT::getIntegerType(NumParts * PartBits);
913 Val = DAG.getNode(ExtendKind, ValueVT, Val);
915 assert(0 && "Unknown mismatch!");
917 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
918 // Different types of the same size.
919 assert(NumParts == 1 && PartVT != ValueVT);
920 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
921 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
922 // If the parts cover less bits than value has, truncate the value.
923 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
924 ValueVT = MVT::getIntegerType(NumParts * PartBits);
925 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
927 assert(0 && "Unknown mismatch!");
931 // The value may have changed - recompute ValueVT.
932 ValueVT = Val.getValueType();
933 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
934 "Failed to tile the value with PartVT!");
937 assert(PartVT == ValueVT && "Type conversion failed!");
942 // Expand the value into multiple parts.
943 if (NumParts & (NumParts - 1)) {
944 // The number of parts is not a power of 2. Split off and copy the tail.
945 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
946 "Do not know what to expand to!");
947 unsigned RoundParts = 1 << Log2_32(NumParts);
948 unsigned RoundBits = RoundParts * PartBits;
949 unsigned OddParts = NumParts - RoundParts;
950 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
951 DAG.getConstant(RoundBits,
952 TLI.getShiftAmountTy()));
953 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
954 if (TLI.isBigEndian())
955 // The odd parts were reversed by getCopyToParts - unreverse them.
956 std::reverse(Parts + RoundParts, Parts + NumParts);
957 NumParts = RoundParts;
958 ValueVT = MVT::getIntegerType(NumParts * PartBits);
959 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
962 // The number of parts is a power of 2. Repeatedly bisect the value using
964 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
965 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
967 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
968 for (unsigned i = 0; i < NumParts; i += StepSize) {
969 unsigned ThisBits = StepSize * PartBits / 2;
970 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
971 SDOperand &Part0 = Parts[i];
972 SDOperand &Part1 = Parts[i+StepSize/2];
974 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
975 DAG.getConstant(1, PtrVT));
976 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
977 DAG.getConstant(0, PtrVT));
979 if (ThisBits == PartBits && ThisVT != PartVT) {
980 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
981 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
986 if (TLI.isBigEndian())
987 std::reverse(Parts, Parts + NumParts);
994 if (PartVT != ValueVT) {
995 if (MVT::isVector(PartVT)) {
996 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
998 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
999 MVT::getVectorNumElements(ValueVT) == 1 &&
1000 "Only trivial vector-to-scalar conversions should get here!");
1001 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1002 DAG.getConstant(0, PtrVT));
1010 // Handle a multi-element vector.
1011 MVT::ValueType IntermediateVT, RegisterVT;
1012 unsigned NumIntermediates;
1014 DAG.getTargetLoweringInfo()
1015 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1017 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1019 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1020 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1022 // Split the vector into intermediate operands.
1023 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1024 for (unsigned i = 0; i != NumIntermediates; ++i)
1025 if (MVT::isVector(IntermediateVT))
1026 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1027 IntermediateVT, Val,
1028 DAG.getConstant(i * (NumElements / NumIntermediates),
1031 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1032 IntermediateVT, Val,
1033 DAG.getConstant(i, PtrVT));
1035 // Split the intermediate operands into legal parts.
1036 if (NumParts == NumIntermediates) {
1037 // If the register was not expanded, promote or copy the value,
1039 for (unsigned i = 0; i != NumParts; ++i)
1040 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1041 } else if (NumParts > 0) {
1042 // If the intermediate type was expanded, split each the value into
1044 assert(NumParts % NumIntermediates == 0 &&
1045 "Must expand into a divisible number of parts!");
1046 unsigned Factor = NumParts / NumIntermediates;
1047 for (unsigned i = 0; i != NumIntermediates; ++i)
1048 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1053 SDOperand SelectionDAGLowering::getValue(const Value *V) {
1054 SDOperand &N = NodeMap[V];
1055 if (N.Val) return N;
1057 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1058 MVT::ValueType VT = TLI.getValueType(V->getType(), true);
1060 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1061 return N = DAG.getConstant(CI->getValue(), VT);
1063 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1064 return N = DAG.getGlobalAddress(GV, VT);
1066 if (isa<ConstantPointerNull>(C))
1067 return N = DAG.getConstant(0, TLI.getPointerTy());
1069 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1070 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1072 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1073 return N = DAG.getNode(ISD::UNDEF, VT);
1075 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1076 visit(CE->getOpcode(), *CE);
1077 SDOperand N1 = NodeMap[V];
1078 assert(N1.Val && "visit didn't populate the ValueMap!");
1082 const VectorType *VecTy = cast<VectorType>(V->getType());
1083 unsigned NumElements = VecTy->getNumElements();
1085 // Now that we know the number and type of the elements, get that number of
1086 // elements into the Ops array based on what kind of constant it is.
1087 SmallVector<SDOperand, 16> Ops;
1088 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1089 for (unsigned i = 0; i != NumElements; ++i)
1090 Ops.push_back(getValue(CP->getOperand(i)));
1092 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1093 "Unknown vector constant!");
1094 MVT::ValueType EltVT = TLI.getValueType(VecTy->getElementType());
1097 if (isa<UndefValue>(C))
1098 Op = DAG.getNode(ISD::UNDEF, EltVT);
1099 else if (MVT::isFloatingPoint(EltVT))
1100 Op = DAG.getConstantFP(0, EltVT);
1102 Op = DAG.getConstant(0, EltVT);
1103 Ops.assign(NumElements, Op);
1106 // Create a BUILD_VECTOR node.
1107 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1110 // If this is a static alloca, generate it as the frameindex instead of
1112 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1113 std::map<const AllocaInst*, int>::iterator SI =
1114 FuncInfo.StaticAllocaMap.find(AI);
1115 if (SI != FuncInfo.StaticAllocaMap.end())
1116 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1119 unsigned InReg = FuncInfo.ValueMap[V];
1120 assert(InReg && "Value not in map!");
1122 RegsForValue RFV(TLI, InReg, V->getType());
1123 SDOperand Chain = DAG.getEntryNode();
1124 return RFV.getCopyFromRegs(DAG, Chain, NULL);
1128 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1129 if (I.getNumOperands() == 0) {
1130 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1134 SmallVector<SDOperand, 8> NewValues;
1135 NewValues.push_back(getControlRoot());
1136 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1137 SDOperand RetOp = getValue(I.getOperand(i));
1138 MVT::ValueType VT = RetOp.getValueType();
1140 // FIXME: C calling convention requires the return type to be promoted to
1141 // at least 32-bit. But this is not necessary for non-C calling conventions.
1142 if (MVT::isInteger(VT)) {
1143 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1144 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1148 unsigned NumParts = TLI.getNumRegisters(VT);
1149 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1150 SmallVector<SDOperand, 4> Parts(NumParts);
1151 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1153 const Function *F = I.getParent()->getParent();
1154 if (F->paramHasAttr(0, ParamAttr::SExt))
1155 ExtendKind = ISD::SIGN_EXTEND;
1156 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1157 ExtendKind = ISD::ZERO_EXTEND;
1159 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1161 for (unsigned i = 0; i < NumParts; ++i) {
1162 NewValues.push_back(Parts[i]);
1163 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1166 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1167 &NewValues[0], NewValues.size()));
1170 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1171 /// the current basic block, add it to ValueMap now so that we'll get a
1173 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1174 // No need to export constants.
1175 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1177 // Already exported?
1178 if (FuncInfo.isExportedInst(V)) return;
1180 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1181 CopyValueToVirtualRegister(V, Reg);
1184 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1185 const BasicBlock *FromBB) {
1186 // The operands of the setcc have to be in this block. We don't know
1187 // how to export them from some other block.
1188 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1189 // Can export from current BB.
1190 if (VI->getParent() == FromBB)
1193 // Is already exported, noop.
1194 return FuncInfo.isExportedInst(V);
1197 // If this is an argument, we can export it if the BB is the entry block or
1198 // if it is already exported.
1199 if (isa<Argument>(V)) {
1200 if (FromBB == &FromBB->getParent()->getEntryBlock())
1203 // Otherwise, can only export this if it is already exported.
1204 return FuncInfo.isExportedInst(V);
1207 // Otherwise, constants can always be exported.
1211 static bool InBlock(const Value *V, const BasicBlock *BB) {
1212 if (const Instruction *I = dyn_cast<Instruction>(V))
1213 return I->getParent() == BB;
1217 /// FindMergedConditions - If Cond is an expression like
1218 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1219 MachineBasicBlock *TBB,
1220 MachineBasicBlock *FBB,
1221 MachineBasicBlock *CurBB,
1223 // If this node is not part of the or/and tree, emit it as a branch.
1224 Instruction *BOp = dyn_cast<Instruction>(Cond);
1226 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1227 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1228 BOp->getParent() != CurBB->getBasicBlock() ||
1229 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1230 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1231 const BasicBlock *BB = CurBB->getBasicBlock();
1233 // If the leaf of the tree is a comparison, merge the condition into
1235 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1236 // The operands of the cmp have to be in this block. We don't know
1237 // how to export them from some other block. If this is the first block
1238 // of the sequence, no exporting is needed.
1240 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1241 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1242 BOp = cast<Instruction>(Cond);
1243 ISD::CondCode Condition;
1244 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1245 switch (IC->getPredicate()) {
1246 default: assert(0 && "Unknown icmp predicate opcode!");
1247 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1248 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1249 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1250 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1251 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1252 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1253 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1254 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1255 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1256 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1258 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1259 ISD::CondCode FPC, FOC;
1260 switch (FC->getPredicate()) {
1261 default: assert(0 && "Unknown fcmp predicate opcode!");
1262 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1263 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1264 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1265 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1266 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1267 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1268 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1269 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1270 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1271 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1272 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1273 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1274 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1275 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1276 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1277 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1279 if (FiniteOnlyFPMath())
1284 Condition = ISD::SETEQ; // silence warning.
1285 assert(0 && "Unknown compare instruction");
1288 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1289 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1290 SwitchCases.push_back(CB);
1294 // Create a CaseBlock record representing this branch.
1295 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1296 NULL, TBB, FBB, CurBB);
1297 SwitchCases.push_back(CB);
1302 // Create TmpBB after CurBB.
1303 MachineFunction::iterator BBI = CurBB;
1304 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1305 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1307 if (Opc == Instruction::Or) {
1308 // Codegen X | Y as:
1316 // Emit the LHS condition.
1317 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1319 // Emit the RHS condition into TmpBB.
1320 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1322 assert(Opc == Instruction::And && "Unknown merge op!");
1323 // Codegen X & Y as:
1330 // This requires creation of TmpBB after CurBB.
1332 // Emit the LHS condition.
1333 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1335 // Emit the RHS condition into TmpBB.
1336 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1340 /// If the set of cases should be emitted as a series of branches, return true.
1341 /// If we should emit this as a bunch of and/or'd together conditions, return
1344 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1345 if (Cases.size() != 2) return true;
1347 // If this is two comparisons of the same values or'd or and'd together, they
1348 // will get folded into a single comparison, so don't emit two blocks.
1349 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1350 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1351 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1352 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1359 void SelectionDAGLowering::visitBr(BranchInst &I) {
1360 // Update machine-CFG edges.
1361 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1363 // Figure out which block is immediately after the current one.
1364 MachineBasicBlock *NextBlock = 0;
1365 MachineFunction::iterator BBI = CurMBB;
1366 if (++BBI != CurMBB->getParent()->end())
1369 if (I.isUnconditional()) {
1370 // If this is not a fall-through branch, emit the branch.
1371 if (Succ0MBB != NextBlock)
1372 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1373 DAG.getBasicBlock(Succ0MBB)));
1375 // Update machine-CFG edges.
1376 CurMBB->addSuccessor(Succ0MBB);
1380 // If this condition is one of the special cases we handle, do special stuff
1382 Value *CondVal = I.getCondition();
1383 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1385 // If this is a series of conditions that are or'd or and'd together, emit
1386 // this as a sequence of branches instead of setcc's with and/or operations.
1387 // For example, instead of something like:
1400 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1401 if (BOp->hasOneUse() &&
1402 (BOp->getOpcode() == Instruction::And ||
1403 BOp->getOpcode() == Instruction::Or)) {
1404 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1405 // If the compares in later blocks need to use values not currently
1406 // exported from this block, export them now. This block should always
1407 // be the first entry.
1408 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1410 // Allow some cases to be rejected.
1411 if (ShouldEmitAsBranches(SwitchCases)) {
1412 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1413 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1414 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1417 // Emit the branch for this block.
1418 visitSwitchCase(SwitchCases[0]);
1419 SwitchCases.erase(SwitchCases.begin());
1423 // Okay, we decided not to do this, remove any inserted MBB's and clear
1425 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1426 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1428 SwitchCases.clear();
1432 // Create a CaseBlock record representing this branch.
1433 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1434 NULL, Succ0MBB, Succ1MBB, CurMBB);
1435 // Use visitSwitchCase to actually insert the fast branch sequence for this
1437 visitSwitchCase(CB);
1440 /// visitSwitchCase - Emits the necessary code to represent a single node in
1441 /// the binary search tree resulting from lowering a switch instruction.
1442 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1444 SDOperand CondLHS = getValue(CB.CmpLHS);
1446 // Build the setcc now.
1447 if (CB.CmpMHS == NULL) {
1448 // Fold "(X == true)" to X and "(X == false)" to !X to
1449 // handle common cases produced by branch lowering.
1450 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1452 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1453 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1454 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1456 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1458 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1460 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1461 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1463 SDOperand CmpOp = getValue(CB.CmpMHS);
1464 MVT::ValueType VT = CmpOp.getValueType();
1466 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1467 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1469 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1470 Cond = DAG.getSetCC(MVT::i1, SUB,
1471 DAG.getConstant(High-Low, VT), ISD::SETULE);
1476 // Set NextBlock to be the MBB immediately after the current one, if any.
1477 // This is used to avoid emitting unnecessary branches to the next block.
1478 MachineBasicBlock *NextBlock = 0;
1479 MachineFunction::iterator BBI = CurMBB;
1480 if (++BBI != CurMBB->getParent()->end())
1483 // If the lhs block is the next block, invert the condition so that we can
1484 // fall through to the lhs instead of the rhs block.
1485 if (CB.TrueBB == NextBlock) {
1486 std::swap(CB.TrueBB, CB.FalseBB);
1487 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1488 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1490 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1491 DAG.getBasicBlock(CB.TrueBB));
1492 if (CB.FalseBB == NextBlock)
1493 DAG.setRoot(BrCond);
1495 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1496 DAG.getBasicBlock(CB.FalseBB)));
1497 // Update successor info
1498 CurMBB->addSuccessor(CB.TrueBB);
1499 CurMBB->addSuccessor(CB.FalseBB);
1502 /// visitJumpTable - Emit JumpTable node in the current MBB
1503 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1504 // Emit the code for the jump table
1505 assert(JT.Reg != -1U && "Should lower JT Header first!");
1506 MVT::ValueType PTy = TLI.getPointerTy();
1507 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1508 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1509 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1514 /// visitJumpTableHeader - This function emits necessary code to produce index
1515 /// in the JumpTable from switch case.
1516 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1517 SelectionDAGISel::JumpTableHeader &JTH) {
1518 // Subtract the lowest switch case value from the value being switched on
1519 // and conditional branch to default mbb if the result is greater than the
1520 // difference between smallest and largest cases.
1521 SDOperand SwitchOp = getValue(JTH.SValue);
1522 MVT::ValueType VT = SwitchOp.getValueType();
1523 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1524 DAG.getConstant(JTH.First, VT));
1526 // The SDNode we just created, which holds the value being switched on
1527 // minus the the smallest case value, needs to be copied to a virtual
1528 // register so it can be used as an index into the jump table in a
1529 // subsequent basic block. This value may be smaller or larger than the
1530 // target's pointer type, and therefore require extension or truncating.
1531 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
1532 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1534 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1536 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1537 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1538 JT.Reg = JumpTableReg;
1540 // Emit the range check for the jump table, and branch to the default
1541 // block for the switch statement if the value being switched on exceeds
1542 // the largest case in the switch.
1543 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1544 DAG.getConstant(JTH.Last-JTH.First,VT),
1547 // Set NextBlock to be the MBB immediately after the current one, if any.
1548 // This is used to avoid emitting unnecessary branches to the next block.
1549 MachineBasicBlock *NextBlock = 0;
1550 MachineFunction::iterator BBI = CurMBB;
1551 if (++BBI != CurMBB->getParent()->end())
1554 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1555 DAG.getBasicBlock(JT.Default));
1557 if (JT.MBB == NextBlock)
1558 DAG.setRoot(BrCond);
1560 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1561 DAG.getBasicBlock(JT.MBB)));
1566 /// visitBitTestHeader - This function emits necessary code to produce value
1567 /// suitable for "bit tests"
1568 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1569 // Subtract the minimum value
1570 SDOperand SwitchOp = getValue(B.SValue);
1571 MVT::ValueType VT = SwitchOp.getValueType();
1572 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1573 DAG.getConstant(B.First, VT));
1576 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1577 DAG.getConstant(B.Range, VT),
1581 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
1582 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1584 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1586 // Make desired shift
1587 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1588 DAG.getConstant(1, TLI.getPointerTy()),
1591 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1592 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1595 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1596 DAG.getBasicBlock(B.Default));
1598 // Set NextBlock to be the MBB immediately after the current one, if any.
1599 // This is used to avoid emitting unnecessary branches to the next block.
1600 MachineBasicBlock *NextBlock = 0;
1601 MachineFunction::iterator BBI = CurMBB;
1602 if (++BBI != CurMBB->getParent()->end())
1605 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1606 if (MBB == NextBlock)
1607 DAG.setRoot(BrRange);
1609 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1610 DAG.getBasicBlock(MBB)));
1612 CurMBB->addSuccessor(B.Default);
1613 CurMBB->addSuccessor(MBB);
1618 /// visitBitTestCase - this function produces one "bit test"
1619 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1621 SelectionDAGISel::BitTestCase &B) {
1622 // Emit bit tests and jumps
1623 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
1625 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1627 DAG.getConstant(B.Mask,
1628 TLI.getPointerTy()));
1629 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1630 DAG.getConstant(0, TLI.getPointerTy()),
1632 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1633 AndCmp, DAG.getBasicBlock(B.TargetBB));
1635 // Set NextBlock to be the MBB immediately after the current one, if any.
1636 // This is used to avoid emitting unnecessary branches to the next block.
1637 MachineBasicBlock *NextBlock = 0;
1638 MachineFunction::iterator BBI = CurMBB;
1639 if (++BBI != CurMBB->getParent()->end())
1642 if (NextMBB == NextBlock)
1645 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1646 DAG.getBasicBlock(NextMBB)));
1648 CurMBB->addSuccessor(B.TargetBB);
1649 CurMBB->addSuccessor(NextMBB);
1654 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1655 // Retrieve successors.
1656 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1657 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1659 if (isa<InlineAsm>(I.getCalledValue()))
1662 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1664 // If the value of the invoke is used outside of its defining block, make it
1665 // available as a virtual register.
1666 if (!I.use_empty()) {
1667 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1668 if (VMI != FuncInfo.ValueMap.end())
1669 CopyValueToVirtualRegister(&I, VMI->second);
1672 // Drop into normal successor.
1673 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1674 DAG.getBasicBlock(Return)));
1676 // Update successor info
1677 CurMBB->addSuccessor(Return);
1678 CurMBB->addSuccessor(LandingPad);
1681 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1684 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1685 /// small case ranges).
1686 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1687 CaseRecVector& WorkList,
1689 MachineBasicBlock* Default) {
1690 Case& BackCase = *(CR.Range.second-1);
1692 // Size is the number of Cases represented by this range.
1693 unsigned Size = CR.Range.second - CR.Range.first;
1697 // Get the MachineFunction which holds the current MBB. This is used when
1698 // inserting any additional MBBs necessary to represent the switch.
1699 MachineFunction *CurMF = CurMBB->getParent();
1701 // Figure out which block is immediately after the current one.
1702 MachineBasicBlock *NextBlock = 0;
1703 MachineFunction::iterator BBI = CR.CaseBB;
1705 if (++BBI != CurMBB->getParent()->end())
1708 // TODO: If any two of the cases has the same destination, and if one value
1709 // is the same as the other, but has one bit unset that the other has set,
1710 // use bit manipulation to do two compares at once. For example:
1711 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1713 // Rearrange the case blocks so that the last one falls through if possible.
1714 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1715 // The last case block won't fall through into 'NextBlock' if we emit the
1716 // branches in this order. See if rearranging a case value would help.
1717 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1718 if (I->BB == NextBlock) {
1719 std::swap(*I, BackCase);
1725 // Create a CaseBlock record representing a conditional branch to
1726 // the Case's target mbb if the value being switched on SV is equal
1728 MachineBasicBlock *CurBlock = CR.CaseBB;
1729 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1730 MachineBasicBlock *FallThrough;
1732 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1733 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1735 // If the last case doesn't match, go to the default block.
1736 FallThrough = Default;
1739 Value *RHS, *LHS, *MHS;
1741 if (I->High == I->Low) {
1742 // This is just small small case range :) containing exactly 1 case
1744 LHS = SV; RHS = I->High; MHS = NULL;
1747 LHS = I->Low; MHS = SV; RHS = I->High;
1749 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1750 I->BB, FallThrough, CurBlock);
1752 // If emitting the first comparison, just call visitSwitchCase to emit the
1753 // code into the current block. Otherwise, push the CaseBlock onto the
1754 // vector to be later processed by SDISel, and insert the node's MBB
1755 // before the next MBB.
1756 if (CurBlock == CurMBB)
1757 visitSwitchCase(CB);
1759 SwitchCases.push_back(CB);
1761 CurBlock = FallThrough;
1767 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1768 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1769 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1772 /// handleJTSwitchCase - Emit jumptable for current switch case range
1773 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1774 CaseRecVector& WorkList,
1776 MachineBasicBlock* Default) {
1777 Case& FrontCase = *CR.Range.first;
1778 Case& BackCase = *(CR.Range.second-1);
1780 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1781 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1784 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1788 if (!areJTsAllowed(TLI) || TSize <= 3)
1791 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1795 DOUT << "Lowering jump table\n"
1796 << "First entry: " << First << ". Last entry: " << Last << "\n"
1797 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1799 // Get the MachineFunction which holds the current MBB. This is used when
1800 // inserting any additional MBBs necessary to represent the switch.
1801 MachineFunction *CurMF = CurMBB->getParent();
1803 // Figure out which block is immediately after the current one.
1804 MachineBasicBlock *NextBlock = 0;
1805 MachineFunction::iterator BBI = CR.CaseBB;
1807 if (++BBI != CurMBB->getParent()->end())
1810 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1812 // Create a new basic block to hold the code for loading the address
1813 // of the jump table, and jumping to it. Update successor information;
1814 // we will either branch to the default case for the switch, or the jump
1816 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1817 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1818 CR.CaseBB->addSuccessor(Default);
1819 CR.CaseBB->addSuccessor(JumpTableBB);
1821 // Build a vector of destination BBs, corresponding to each target
1822 // of the jump table. If the value of the jump table slot corresponds to
1823 // a case statement, push the case's BB onto the vector, otherwise, push
1825 std::vector<MachineBasicBlock*> DestBBs;
1826 int64_t TEI = First;
1827 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1828 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1829 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1831 if ((Low <= TEI) && (TEI <= High)) {
1832 DestBBs.push_back(I->BB);
1836 DestBBs.push_back(Default);
1840 // Update successor info. Add one edge to each unique successor.
1841 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1842 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1843 E = DestBBs.end(); I != E; ++I) {
1844 if (!SuccsHandled[(*I)->getNumber()]) {
1845 SuccsHandled[(*I)->getNumber()] = true;
1846 JumpTableBB->addSuccessor(*I);
1850 // Create a jump table index for this jump table, or return an existing
1852 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1854 // Set the jump table information so that we can codegen it as a second
1855 // MachineBasicBlock
1856 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1857 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1858 (CR.CaseBB == CurMBB));
1859 if (CR.CaseBB == CurMBB)
1860 visitJumpTableHeader(JT, JTH);
1862 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1867 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1869 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1870 CaseRecVector& WorkList,
1872 MachineBasicBlock* Default) {
1873 // Get the MachineFunction which holds the current MBB. This is used when
1874 // inserting any additional MBBs necessary to represent the switch.
1875 MachineFunction *CurMF = CurMBB->getParent();
1877 // Figure out which block is immediately after the current one.
1878 MachineBasicBlock *NextBlock = 0;
1879 MachineFunction::iterator BBI = CR.CaseBB;
1881 if (++BBI != CurMBB->getParent()->end())
1884 Case& FrontCase = *CR.Range.first;
1885 Case& BackCase = *(CR.Range.second-1);
1886 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1888 // Size is the number of Cases represented by this range.
1889 unsigned Size = CR.Range.second - CR.Range.first;
1891 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1892 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1894 CaseItr Pivot = CR.Range.first + Size/2;
1896 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1897 // (heuristically) allow us to emit JumpTable's later.
1899 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1903 uint64_t LSize = FrontCase.size();
1904 uint64_t RSize = TSize-LSize;
1905 DOUT << "Selecting best pivot: \n"
1906 << "First: " << First << ", Last: " << Last <<"\n"
1907 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1908 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1910 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1911 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1912 assert((RBegin-LEnd>=1) && "Invalid case distance");
1913 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1914 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1915 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1916 // Should always split in some non-trivial place
1918 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1919 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1920 << "Metric: " << Metric << "\n";
1921 if (FMetric < Metric) {
1924 DOUT << "Current metric set to: " << FMetric << "\n";
1930 if (areJTsAllowed(TLI)) {
1931 // If our case is dense we *really* should handle it earlier!
1932 assert((FMetric > 0) && "Should handle dense range earlier!");
1934 Pivot = CR.Range.first + Size/2;
1937 CaseRange LHSR(CR.Range.first, Pivot);
1938 CaseRange RHSR(Pivot, CR.Range.second);
1939 Constant *C = Pivot->Low;
1940 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1942 // We know that we branch to the LHS if the Value being switched on is
1943 // less than the Pivot value, C. We use this to optimize our binary
1944 // tree a bit, by recognizing that if SV is greater than or equal to the
1945 // LHS's Case Value, and that Case Value is exactly one less than the
1946 // Pivot's Value, then we can branch directly to the LHS's Target,
1947 // rather than creating a leaf node for it.
1948 if ((LHSR.second - LHSR.first) == 1 &&
1949 LHSR.first->High == CR.GE &&
1950 cast<ConstantInt>(C)->getSExtValue() ==
1951 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1952 TrueBB = LHSR.first->BB;
1954 TrueBB = new MachineBasicBlock(LLVMBB);
1955 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1956 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1959 // Similar to the optimization above, if the Value being switched on is
1960 // known to be less than the Constant CR.LT, and the current Case Value
1961 // is CR.LT - 1, then we can branch directly to the target block for
1962 // the current Case Value, rather than emitting a RHS leaf node for it.
1963 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1964 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1965 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1966 FalseBB = RHSR.first->BB;
1968 FalseBB = new MachineBasicBlock(LLVMBB);
1969 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1970 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1973 // Create a CaseBlock record representing a conditional branch to
1974 // the LHS node if the value being switched on SV is less than C.
1975 // Otherwise, branch to LHS.
1976 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1977 TrueBB, FalseBB, CR.CaseBB);
1979 if (CR.CaseBB == CurMBB)
1980 visitSwitchCase(CB);
1982 SwitchCases.push_back(CB);
1987 /// handleBitTestsSwitchCase - if current case range has few destination and
1988 /// range span less, than machine word bitwidth, encode case range into series
1989 /// of masks and emit bit tests with these masks.
1990 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1991 CaseRecVector& WorkList,
1993 MachineBasicBlock* Default){
1994 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
1996 Case& FrontCase = *CR.Range.first;
1997 Case& BackCase = *(CR.Range.second-1);
1999 // Get the MachineFunction which holds the current MBB. This is used when
2000 // inserting any additional MBBs necessary to represent the switch.
2001 MachineFunction *CurMF = CurMBB->getParent();
2003 unsigned numCmps = 0;
2004 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2006 // Single case counts one, case range - two.
2007 if (I->Low == I->High)
2013 // Count unique destinations
2014 SmallSet<MachineBasicBlock*, 4> Dests;
2015 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2016 Dests.insert(I->BB);
2017 if (Dests.size() > 3)
2018 // Don't bother the code below, if there are too much unique destinations
2021 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2022 << "Total number of comparisons: " << numCmps << "\n";
2024 // Compute span of values.
2025 Constant* minValue = FrontCase.Low;
2026 Constant* maxValue = BackCase.High;
2027 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2028 cast<ConstantInt>(minValue)->getSExtValue();
2029 DOUT << "Compare range: " << range << "\n"
2030 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2031 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2033 if (range>=IntPtrBits ||
2034 (!(Dests.size() == 1 && numCmps >= 3) &&
2035 !(Dests.size() == 2 && numCmps >= 5) &&
2036 !(Dests.size() >= 3 && numCmps >= 6)))
2039 DOUT << "Emitting bit tests\n";
2040 int64_t lowBound = 0;
2042 // Optimize the case where all the case values fit in a
2043 // word without having to subtract minValue. In this case,
2044 // we can optimize away the subtraction.
2045 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2046 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
2047 range = cast<ConstantInt>(maxValue)->getSExtValue();
2049 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2052 CaseBitsVector CasesBits;
2053 unsigned i, count = 0;
2055 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2056 MachineBasicBlock* Dest = I->BB;
2057 for (i = 0; i < count; ++i)
2058 if (Dest == CasesBits[i].BB)
2062 assert((count < 3) && "Too much destinations to test!");
2063 CasesBits.push_back(CaseBits(0, Dest, 0));
2067 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2068 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2070 for (uint64_t j = lo; j <= hi; j++) {
2071 CasesBits[i].Mask |= 1ULL << j;
2072 CasesBits[i].Bits++;
2076 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2078 SelectionDAGISel::BitTestInfo BTC;
2080 // Figure out which block is immediately after the current one.
2081 MachineFunction::iterator BBI = CR.CaseBB;
2084 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2087 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2088 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2089 << ", BB: " << CasesBits[i].BB << "\n";
2091 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2092 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2093 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2098 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2099 -1U, (CR.CaseBB == CurMBB),
2100 CR.CaseBB, Default, BTC);
2102 if (CR.CaseBB == CurMBB)
2103 visitBitTestHeader(BTB);
2105 BitTestCases.push_back(BTB);
2111 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2112 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2113 const SwitchInst& SI) {
2114 unsigned numCmps = 0;
2116 // Start with "simple" cases
2117 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2118 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2119 Cases.push_back(Case(SI.getSuccessorValue(i),
2120 SI.getSuccessorValue(i),
2123 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2125 // Merge case into clusters
2126 if (Cases.size()>=2)
2127 // Must recompute end() each iteration because it may be
2128 // invalidated by erase if we hold on to it
2129 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2130 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2131 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2132 MachineBasicBlock* nextBB = J->BB;
2133 MachineBasicBlock* currentBB = I->BB;
2135 // If the two neighboring cases go to the same destination, merge them
2136 // into a single case.
2137 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2145 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2146 if (I->Low != I->High)
2147 // A range counts double, since it requires two compares.
2154 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2155 // Figure out which block is immediately after the current one.
2156 MachineBasicBlock *NextBlock = 0;
2157 MachineFunction::iterator BBI = CurMBB;
2159 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2161 // If there is only the default destination, branch to it if it is not the
2162 // next basic block. Otherwise, just fall through.
2163 if (SI.getNumOperands() == 2) {
2164 // Update machine-CFG edges.
2166 // If this is not a fall-through branch, emit the branch.
2167 if (Default != NextBlock)
2168 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2169 DAG.getBasicBlock(Default)));
2171 CurMBB->addSuccessor(Default);
2175 // If there are any non-default case statements, create a vector of Cases
2176 // representing each one, and sort the vector so that we can efficiently
2177 // create a binary search tree from them.
2179 unsigned numCmps = Clusterify(Cases, SI);
2180 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2181 << ". Total compares: " << numCmps << "\n";
2183 // Get the Value to be switched on and default basic blocks, which will be
2184 // inserted into CaseBlock records, representing basic blocks in the binary
2186 Value *SV = SI.getOperand(0);
2188 // Push the initial CaseRec onto the worklist
2189 CaseRecVector WorkList;
2190 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2192 while (!WorkList.empty()) {
2193 // Grab a record representing a case range to process off the worklist
2194 CaseRec CR = WorkList.back();
2195 WorkList.pop_back();
2197 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2200 // If the range has few cases (two or less) emit a series of specific
2202 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2205 // If the switch has more than 5 blocks, and at least 40% dense, and the
2206 // target supports indirect branches, then emit a jump table rather than
2207 // lowering the switch to a binary tree of conditional branches.
2208 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2211 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2212 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2213 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2218 void SelectionDAGLowering::visitSub(User &I) {
2219 // -0.0 - X --> fneg
2220 const Type *Ty = I.getType();
2221 if (isa<VectorType>(Ty)) {
2222 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2223 const VectorType *DestTy = cast<VectorType>(I.getType());
2224 const Type *ElTy = DestTy->getElementType();
2225 if (ElTy->isFloatingPoint()) {
2226 unsigned VL = DestTy->getNumElements();
2227 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2228 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2230 SDOperand Op2 = getValue(I.getOperand(1));
2231 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2237 if (Ty->isFloatingPoint()) {
2238 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2239 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2240 SDOperand Op2 = getValue(I.getOperand(1));
2241 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2246 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2249 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2250 SDOperand Op1 = getValue(I.getOperand(0));
2251 SDOperand Op2 = getValue(I.getOperand(1));
2253 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2256 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2257 SDOperand Op1 = getValue(I.getOperand(0));
2258 SDOperand Op2 = getValue(I.getOperand(1));
2260 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2261 MVT::getSizeInBits(Op2.getValueType()))
2262 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2263 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2264 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2266 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2269 void SelectionDAGLowering::visitICmp(User &I) {
2270 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2271 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2272 predicate = IC->getPredicate();
2273 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2274 predicate = ICmpInst::Predicate(IC->getPredicate());
2275 SDOperand Op1 = getValue(I.getOperand(0));
2276 SDOperand Op2 = getValue(I.getOperand(1));
2277 ISD::CondCode Opcode;
2278 switch (predicate) {
2279 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2280 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2281 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2282 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2283 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2284 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2285 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2286 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2287 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2288 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2290 assert(!"Invalid ICmp predicate value");
2291 Opcode = ISD::SETEQ;
2294 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2297 void SelectionDAGLowering::visitFCmp(User &I) {
2298 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2299 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2300 predicate = FC->getPredicate();
2301 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2302 predicate = FCmpInst::Predicate(FC->getPredicate());
2303 SDOperand Op1 = getValue(I.getOperand(0));
2304 SDOperand Op2 = getValue(I.getOperand(1));
2305 ISD::CondCode Condition, FOC, FPC;
2306 switch (predicate) {
2307 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2308 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2309 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2310 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2311 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2312 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2313 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2314 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2315 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2316 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2317 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2318 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2319 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2320 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2321 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2322 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2324 assert(!"Invalid FCmp predicate value");
2325 FOC = FPC = ISD::SETFALSE;
2328 if (FiniteOnlyFPMath())
2332 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2335 void SelectionDAGLowering::visitSelect(User &I) {
2336 SDOperand Cond = getValue(I.getOperand(0));
2337 SDOperand TrueVal = getValue(I.getOperand(1));
2338 SDOperand FalseVal = getValue(I.getOperand(2));
2339 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2340 TrueVal, FalseVal));
2344 void SelectionDAGLowering::visitTrunc(User &I) {
2345 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2346 SDOperand N = getValue(I.getOperand(0));
2347 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2348 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2351 void SelectionDAGLowering::visitZExt(User &I) {
2352 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2353 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2354 SDOperand N = getValue(I.getOperand(0));
2355 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2356 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2359 void SelectionDAGLowering::visitSExt(User &I) {
2360 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2361 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2362 SDOperand N = getValue(I.getOperand(0));
2363 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2364 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2367 void SelectionDAGLowering::visitFPTrunc(User &I) {
2368 // FPTrunc is never a no-op cast, no need to check
2369 SDOperand N = getValue(I.getOperand(0));
2370 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2371 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2374 void SelectionDAGLowering::visitFPExt(User &I){
2375 // FPTrunc is never a no-op cast, no need to check
2376 SDOperand N = getValue(I.getOperand(0));
2377 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2378 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2381 void SelectionDAGLowering::visitFPToUI(User &I) {
2382 // FPToUI is never a no-op cast, no need to check
2383 SDOperand N = getValue(I.getOperand(0));
2384 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2385 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2388 void SelectionDAGLowering::visitFPToSI(User &I) {
2389 // FPToSI is never a no-op cast, no need to check
2390 SDOperand N = getValue(I.getOperand(0));
2391 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2392 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2395 void SelectionDAGLowering::visitUIToFP(User &I) {
2396 // UIToFP is never a no-op cast, no need to check
2397 SDOperand N = getValue(I.getOperand(0));
2398 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2399 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2402 void SelectionDAGLowering::visitSIToFP(User &I){
2403 // UIToFP is never a no-op cast, no need to check
2404 SDOperand N = getValue(I.getOperand(0));
2405 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2406 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2409 void SelectionDAGLowering::visitPtrToInt(User &I) {
2410 // What to do depends on the size of the integer and the size of the pointer.
2411 // We can either truncate, zero extend, or no-op, accordingly.
2412 SDOperand N = getValue(I.getOperand(0));
2413 MVT::ValueType SrcVT = N.getValueType();
2414 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2416 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2417 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2419 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2420 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2421 setValue(&I, Result);
2424 void SelectionDAGLowering::visitIntToPtr(User &I) {
2425 // What to do depends on the size of the integer and the size of the pointer.
2426 // We can either truncate, zero extend, or no-op, accordingly.
2427 SDOperand N = getValue(I.getOperand(0));
2428 MVT::ValueType SrcVT = N.getValueType();
2429 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2430 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2431 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2433 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2434 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2437 void SelectionDAGLowering::visitBitCast(User &I) {
2438 SDOperand N = getValue(I.getOperand(0));
2439 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2441 // BitCast assures us that source and destination are the same size so this
2442 // is either a BIT_CONVERT or a no-op.
2443 if (DestVT != N.getValueType())
2444 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2446 setValue(&I, N); // noop cast.
2449 void SelectionDAGLowering::visitInsertElement(User &I) {
2450 SDOperand InVec = getValue(I.getOperand(0));
2451 SDOperand InVal = getValue(I.getOperand(1));
2452 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2453 getValue(I.getOperand(2)));
2455 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2456 TLI.getValueType(I.getType()),
2457 InVec, InVal, InIdx));
2460 void SelectionDAGLowering::visitExtractElement(User &I) {
2461 SDOperand InVec = getValue(I.getOperand(0));
2462 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2463 getValue(I.getOperand(1)));
2464 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2465 TLI.getValueType(I.getType()), InVec, InIdx));
2468 void SelectionDAGLowering::visitShuffleVector(User &I) {
2469 SDOperand V1 = getValue(I.getOperand(0));
2470 SDOperand V2 = getValue(I.getOperand(1));
2471 SDOperand Mask = getValue(I.getOperand(2));
2473 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2474 TLI.getValueType(I.getType()),
2479 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2480 SDOperand N = getValue(I.getOperand(0));
2481 const Type *Ty = I.getOperand(0)->getType();
2483 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2486 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2487 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2490 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2491 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2492 DAG.getIntPtrConstant(Offset));
2494 Ty = StTy->getElementType(Field);
2496 Ty = cast<SequentialType>(Ty)->getElementType();
2498 // If this is a constant subscript, handle it quickly.
2499 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2500 if (CI->getZExtValue() == 0) continue;
2502 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2503 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2504 DAG.getIntPtrConstant(Offs));
2508 // N = N + Idx * ElementSize;
2509 uint64_t ElementSize = TD->getABITypeSize(Ty);
2510 SDOperand IdxN = getValue(Idx);
2512 // If the index is smaller or larger than intptr_t, truncate or extend
2514 if (IdxN.getValueType() < N.getValueType()) {
2515 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2516 } else if (IdxN.getValueType() > N.getValueType())
2517 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2519 // If this is a multiply by a power of two, turn it into a shl
2520 // immediately. This is a very common case.
2521 if (isPowerOf2_64(ElementSize)) {
2522 unsigned Amt = Log2_64(ElementSize);
2523 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2524 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2525 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2529 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2530 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2531 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2537 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2538 // If this is a fixed sized alloca in the entry block of the function,
2539 // allocate it statically on the stack.
2540 if (FuncInfo.StaticAllocaMap.count(&I))
2541 return; // getValue will auto-populate this.
2543 const Type *Ty = I.getAllocatedType();
2544 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2546 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2549 SDOperand AllocSize = getValue(I.getArraySize());
2550 MVT::ValueType IntPtr = TLI.getPointerTy();
2551 if (IntPtr < AllocSize.getValueType())
2552 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2553 else if (IntPtr > AllocSize.getValueType())
2554 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2556 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2557 DAG.getIntPtrConstant(TySize));
2559 // Handle alignment. If the requested alignment is less than or equal to
2560 // the stack alignment, ignore it. If the size is greater than or equal to
2561 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2562 unsigned StackAlign =
2563 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2564 if (Align <= StackAlign)
2567 // Round the size of the allocation up to the stack alignment size
2568 // by add SA-1 to the size.
2569 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2570 DAG.getIntPtrConstant(StackAlign-1));
2571 // Mask out the low bits for alignment purposes.
2572 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2573 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2575 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2576 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2578 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2580 DAG.setRoot(DSA.getValue(1));
2582 // Inform the Frame Information that we have just allocated a variable-sized
2584 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2587 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2588 SDOperand Ptr = getValue(I.getOperand(0));
2594 // Do not serialize non-volatile loads against each other.
2595 Root = DAG.getRoot();
2598 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2599 Root, I.isVolatile(), I.getAlignment()));
2602 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2603 const Value *SV, SDOperand Root,
2605 unsigned Alignment) {
2607 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2608 isVolatile, Alignment);
2611 DAG.setRoot(L.getValue(1));
2613 PendingLoads.push_back(L.getValue(1));
2619 void SelectionDAGLowering::visitStore(StoreInst &I) {
2620 Value *SrcV = I.getOperand(0);
2621 SDOperand Src = getValue(SrcV);
2622 SDOperand Ptr = getValue(I.getOperand(1));
2623 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2624 I.isVolatile(), I.getAlignment()));
2627 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2629 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2630 unsigned Intrinsic) {
2631 bool HasChain = !I.doesNotAccessMemory();
2632 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2634 // Build the operand list.
2635 SmallVector<SDOperand, 8> Ops;
2636 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2638 // We don't need to serialize loads against other loads.
2639 Ops.push_back(DAG.getRoot());
2641 Ops.push_back(getRoot());
2645 // Add the intrinsic ID as an integer operand.
2646 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2648 // Add all operands of the call to the operand list.
2649 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2650 SDOperand Op = getValue(I.getOperand(i));
2651 assert(TLI.isTypeLegal(Op.getValueType()) &&
2652 "Intrinsic uses a non-legal type?");
2656 std::vector<MVT::ValueType> VTs;
2657 if (I.getType() != Type::VoidTy) {
2658 MVT::ValueType VT = TLI.getValueType(I.getType());
2659 if (MVT::isVector(VT)) {
2660 const VectorType *DestTy = cast<VectorType>(I.getType());
2661 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2663 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2664 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2667 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2671 VTs.push_back(MVT::Other);
2673 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2678 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2679 &Ops[0], Ops.size());
2680 else if (I.getType() != Type::VoidTy)
2681 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2682 &Ops[0], Ops.size());
2684 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2685 &Ops[0], Ops.size());
2688 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2690 PendingLoads.push_back(Chain);
2694 if (I.getType() != Type::VoidTy) {
2695 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2696 MVT::ValueType VT = TLI.getValueType(PTy);
2697 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2699 setValue(&I, Result);
2703 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2704 static GlobalVariable *ExtractTypeInfo (Value *V) {
2705 V = IntrinsicInst::StripPointerCasts(V);
2706 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2707 assert ((GV || isa<ConstantPointerNull>(V)) &&
2708 "TypeInfo must be a global variable or NULL");
2712 /// addCatchInfo - Extract the personality and type infos from an eh.selector
2713 /// call, and add them to the specified machine basic block.
2714 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2715 MachineBasicBlock *MBB) {
2716 // Inform the MachineModuleInfo of the personality for this landing pad.
2717 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2718 assert(CE->getOpcode() == Instruction::BitCast &&
2719 isa<Function>(CE->getOperand(0)) &&
2720 "Personality should be a function");
2721 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2723 // Gather all the type infos for this landing pad and pass them along to
2724 // MachineModuleInfo.
2725 std::vector<GlobalVariable *> TyInfo;
2726 unsigned N = I.getNumOperands();
2728 for (unsigned i = N - 1; i > 2; --i) {
2729 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2730 unsigned FilterLength = CI->getZExtValue();
2731 unsigned FirstCatch = i + FilterLength + !FilterLength;
2732 assert (FirstCatch <= N && "Invalid filter length");
2734 if (FirstCatch < N) {
2735 TyInfo.reserve(N - FirstCatch);
2736 for (unsigned j = FirstCatch; j < N; ++j)
2737 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2738 MMI->addCatchTypeInfo(MBB, TyInfo);
2742 if (!FilterLength) {
2744 MMI->addCleanup(MBB);
2747 TyInfo.reserve(FilterLength - 1);
2748 for (unsigned j = i + 1; j < FirstCatch; ++j)
2749 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2750 MMI->addFilterTypeInfo(MBB, TyInfo);
2759 TyInfo.reserve(N - 3);
2760 for (unsigned j = 3; j < N; ++j)
2761 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2762 MMI->addCatchTypeInfo(MBB, TyInfo);
2766 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2767 /// we want to emit this as a call to a named external function, return the name
2768 /// otherwise lower it and return null.
2770 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2771 switch (Intrinsic) {
2773 // By default, turn this into a target intrinsic node.
2774 visitTargetIntrinsic(I, Intrinsic);
2776 case Intrinsic::vastart: visitVAStart(I); return 0;
2777 case Intrinsic::vaend: visitVAEnd(I); return 0;
2778 case Intrinsic::vacopy: visitVACopy(I); return 0;
2779 case Intrinsic::returnaddress:
2780 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2781 getValue(I.getOperand(1))));
2783 case Intrinsic::frameaddress:
2784 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2785 getValue(I.getOperand(1))));
2787 case Intrinsic::setjmp:
2788 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2790 case Intrinsic::longjmp:
2791 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2793 case Intrinsic::memcpy_i32:
2794 case Intrinsic::memcpy_i64: {
2795 SDOperand Op1 = getValue(I.getOperand(1));
2796 SDOperand Op2 = getValue(I.getOperand(2));
2797 SDOperand Op3 = getValue(I.getOperand(3));
2798 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2799 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2800 I.getOperand(1), 0, I.getOperand(2), 0));
2803 case Intrinsic::memset_i32:
2804 case Intrinsic::memset_i64: {
2805 SDOperand Op1 = getValue(I.getOperand(1));
2806 SDOperand Op2 = getValue(I.getOperand(2));
2807 SDOperand Op3 = getValue(I.getOperand(3));
2808 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2809 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2810 I.getOperand(1), 0));
2813 case Intrinsic::memmove_i32:
2814 case Intrinsic::memmove_i64: {
2815 SDOperand Op1 = getValue(I.getOperand(1));
2816 SDOperand Op2 = getValue(I.getOperand(2));
2817 SDOperand Op3 = getValue(I.getOperand(3));
2818 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2820 // If the source and destination are known to not be aliases, we can
2821 // lower memmove as memcpy.
2822 uint64_t Size = -1ULL;
2823 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2824 Size = C->getValue();
2825 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2826 AliasAnalysis::NoAlias) {
2827 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2828 I.getOperand(1), 0, I.getOperand(2), 0));
2832 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2833 I.getOperand(1), 0, I.getOperand(2), 0));
2836 case Intrinsic::dbg_stoppoint: {
2837 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2838 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2839 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2843 Ops[1] = getValue(SPI.getLineValue());
2844 Ops[2] = getValue(SPI.getColumnValue());
2846 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2847 assert(DD && "Not a debug information descriptor");
2848 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2850 Ops[3] = DAG.getString(CompileUnit->getFileName());
2851 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2853 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2858 case Intrinsic::dbg_region_start: {
2859 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2860 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2861 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2862 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2863 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2864 DAG.getConstant(LabelID, MVT::i32),
2865 DAG.getConstant(0, MVT::i32)));
2870 case Intrinsic::dbg_region_end: {
2871 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2872 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2873 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2874 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2875 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2876 DAG.getConstant(LabelID, MVT::i32),
2877 DAG.getConstant(0, MVT::i32)));
2882 case Intrinsic::dbg_func_start: {
2883 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2885 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2886 Value *SP = FSI.getSubprogram();
2887 if (SP && MMI->Verify(SP)) {
2888 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2889 // what (most?) gdb expects.
2890 DebugInfoDesc *DD = MMI->getDescFor(SP);
2891 assert(DD && "Not a debug information descriptor");
2892 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2893 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2894 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2895 CompileUnit->getFileName());
2896 // Record the source line but does create a label. It will be emitted
2897 // at asm emission time.
2898 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
2903 case Intrinsic::dbg_declare: {
2904 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2905 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2906 Value *Variable = DI.getVariable();
2907 if (MMI && Variable && MMI->Verify(Variable))
2908 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2909 getValue(DI.getAddress()), getValue(Variable)));
2913 case Intrinsic::eh_exception: {
2914 if (!CurMBB->isLandingPad()) {
2915 // FIXME: Mark exception register as live in. Hack for PR1508.
2916 unsigned Reg = TLI.getExceptionAddressRegister();
2917 if (Reg) CurMBB->addLiveIn(Reg);
2919 // Insert the EXCEPTIONADDR instruction.
2920 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2922 Ops[0] = DAG.getRoot();
2923 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2925 DAG.setRoot(Op.getValue(1));
2929 case Intrinsic::eh_selector_i32:
2930 case Intrinsic::eh_selector_i64: {
2931 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2932 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2933 MVT::i32 : MVT::i64);
2936 if (CurMBB->isLandingPad())
2937 addCatchInfo(I, MMI, CurMBB);
2940 FuncInfo.CatchInfoLost.insert(&I);
2942 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2943 unsigned Reg = TLI.getExceptionSelectorRegister();
2944 if (Reg) CurMBB->addLiveIn(Reg);
2947 // Insert the EHSELECTION instruction.
2948 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2950 Ops[0] = getValue(I.getOperand(1));
2952 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2954 DAG.setRoot(Op.getValue(1));
2956 setValue(&I, DAG.getConstant(0, VT));
2962 case Intrinsic::eh_typeid_for_i32:
2963 case Intrinsic::eh_typeid_for_i64: {
2964 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2965 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2966 MVT::i32 : MVT::i64);
2969 // Find the type id for the given typeinfo.
2970 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
2972 unsigned TypeID = MMI->getTypeIDFor(GV);
2973 setValue(&I, DAG.getConstant(TypeID, VT));
2975 // Return something different to eh_selector.
2976 setValue(&I, DAG.getConstant(1, VT));
2982 case Intrinsic::eh_return: {
2983 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2986 MMI->setCallsEHReturn(true);
2987 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2990 getValue(I.getOperand(1)),
2991 getValue(I.getOperand(2))));
2993 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2999 case Intrinsic::eh_unwind_init: {
3000 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3001 MMI->setCallsUnwindInit(true);
3007 case Intrinsic::eh_dwarf_cfa: {
3008 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3010 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3011 CfaArg = DAG.getNode(ISD::TRUNCATE,
3012 TLI.getPointerTy(), getValue(I.getOperand(1)));
3014 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3015 TLI.getPointerTy(), getValue(I.getOperand(1)));
3017 SDOperand Offset = DAG.getNode(ISD::ADD,
3019 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3020 TLI.getPointerTy()),
3022 setValue(&I, DAG.getNode(ISD::ADD,
3024 DAG.getNode(ISD::FRAMEADDR,
3027 TLI.getPointerTy())),
3032 case Intrinsic::sqrt:
3033 setValue(&I, DAG.getNode(ISD::FSQRT,
3034 getValue(I.getOperand(1)).getValueType(),
3035 getValue(I.getOperand(1))));
3037 case Intrinsic::powi:
3038 setValue(&I, DAG.getNode(ISD::FPOWI,
3039 getValue(I.getOperand(1)).getValueType(),
3040 getValue(I.getOperand(1)),
3041 getValue(I.getOperand(2))));
3043 case Intrinsic::sin:
3044 setValue(&I, DAG.getNode(ISD::FSIN,
3045 getValue(I.getOperand(1)).getValueType(),
3046 getValue(I.getOperand(1))));
3048 case Intrinsic::cos:
3049 setValue(&I, DAG.getNode(ISD::FCOS,
3050 getValue(I.getOperand(1)).getValueType(),
3051 getValue(I.getOperand(1))));
3053 case Intrinsic::pow:
3054 setValue(&I, DAG.getNode(ISD::FPOW,
3055 getValue(I.getOperand(1)).getValueType(),
3056 getValue(I.getOperand(1)),
3057 getValue(I.getOperand(2))));
3059 case Intrinsic::pcmarker: {
3060 SDOperand Tmp = getValue(I.getOperand(1));
3061 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3064 case Intrinsic::readcyclecounter: {
3065 SDOperand Op = getRoot();
3066 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3067 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3070 DAG.setRoot(Tmp.getValue(1));
3073 case Intrinsic::part_select: {
3074 // Currently not implemented: just abort
3075 assert(0 && "part_select intrinsic not implemented");
3078 case Intrinsic::part_set: {
3079 // Currently not implemented: just abort
3080 assert(0 && "part_set intrinsic not implemented");
3083 case Intrinsic::bswap:
3084 setValue(&I, DAG.getNode(ISD::BSWAP,
3085 getValue(I.getOperand(1)).getValueType(),
3086 getValue(I.getOperand(1))));
3088 case Intrinsic::cttz: {
3089 SDOperand Arg = getValue(I.getOperand(1));
3090 MVT::ValueType Ty = Arg.getValueType();
3091 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3092 setValue(&I, result);
3095 case Intrinsic::ctlz: {
3096 SDOperand Arg = getValue(I.getOperand(1));
3097 MVT::ValueType Ty = Arg.getValueType();
3098 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3099 setValue(&I, result);
3102 case Intrinsic::ctpop: {
3103 SDOperand Arg = getValue(I.getOperand(1));
3104 MVT::ValueType Ty = Arg.getValueType();
3105 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3106 setValue(&I, result);
3109 case Intrinsic::stacksave: {
3110 SDOperand Op = getRoot();
3111 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3112 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3114 DAG.setRoot(Tmp.getValue(1));
3117 case Intrinsic::stackrestore: {
3118 SDOperand Tmp = getValue(I.getOperand(1));
3119 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3122 case Intrinsic::var_annotation:
3123 // Discard annotate attributes
3126 case Intrinsic::init_trampoline: {
3128 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3132 Ops[1] = getValue(I.getOperand(1));
3133 Ops[2] = getValue(I.getOperand(2));
3134 Ops[3] = getValue(I.getOperand(3));
3135 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3136 Ops[5] = DAG.getSrcValue(F);
3138 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3139 DAG.getNodeValueTypes(TLI.getPointerTy(),
3144 DAG.setRoot(Tmp.getValue(1));
3148 case Intrinsic::gcroot:
3150 Value *Alloca = I.getOperand(1);
3151 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3153 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3154 GCI->addStackRoot(FI->getIndex(), TypeMap);
3158 case Intrinsic::gcread:
3159 case Intrinsic::gcwrite:
3160 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3163 case Intrinsic::flt_rounds: {
3164 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3168 case Intrinsic::trap: {
3169 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3172 case Intrinsic::prefetch: {
3175 Ops[1] = getValue(I.getOperand(1));
3176 Ops[2] = getValue(I.getOperand(2));
3177 Ops[3] = getValue(I.getOperand(3));
3178 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3182 case Intrinsic::memory_barrier: {
3185 for (int x = 1; x < 6; ++x)
3186 Ops[x] = getValue(I.getOperand(x));
3188 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3191 case Intrinsic::atomic_lcs: {
3192 SDOperand Root = getRoot();
3193 SDOperand O3 = getValue(I.getOperand(3));
3194 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3195 getValue(I.getOperand(1)),
3196 getValue(I.getOperand(2)),
3197 O3, O3.getValueType());
3199 DAG.setRoot(L.getValue(1));
3202 case Intrinsic::atomic_las: {
3203 SDOperand Root = getRoot();
3204 SDOperand O2 = getValue(I.getOperand(2));
3205 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root,
3206 getValue(I.getOperand(1)),
3207 O2, O2.getValueType());
3209 DAG.setRoot(L.getValue(1));
3212 case Intrinsic::atomic_swap: {
3213 SDOperand Root = getRoot();
3214 SDOperand O2 = getValue(I.getOperand(2));
3215 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root,
3216 getValue(I.getOperand(1)),
3217 O2, O2.getValueType());
3219 DAG.setRoot(L.getValue(1));
3227 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3229 MachineBasicBlock *LandingPad) {
3230 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3231 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3232 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3233 unsigned BeginLabel = 0, EndLabel = 0;
3235 TargetLowering::ArgListTy Args;
3236 TargetLowering::ArgListEntry Entry;
3237 Args.reserve(CS.arg_size());
3238 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3240 SDOperand ArgNode = getValue(*i);
3241 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3243 unsigned attrInd = i - CS.arg_begin() + 1;
3244 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3245 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3246 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3247 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3248 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3249 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3250 Entry.Alignment = CS.getParamAlignment(attrInd);
3251 Args.push_back(Entry);
3254 if (LandingPad && MMI) {
3255 // Insert a label before the invoke call to mark the try range. This can be
3256 // used to detect deletion of the invoke via the MachineModuleInfo.
3257 BeginLabel = MMI->NextLabelID();
3258 // Both PendingLoads and PendingExports must be flushed here;
3259 // this call might not return.
3261 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
3262 DAG.getConstant(BeginLabel, MVT::i32),
3263 DAG.getConstant(1, MVT::i32)));
3266 std::pair<SDOperand,SDOperand> Result =
3267 TLI.LowerCallTo(getRoot(), CS.getType(),
3268 CS.paramHasAttr(0, ParamAttr::SExt),
3269 CS.paramHasAttr(0, ParamAttr::ZExt),
3270 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3272 if (CS.getType() != Type::VoidTy)
3273 setValue(CS.getInstruction(), Result.first);
3274 DAG.setRoot(Result.second);
3276 if (LandingPad && MMI) {
3277 // Insert a label at the end of the invoke call to mark the try range. This
3278 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3279 EndLabel = MMI->NextLabelID();
3280 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3281 DAG.getConstant(EndLabel, MVT::i32),
3282 DAG.getConstant(1, MVT::i32)));
3284 // Inform MachineModuleInfo of range.
3285 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3290 void SelectionDAGLowering::visitCall(CallInst &I) {
3291 const char *RenameFn = 0;
3292 if (Function *F = I.getCalledFunction()) {
3293 if (F->isDeclaration()) {
3294 if (unsigned IID = F->getIntrinsicID()) {
3295 RenameFn = visitIntrinsicCall(I, IID);
3301 // Check for well-known libc/libm calls. If the function is internal, it
3302 // can't be a library call.
3303 unsigned NameLen = F->getNameLen();
3304 if (!F->hasInternalLinkage() && NameLen) {
3305 const char *NameStr = F->getNameStart();
3306 if (NameStr[0] == 'c' &&
3307 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3308 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3309 if (I.getNumOperands() == 3 && // Basic sanity checks.
3310 I.getOperand(1)->getType()->isFloatingPoint() &&
3311 I.getType() == I.getOperand(1)->getType() &&
3312 I.getType() == I.getOperand(2)->getType()) {
3313 SDOperand LHS = getValue(I.getOperand(1));
3314 SDOperand RHS = getValue(I.getOperand(2));
3315 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3319 } else if (NameStr[0] == 'f' &&
3320 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3321 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3322 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3323 if (I.getNumOperands() == 2 && // Basic sanity checks.
3324 I.getOperand(1)->getType()->isFloatingPoint() &&
3325 I.getType() == I.getOperand(1)->getType()) {
3326 SDOperand Tmp = getValue(I.getOperand(1));
3327 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3330 } else if (NameStr[0] == 's' &&
3331 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3332 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3333 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3334 if (I.getNumOperands() == 2 && // Basic sanity checks.
3335 I.getOperand(1)->getType()->isFloatingPoint() &&
3336 I.getType() == I.getOperand(1)->getType()) {
3337 SDOperand Tmp = getValue(I.getOperand(1));
3338 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3341 } else if (NameStr[0] == 'c' &&
3342 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3343 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3344 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3345 if (I.getNumOperands() == 2 && // Basic sanity checks.
3346 I.getOperand(1)->getType()->isFloatingPoint() &&
3347 I.getType() == I.getOperand(1)->getType()) {
3348 SDOperand Tmp = getValue(I.getOperand(1));
3349 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3354 } else if (isa<InlineAsm>(I.getOperand(0))) {
3361 Callee = getValue(I.getOperand(0));
3363 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3365 LowerCallTo(&I, Callee, I.isTailCall());
3369 void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3370 if (isa<UndefValue>(I.getOperand(0))) {
3371 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3372 setValue(&I, Undef);
3376 // To add support for individual return values with aggregate types,
3377 // we'd need a way to take a getresult index and determine which
3378 // values of the Call SDNode are associated with it.
3379 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3380 "Individual return values must not be aggregates!");
3382 SDOperand Call = getValue(I.getOperand(0));
3383 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3387 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3388 /// this value and returns the result as a ValueVT value. This uses
3389 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3390 /// If the Flag pointer is NULL, no flag is used.
3391 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3393 SDOperand *Flag) const {
3394 // Assemble the legal parts into the final values.
3395 SmallVector<SDOperand, 4> Values(ValueVTs.size());
3396 SmallVector<SDOperand, 8> Parts;
3397 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3398 // Copy the legal parts from the registers.
3399 MVT::ValueType ValueVT = ValueVTs[Value];
3400 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3401 MVT::ValueType RegisterVT = RegVTs[Value];
3403 Parts.resize(NumRegs);
3404 for (unsigned i = 0; i != NumRegs; ++i) {
3407 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3409 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3410 *Flag = P.getValue(2);
3412 Chain = P.getValue(1);
3416 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3421 if (ValueVTs.size() == 1)
3424 return DAG.getNode(ISD::MERGE_VALUES,
3425 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3426 &Values[0], ValueVTs.size());
3429 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3430 /// specified value into the registers specified by this object. This uses
3431 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3432 /// If the Flag pointer is NULL, no flag is used.
3433 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3434 SDOperand &Chain, SDOperand *Flag) const {
3435 // Get the list of the values's legal parts.
3436 unsigned NumRegs = Regs.size();
3437 SmallVector<SDOperand, 8> Parts(NumRegs);
3438 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3439 MVT::ValueType ValueVT = ValueVTs[Value];
3440 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3441 MVT::ValueType RegisterVT = RegVTs[Value];
3443 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3444 &Parts[Part], NumParts, RegisterVT);
3448 // Copy the parts into the registers.
3449 SmallVector<SDOperand, 8> Chains(NumRegs);
3450 for (unsigned i = 0; i != NumRegs; ++i) {
3453 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3455 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3456 *Flag = Part.getValue(1);
3458 Chains[i] = Part.getValue(0);
3464 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3467 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3468 /// operand list. This adds the code marker and includes the number of
3469 /// values added into it.
3470 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3471 std::vector<SDOperand> &Ops) const {
3472 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3473 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3474 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3475 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3476 MVT::ValueType RegisterVT = RegVTs[Value];
3477 for (unsigned i = 0; i != NumRegs; ++i)
3478 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3482 /// isAllocatableRegister - If the specified register is safe to allocate,
3483 /// i.e. it isn't a stack pointer or some other special register, return the
3484 /// register class for the register. Otherwise, return null.
3485 static const TargetRegisterClass *
3486 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3487 const TargetLowering &TLI,
3488 const TargetRegisterInfo *TRI) {
3489 MVT::ValueType FoundVT = MVT::Other;
3490 const TargetRegisterClass *FoundRC = 0;
3491 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3492 E = TRI->regclass_end(); RCI != E; ++RCI) {
3493 MVT::ValueType ThisVT = MVT::Other;
3495 const TargetRegisterClass *RC = *RCI;
3496 // If none of the the value types for this register class are valid, we
3497 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3498 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3500 if (TLI.isTypeLegal(*I)) {
3501 // If we have already found this register in a different register class,
3502 // choose the one with the largest VT specified. For example, on
3503 // PowerPC, we favor f64 register classes over f32.
3504 if (FoundVT == MVT::Other ||
3505 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3512 if (ThisVT == MVT::Other) continue;
3514 // NOTE: This isn't ideal. In particular, this might allocate the
3515 // frame pointer in functions that need it (due to them not being taken
3516 // out of allocation, because a variable sized allocation hasn't been seen
3517 // yet). This is a slight code pessimization, but should still work.
3518 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3519 E = RC->allocation_order_end(MF); I != E; ++I)
3521 // We found a matching register class. Keep looking at others in case
3522 // we find one with larger registers that this physreg is also in.
3533 /// AsmOperandInfo - This contains information for each constraint that we are
3535 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3536 /// CallOperand - If this is the result output operand or a clobber
3537 /// this is null, otherwise it is the incoming operand to the CallInst.
3538 /// This gets modified as the asm is processed.
3539 SDOperand CallOperand;
3541 /// AssignedRegs - If this is a register or register class operand, this
3542 /// contains the set of register corresponding to the operand.
3543 RegsForValue AssignedRegs;
3545 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3546 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3549 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3550 /// busy in OutputRegs/InputRegs.
3551 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3552 std::set<unsigned> &OutputRegs,
3553 std::set<unsigned> &InputRegs,
3554 const TargetRegisterInfo &TRI) const {
3556 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3557 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3560 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3561 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3566 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3568 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3569 const TargetRegisterInfo &TRI) {
3570 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3572 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3573 for (; *Aliases; ++Aliases)
3574 Regs.insert(*Aliases);
3577 } // end anon namespace.
3580 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3581 /// specified operand. We prefer to assign virtual registers, to allow the
3582 /// register allocator handle the assignment process. However, if the asm uses
3583 /// features that we can't model on machineinstrs, we have SDISel do the
3584 /// allocation. This produces generally horrible, but correct, code.
3586 /// OpInfo describes the operand.
3587 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3588 /// or any explicitly clobbered registers.
3589 /// Input and OutputRegs are the set of already allocated physical registers.
3591 void SelectionDAGLowering::
3592 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3593 std::set<unsigned> &OutputRegs,
3594 std::set<unsigned> &InputRegs) {
3595 // Compute whether this value requires an input register, an output register,
3597 bool isOutReg = false;
3598 bool isInReg = false;
3599 switch (OpInfo.Type) {
3600 case InlineAsm::isOutput:
3603 // If this is an early-clobber output, or if there is an input
3604 // constraint that matches this, we need to reserve the input register
3605 // so no other inputs allocate to it.
3606 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3608 case InlineAsm::isInput:
3612 case InlineAsm::isClobber:
3619 MachineFunction &MF = DAG.getMachineFunction();
3620 SmallVector<unsigned, 4> Regs;
3622 // If this is a constraint for a single physreg, or a constraint for a
3623 // register class, find it.
3624 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3625 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3626 OpInfo.ConstraintVT);
3628 unsigned NumRegs = 1;
3629 if (OpInfo.ConstraintVT != MVT::Other)
3630 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3631 MVT::ValueType RegVT;
3632 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3635 // If this is a constraint for a specific physical register, like {r17},
3637 if (PhysReg.first) {
3638 if (OpInfo.ConstraintVT == MVT::Other)
3639 ValueVT = *PhysReg.second->vt_begin();
3641 // Get the actual register value type. This is important, because the user
3642 // may have asked for (e.g.) the AX register in i32 type. We need to
3643 // remember that AX is actually i16 to get the right extension.
3644 RegVT = *PhysReg.second->vt_begin();
3646 // This is a explicit reference to a physical register.
3647 Regs.push_back(PhysReg.first);
3649 // If this is an expanded reference, add the rest of the regs to Regs.
3651 TargetRegisterClass::iterator I = PhysReg.second->begin();
3652 TargetRegisterClass::iterator E = PhysReg.second->end();
3653 for (; *I != PhysReg.first; ++I)
3654 assert(I != E && "Didn't find reg!");
3656 // Already added the first reg.
3658 for (; NumRegs; --NumRegs, ++I) {
3659 assert(I != E && "Ran out of registers to allocate!");
3663 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3664 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3665 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3669 // Otherwise, if this was a reference to an LLVM register class, create vregs
3670 // for this reference.
3671 std::vector<unsigned> RegClassRegs;
3672 const TargetRegisterClass *RC = PhysReg.second;
3674 // If this is an early clobber or tied register, our regalloc doesn't know
3675 // how to maintain the constraint. If it isn't, go ahead and create vreg
3676 // and let the regalloc do the right thing.
3677 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3678 // If there is some other early clobber and this is an input register,
3679 // then we are forced to pre-allocate the input reg so it doesn't
3680 // conflict with the earlyclobber.
3681 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3682 RegVT = *PhysReg.second->vt_begin();
3684 if (OpInfo.ConstraintVT == MVT::Other)
3687 // Create the appropriate number of virtual registers.
3688 MachineRegisterInfo &RegInfo = MF.getRegInfo();
3689 for (; NumRegs; --NumRegs)
3690 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
3692 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3696 // Otherwise, we can't allocate it. Let the code below figure out how to
3697 // maintain these constraints.
3698 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3701 // This is a reference to a register class that doesn't directly correspond
3702 // to an LLVM register class. Allocate NumRegs consecutive, available,
3703 // registers from the class.
3704 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3705 OpInfo.ConstraintVT);
3708 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3709 unsigned NumAllocated = 0;
3710 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3711 unsigned Reg = RegClassRegs[i];
3712 // See if this register is available.
3713 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3714 (isInReg && InputRegs.count(Reg))) { // Already used.
3715 // Make sure we find consecutive registers.
3720 // Check to see if this register is allocatable (i.e. don't give out the
3723 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
3724 if (!RC) { // Couldn't allocate this register.
3725 // Reset NumAllocated to make sure we return consecutive registers.
3731 // Okay, this register is good, we can use it.
3734 // If we allocated enough consecutive registers, succeed.
3735 if (NumAllocated == NumRegs) {
3736 unsigned RegStart = (i-NumAllocated)+1;
3737 unsigned RegEnd = i+1;
3738 // Mark all of the allocated registers used.
3739 for (unsigned i = RegStart; i != RegEnd; ++i)
3740 Regs.push_back(RegClassRegs[i]);
3742 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
3743 OpInfo.ConstraintVT);
3744 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3749 // Otherwise, we couldn't allocate enough registers for this.
3754 /// visitInlineAsm - Handle a call to an InlineAsm object.
3756 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3757 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3759 /// ConstraintOperands - Information about all of the constraints.
3760 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
3762 SDOperand Chain = getRoot();
3765 std::set<unsigned> OutputRegs, InputRegs;
3767 // Do a prepass over the constraints, canonicalizing them, and building up the
3768 // ConstraintOperands list.
3769 std::vector<InlineAsm::ConstraintInfo>
3770 ConstraintInfos = IA->ParseConstraints();
3772 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3773 // constraint. If so, we can't let the register allocator allocate any input
3774 // registers, because it will not know to avoid the earlyclobbered output reg.
3775 bool SawEarlyClobber = false;
3777 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3778 unsigned ResNo = 0; // ResNo - The result number of the next output.
3779 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3780 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3781 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
3783 MVT::ValueType OpVT = MVT::Other;
3785 // Compute the value type for each operand.
3786 switch (OpInfo.Type) {
3787 case InlineAsm::isOutput:
3788 // Indirect outputs just consume an argument.
3789 if (OpInfo.isIndirect) {
3790 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3793 // The return value of the call is this value. As such, there is no
3794 // corresponding argument.
3795 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3796 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3797 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3799 assert(ResNo == 0 && "Asm only has one result!");
3800 OpVT = TLI.getValueType(CS.getType());
3804 case InlineAsm::isInput:
3805 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3807 case InlineAsm::isClobber:
3812 // If this is an input or an indirect output, process the call argument.
3813 // BasicBlocks are labels, currently appearing only in asm's.
3814 if (OpInfo.CallOperandVal) {
3815 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3816 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
3818 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3819 const Type *OpTy = OpInfo.CallOperandVal->getType();
3820 // If this is an indirect operand, the operand is a pointer to the
3822 if (OpInfo.isIndirect)
3823 OpTy = cast<PointerType>(OpTy)->getElementType();
3825 // If OpTy is not a first-class value, it may be a struct/union that we
3826 // can tile with integers.
3827 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3828 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3836 OpTy = IntegerType::get(BitSize);
3841 OpVT = TLI.getValueType(OpTy, true);
3845 OpInfo.ConstraintVT = OpVT;
3847 // Compute the constraint code and ConstraintType to use.
3848 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
3850 // Keep track of whether we see an earlyclobber.
3851 SawEarlyClobber |= OpInfo.isEarlyClobber;
3853 // If we see a clobber of a register, it is an early clobber.
3854 if (!SawEarlyClobber &&
3855 OpInfo.Type == InlineAsm::isClobber &&
3856 OpInfo.ConstraintType == TargetLowering::C_Register) {
3857 // Note that we want to ignore things that we don't trick here, like
3858 // dirflag, fpsr, flags, etc.
3859 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3860 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3861 OpInfo.ConstraintVT);
3862 if (PhysReg.first || PhysReg.second) {
3863 // This is a register we know of.
3864 SawEarlyClobber = true;
3868 // If this is a memory input, and if the operand is not indirect, do what we
3869 // need to to provide an address for the memory input.
3870 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3871 !OpInfo.isIndirect) {
3872 assert(OpInfo.Type == InlineAsm::isInput &&
3873 "Can only indirectify direct input operands!");
3875 // Memory operands really want the address of the value. If we don't have
3876 // an indirect input, put it in the constpool if we can, otherwise spill
3877 // it to a stack slot.
3879 // If the operand is a float, integer, or vector constant, spill to a
3880 // constant pool entry to get its address.
3881 Value *OpVal = OpInfo.CallOperandVal;
3882 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3883 isa<ConstantVector>(OpVal)) {
3884 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3885 TLI.getPointerTy());
3887 // Otherwise, create a stack slot and emit a store to it before the
3889 const Type *Ty = OpVal->getType();
3890 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
3891 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3892 MachineFunction &MF = DAG.getMachineFunction();
3893 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3894 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3895 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3896 OpInfo.CallOperand = StackSlot;
3899 // There is no longer a Value* corresponding to this operand.
3900 OpInfo.CallOperandVal = 0;
3901 // It is now an indirect operand.
3902 OpInfo.isIndirect = true;
3905 // If this constraint is for a specific register, allocate it before
3907 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3908 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3910 ConstraintInfos.clear();
3913 // Second pass - Loop over all of the operands, assigning virtual or physregs
3914 // to registerclass operands.
3915 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3916 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3918 // C_Register operands have already been allocated, Other/Memory don't need
3920 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3921 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3924 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3925 std::vector<SDOperand> AsmNodeOperands;
3926 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3927 AsmNodeOperands.push_back(
3928 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3931 // Loop over all of the inputs, copying the operand values into the
3932 // appropriate registers and processing the output regs.
3933 RegsForValue RetValRegs;
3935 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3936 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3938 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3939 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3941 switch (OpInfo.Type) {
3942 case InlineAsm::isOutput: {
3943 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3944 OpInfo.ConstraintType != TargetLowering::C_Register) {
3945 // Memory output, or 'other' output (e.g. 'X' constraint).
3946 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3948 // Add information to the INLINEASM node to know about this output.
3949 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3950 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3951 TLI.getPointerTy()));
3952 AsmNodeOperands.push_back(OpInfo.CallOperand);
3956 // Otherwise, this is a register or register class output.
3958 // Copy the output from the appropriate register. Find a register that
3960 if (OpInfo.AssignedRegs.Regs.empty()) {
3961 cerr << "Couldn't allocate output reg for contraint '"
3962 << OpInfo.ConstraintCode << "'!\n";
3966 if (!OpInfo.isIndirect) {
3967 // This is the result value of the call.
3968 assert(RetValRegs.Regs.empty() &&
3969 "Cannot have multiple output constraints yet!");
3970 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3971 RetValRegs = OpInfo.AssignedRegs;
3973 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
3974 OpInfo.CallOperandVal));
3977 // Add information to the INLINEASM node to know that this register is
3979 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3983 case InlineAsm::isInput: {
3984 SDOperand InOperandVal = OpInfo.CallOperand;
3986 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
3987 // If this is required to match an output register we have already set,
3988 // just use its register.
3989 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
3991 // Scan until we find the definition we already emitted of this operand.
3992 // When we find it, create a RegsForValue operand.
3993 unsigned CurOp = 2; // The first operand.
3994 for (; OperandNo; --OperandNo) {
3995 // Advance to the next operand.
3997 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3998 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3999 (NumOps & 7) == 4 /*MEM*/) &&
4000 "Skipped past definitions?");
4001 CurOp += (NumOps>>3)+1;
4005 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4006 if ((NumOps & 7) == 2 /*REGDEF*/) {
4007 // Add NumOps>>3 registers to MatchedRegs.
4008 RegsForValue MatchedRegs;
4009 MatchedRegs.TLI = &TLI;
4010 MatchedRegs.ValueVTs.resize(1, InOperandVal.getValueType());
4011 MatchedRegs.RegVTs.resize(1, AsmNodeOperands[CurOp+1].getValueType());
4012 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4014 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4015 MatchedRegs.Regs.push_back(Reg);
4018 // Use the produced MatchedRegs object to
4019 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4020 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4023 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4024 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4025 // Add information to the INLINEASM node to know about this input.
4026 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4027 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4028 TLI.getPointerTy()));
4029 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4034 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4035 assert(!OpInfo.isIndirect &&
4036 "Don't know how to handle indirect other inputs yet!");
4038 std::vector<SDOperand> Ops;
4039 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4042 cerr << "Invalid operand for inline asm constraint '"
4043 << OpInfo.ConstraintCode << "'!\n";
4047 // Add information to the INLINEASM node to know about this input.
4048 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4049 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4050 TLI.getPointerTy()));
4051 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4053 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4054 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4055 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4056 "Memory operands expect pointer values");
4058 // Add information to the INLINEASM node to know about this input.
4059 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4060 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4061 TLI.getPointerTy()));
4062 AsmNodeOperands.push_back(InOperandVal);
4066 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4067 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4068 "Unknown constraint type!");
4069 assert(!OpInfo.isIndirect &&
4070 "Don't know how to handle indirect register inputs yet!");
4072 // Copy the input into the appropriate registers.
4073 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4074 "Couldn't allocate input reg!");
4076 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4078 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4082 case InlineAsm::isClobber: {
4083 // Add the clobbered value to the operand list, so that the register
4084 // allocator is aware that the physreg got clobbered.
4085 if (!OpInfo.AssignedRegs.Regs.empty())
4086 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4093 // Finish up input operands.
4094 AsmNodeOperands[0] = Chain;
4095 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4097 Chain = DAG.getNode(ISD::INLINEASM,
4098 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4099 &AsmNodeOperands[0], AsmNodeOperands.size());
4100 Flag = Chain.getValue(1);
4102 // If this asm returns a register value, copy the result from that register
4103 // and set it as the value of the call.
4104 if (!RetValRegs.Regs.empty()) {
4105 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4107 // If the result of the inline asm is a vector, it may have the wrong
4108 // width/num elts. Make sure to convert it to the right type with
4110 if (MVT::isVector(Val.getValueType())) {
4111 const VectorType *VTy = cast<VectorType>(CS.getType());
4112 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
4114 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
4117 setValue(CS.getInstruction(), Val);
4120 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4122 // Process indirect outputs, first output all of the flagged copies out of
4124 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4125 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4126 Value *Ptr = IndirectStoresToEmit[i].second;
4127 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4128 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4131 // Emit the non-flagged stores from the physregs.
4132 SmallVector<SDOperand, 8> OutChains;
4133 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4134 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4135 getValue(StoresToEmit[i].second),
4136 StoresToEmit[i].second, 0));
4137 if (!OutChains.empty())
4138 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4139 &OutChains[0], OutChains.size());
4144 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4145 SDOperand Src = getValue(I.getOperand(0));
4147 MVT::ValueType IntPtr = TLI.getPointerTy();
4149 if (IntPtr < Src.getValueType())
4150 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4151 else if (IntPtr > Src.getValueType())
4152 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4154 // Scale the source by the type size.
4155 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4156 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4157 Src, DAG.getIntPtrConstant(ElementSize));
4159 TargetLowering::ArgListTy Args;
4160 TargetLowering::ArgListEntry Entry;
4162 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4163 Args.push_back(Entry);
4165 std::pair<SDOperand,SDOperand> Result =
4166 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4167 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4168 setValue(&I, Result.first); // Pointers always fit in registers
4169 DAG.setRoot(Result.second);
4172 void SelectionDAGLowering::visitFree(FreeInst &I) {
4173 TargetLowering::ArgListTy Args;
4174 TargetLowering::ArgListEntry Entry;
4175 Entry.Node = getValue(I.getOperand(0));
4176 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4177 Args.push_back(Entry);
4178 MVT::ValueType IntPtr = TLI.getPointerTy();
4179 std::pair<SDOperand,SDOperand> Result =
4180 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4181 CallingConv::C, true,
4182 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4183 DAG.setRoot(Result.second);
4186 // EmitInstrWithCustomInserter - This method should be implemented by targets
4187 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
4188 // instructions are special in various ways, which require special support to
4189 // insert. The specified MachineInstr is created but not inserted into any
4190 // basic blocks, and the scheduler passes ownership of it to this method.
4191 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4192 MachineBasicBlock *MBB) {
4193 cerr << "If a target marks an instruction with "
4194 << "'usesCustomDAGSchedInserter', it must implement "
4195 << "TargetLowering::EmitInstrWithCustomInserter!\n";
4200 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4201 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4202 getValue(I.getOperand(1)),
4203 DAG.getSrcValue(I.getOperand(1))));
4206 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4207 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4208 getValue(I.getOperand(0)),
4209 DAG.getSrcValue(I.getOperand(0)));
4211 DAG.setRoot(V.getValue(1));
4214 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4215 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4216 getValue(I.getOperand(1)),
4217 DAG.getSrcValue(I.getOperand(1))));
4220 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4221 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4222 getValue(I.getOperand(1)),
4223 getValue(I.getOperand(2)),
4224 DAG.getSrcValue(I.getOperand(1)),
4225 DAG.getSrcValue(I.getOperand(2))));
4228 /// TargetLowering::LowerArguments - This is the default LowerArguments
4229 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4230 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4231 /// integrated into SDISel.
4232 std::vector<SDOperand>
4233 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4234 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4235 std::vector<SDOperand> Ops;
4236 Ops.push_back(DAG.getRoot());
4237 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4238 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4240 // Add one result value for each formal argument.
4241 std::vector<MVT::ValueType> RetVals;
4243 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4245 MVT::ValueType VT = getValueType(I->getType());
4246 ISD::ArgFlagsTy Flags;
4247 unsigned OriginalAlignment =
4248 getTargetData()->getABITypeAlignment(I->getType());
4250 if (F.paramHasAttr(j, ParamAttr::ZExt))
4252 if (F.paramHasAttr(j, ParamAttr::SExt))
4254 if (F.paramHasAttr(j, ParamAttr::InReg))
4256 if (F.paramHasAttr(j, ParamAttr::StructRet))
4258 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4260 const PointerType *Ty = cast<PointerType>(I->getType());
4261 const Type *ElementTy = Ty->getElementType();
4262 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4263 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4264 // For ByVal, alignment should be passed from FE. BE will guess if
4265 // this info is not there but there are cases it cannot get right.
4266 if (F.getParamAlignment(j))
4267 FrameAlign = F.getParamAlignment(j);
4268 Flags.setByValAlign(FrameAlign);
4269 Flags.setByValSize(FrameSize);
4271 if (F.paramHasAttr(j, ParamAttr::Nest))
4273 Flags.setOrigAlign(OriginalAlignment);
4275 MVT::ValueType RegisterVT = getRegisterType(VT);
4276 unsigned NumRegs = getNumRegisters(VT);
4277 for (unsigned i = 0; i != NumRegs; ++i) {
4278 RetVals.push_back(RegisterVT);
4279 ISD::ArgFlagsTy MyFlags = Flags;
4280 if (NumRegs > 1 && i == 0)
4282 // if it isn't first piece, alignment must be 1
4284 MyFlags.setOrigAlign(1);
4285 Ops.push_back(DAG.getArgFlags(MyFlags));
4289 RetVals.push_back(MVT::Other);
4292 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4293 DAG.getVTList(&RetVals[0], RetVals.size()),
4294 &Ops[0], Ops.size()).Val;
4296 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4297 // allows exposing the loads that may be part of the argument access to the
4298 // first DAGCombiner pass.
4299 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4301 // The number of results should match up, except that the lowered one may have
4302 // an extra flag result.
4303 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4304 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4305 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4306 && "Lowering produced unexpected number of results!");
4307 Result = TmpRes.Val;
4309 unsigned NumArgRegs = Result->getNumValues() - 1;
4310 DAG.setRoot(SDOperand(Result, NumArgRegs));
4312 // Set up the return result vector.
4316 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4318 MVT::ValueType VT = getValueType(I->getType());
4319 MVT::ValueType PartVT = getRegisterType(VT);
4321 unsigned NumParts = getNumRegisters(VT);
4322 SmallVector<SDOperand, 4> Parts(NumParts);
4323 for (unsigned j = 0; j != NumParts; ++j)
4324 Parts[j] = SDOperand(Result, i++);
4326 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4327 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4328 AssertOp = ISD::AssertSext;
4329 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4330 AssertOp = ISD::AssertZext;
4332 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4335 assert(i == NumArgRegs && "Argument register count mismatch!");
4340 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4341 /// implementation, which just inserts an ISD::CALL node, which is later custom
4342 /// lowered by the target to something concrete. FIXME: When all targets are
4343 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4344 std::pair<SDOperand, SDOperand>
4345 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4346 bool RetSExt, bool RetZExt, bool isVarArg,
4347 unsigned CallingConv, bool isTailCall,
4349 ArgListTy &Args, SelectionDAG &DAG) {
4350 SmallVector<SDOperand, 32> Ops;
4351 Ops.push_back(Chain); // Op#0 - Chain
4352 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4353 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4354 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4355 Ops.push_back(Callee);
4357 // Handle all of the outgoing arguments.
4358 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4359 MVT::ValueType VT = getValueType(Args[i].Ty);
4360 SDOperand Op = Args[i].Node;
4361 ISD::ArgFlagsTy Flags;
4362 unsigned OriginalAlignment =
4363 getTargetData()->getABITypeAlignment(Args[i].Ty);
4369 if (Args[i].isInReg)
4373 if (Args[i].isByVal) {
4375 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4376 const Type *ElementTy = Ty->getElementType();
4377 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4378 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4379 // For ByVal, alignment should come from FE. BE will guess if this
4380 // info is not there but there are cases it cannot get right.
4381 if (Args[i].Alignment)
4382 FrameAlign = Args[i].Alignment;
4383 Flags.setByValAlign(FrameAlign);
4384 Flags.setByValSize(FrameSize);
4388 Flags.setOrigAlign(OriginalAlignment);
4390 MVT::ValueType PartVT = getRegisterType(VT);
4391 unsigned NumParts = getNumRegisters(VT);
4392 SmallVector<SDOperand, 4> Parts(NumParts);
4393 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4396 ExtendKind = ISD::SIGN_EXTEND;
4397 else if (Args[i].isZExt)
4398 ExtendKind = ISD::ZERO_EXTEND;
4400 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4402 for (unsigned i = 0; i != NumParts; ++i) {
4403 // if it isn't first piece, alignment must be 1
4404 ISD::ArgFlagsTy MyFlags = Flags;
4405 if (NumParts > 1 && i == 0)
4408 MyFlags.setOrigAlign(1);
4410 Ops.push_back(Parts[i]);
4411 Ops.push_back(DAG.getArgFlags(MyFlags));
4415 // Figure out the result value types. We start by making a list of
4416 // the potentially illegal return value types.
4417 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4418 SmallVector<MVT::ValueType, 4> RetTys;
4419 ComputeValueVTs(*this, RetTy, RetTys);
4421 // Then we translate that to a list of legal types.
4422 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4423 MVT::ValueType VT = RetTys[I];
4424 MVT::ValueType RegisterVT = getRegisterType(VT);
4425 unsigned NumRegs = getNumRegisters(VT);
4426 for (unsigned i = 0; i != NumRegs; ++i)
4427 LoweredRetTys.push_back(RegisterVT);
4430 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4432 // Create the CALL node.
4433 SDOperand Res = DAG.getNode(ISD::CALL,
4434 DAG.getVTList(&LoweredRetTys[0],
4435 LoweredRetTys.size()),
4436 &Ops[0], Ops.size());
4437 Chain = Res.getValue(LoweredRetTys.size() - 1);
4439 // Gather up the call result into a single value.
4440 if (RetTy != Type::VoidTy) {
4441 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4444 AssertOp = ISD::AssertSext;
4446 AssertOp = ISD::AssertZext;
4448 SmallVector<SDOperand, 4> ReturnValues;
4450 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4451 MVT::ValueType VT = RetTys[I];
4452 MVT::ValueType RegisterVT = getRegisterType(VT);
4453 unsigned NumRegs = getNumRegisters(VT);
4454 unsigned RegNoEnd = NumRegs + RegNo;
4455 SmallVector<SDOperand, 4> Results;
4456 for (; RegNo != RegNoEnd; ++RegNo)
4457 Results.push_back(Res.getValue(RegNo));
4458 SDOperand ReturnValue =
4459 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4461 ReturnValues.push_back(ReturnValue);
4463 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4464 DAG.getNode(ISD::MERGE_VALUES,
4465 DAG.getVTList(&RetTys[0], RetTys.size()),
4466 &ReturnValues[0], ReturnValues.size());
4469 return std::make_pair(Res, Chain);
4472 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4473 assert(0 && "LowerOperation not implemented for this target!");
4478 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4479 SelectionDAG &DAG) {
4480 assert(0 && "CustomPromoteOperation not implemented for this target!");
4485 //===----------------------------------------------------------------------===//
4486 // SelectionDAGISel code
4487 //===----------------------------------------------------------------------===//
4489 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4490 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4493 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4494 AU.addRequired<AliasAnalysis>();
4495 AU.addRequired<CollectorModuleMetadata>();
4496 AU.setPreservesAll();
4501 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4502 // Get alias analysis for load/store combining.
4503 AA = &getAnalysis<AliasAnalysis>();
4505 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4506 if (MF.getFunction()->hasCollector())
4507 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4510 RegInfo = &MF.getRegInfo();
4511 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4513 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4515 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4516 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4517 // Mark landing pad.
4518 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4520 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4521 SelectBasicBlock(I, MF, FuncInfo);
4523 // Add function live-ins to entry block live-in set.
4524 BasicBlock *EntryBB = &Fn.getEntryBlock();
4525 BB = FuncInfo.MBBMap[EntryBB];
4526 if (!RegInfo->livein_empty())
4527 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4528 E = RegInfo->livein_end(); I != E; ++I)
4529 BB->addLiveIn(I->first);
4532 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4533 "Not all catch info was assigned to a landing pad!");
4539 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4540 SDOperand Op = getValue(V);
4541 assert((Op.getOpcode() != ISD::CopyFromReg ||
4542 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4543 "Copy from a reg to the same reg!");
4544 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4546 RegsForValue RFV(TLI, Reg, V->getType());
4547 SDOperand Chain = DAG.getEntryNode();
4548 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4549 PendingExports.push_back(Chain);
4552 void SelectionDAGISel::
4553 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4554 // If this is the entry block, emit arguments.
4555 Function &F = *LLVMBB->getParent();
4556 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4557 SDOperand OldRoot = SDL.DAG.getRoot();
4558 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4561 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4563 if (!AI->use_empty()) {
4564 SDL.setValue(AI, Args[a]);
4566 // If this argument is live outside of the entry block, insert a copy from
4567 // whereever we got it to the vreg that other BB's will reference it as.
4568 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4569 if (VMI != FuncInfo.ValueMap.end()) {
4570 SDL.CopyValueToVirtualRegister(AI, VMI->second);
4574 // Finally, if the target has anything special to do, allow it to do so.
4575 // FIXME: this should insert code into the DAG!
4576 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4579 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4580 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4581 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4582 if (isSelector(I)) {
4583 // Apply the catch info to DestBB.
4584 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4586 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4587 FLI.CatchInfoFound.insert(I);
4592 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
4593 /// DAG and fixes their tailcall attribute operand.
4594 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4595 TargetLowering& TLI) {
4596 SDNode * Ret = NULL;
4597 SDOperand Terminator = DAG.getRoot();
4600 if (Terminator.getOpcode() == ISD::RET) {
4601 Ret = Terminator.Val;
4604 // Fix tail call attribute of CALL nodes.
4605 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4606 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4607 if (BI->getOpcode() == ISD::CALL) {
4608 SDOperand OpRet(Ret, 0);
4609 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4610 bool isMarkedTailCall =
4611 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4612 // If CALL node has tail call attribute set to true and the call is not
4613 // eligible (no RET or the target rejects) the attribute is fixed to
4614 // false. The TargetLowering::IsEligibleForTailCallOptimization function
4615 // must correctly identify tail call optimizable calls.
4616 if (isMarkedTailCall &&
4618 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) {
4619 SmallVector<SDOperand, 32> Ops;
4621 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4622 E=OpCall.Val->op_end(); I!=E; I++, idx++) {
4626 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4628 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4634 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4635 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4636 FunctionLoweringInfo &FuncInfo) {
4637 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
4639 // Lower any arguments needed in this block if this is the entry block.
4640 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4641 LowerArguments(LLVMBB, SDL);
4643 BB = FuncInfo.MBBMap[LLVMBB];
4644 SDL.setCurrentBasicBlock(BB);
4646 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4648 if (MMI && BB->isLandingPad()) {
4649 // Add a label to mark the beginning of the landing pad. Deletion of the
4650 // landing pad can thus be detected via the MachineModuleInfo.
4651 unsigned LabelID = MMI->addLandingPad(BB);
4652 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4653 DAG.getConstant(LabelID, MVT::i32),
4654 DAG.getConstant(1, MVT::i32)));
4656 // Mark exception register as live in.
4657 unsigned Reg = TLI.getExceptionAddressRegister();
4658 if (Reg) BB->addLiveIn(Reg);
4660 // Mark exception selector register as live in.
4661 Reg = TLI.getExceptionSelectorRegister();
4662 if (Reg) BB->addLiveIn(Reg);
4664 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4665 // function and list of typeids logically belong to the invoke (or, if you
4666 // like, the basic block containing the invoke), and need to be associated
4667 // with it in the dwarf exception handling tables. Currently however the
4668 // information is provided by an intrinsic (eh.selector) that can be moved
4669 // to unexpected places by the optimizers: if the unwind edge is critical,
4670 // then breaking it can result in the intrinsics being in the successor of
4671 // the landing pad, not the landing pad itself. This results in exceptions
4672 // not being caught because no typeids are associated with the invoke.
4673 // This may not be the only way things can go wrong, but it is the only way
4674 // we try to work around for the moment.
4675 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4677 if (Br && Br->isUnconditional()) { // Critical edge?
4678 BasicBlock::iterator I, E;
4679 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4684 // No catch info found - try to extract some from the successor.
4685 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
4689 // Lower all of the non-terminator instructions.
4690 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4694 // Ensure that all instructions which are used outside of their defining
4695 // blocks are available as virtual registers. Invoke is handled elsewhere.
4696 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4697 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
4698 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4699 if (VMI != FuncInfo.ValueMap.end())
4700 SDL.CopyValueToVirtualRegister(I, VMI->second);
4703 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4704 // ensure constants are generated when needed. Remember the virtual registers
4705 // that need to be added to the Machine PHI nodes as input. We cannot just
4706 // directly add them, because expansion might result in multiple MBB's for one
4707 // BB. As such, the start of the BB might correspond to a different MBB than
4710 TerminatorInst *TI = LLVMBB->getTerminator();
4712 // Emit constants only once even if used by multiple PHI nodes.
4713 std::map<Constant*, unsigned> ConstantsOut;
4715 // Vector bool would be better, but vector<bool> is really slow.
4716 std::vector<unsigned char> SuccsHandled;
4717 if (TI->getNumSuccessors())
4718 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4720 // Check successor nodes' PHI nodes that expect a constant to be available
4722 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4723 BasicBlock *SuccBB = TI->getSuccessor(succ);
4724 if (!isa<PHINode>(SuccBB->begin())) continue;
4725 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4727 // If this terminator has multiple identical successors (common for
4728 // switches), only handle each succ once.
4729 unsigned SuccMBBNo = SuccMBB->getNumber();
4730 if (SuccsHandled[SuccMBBNo]) continue;
4731 SuccsHandled[SuccMBBNo] = true;
4733 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4736 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4737 // nodes and Machine PHI nodes, but the incoming operands have not been
4739 for (BasicBlock::iterator I = SuccBB->begin();
4740 (PN = dyn_cast<PHINode>(I)); ++I) {
4741 // Ignore dead phi's.
4742 if (PN->use_empty()) continue;
4745 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4747 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4748 unsigned &RegOut = ConstantsOut[C];
4750 RegOut = FuncInfo.CreateRegForValue(C);
4751 SDL.CopyValueToVirtualRegister(C, RegOut);
4755 Reg = FuncInfo.ValueMap[PHIOp];
4757 assert(isa<AllocaInst>(PHIOp) &&
4758 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4759 "Didn't codegen value into a register!??");
4760 Reg = FuncInfo.CreateRegForValue(PHIOp);
4761 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
4765 // Remember that this register needs to added to the machine PHI node as
4766 // the input for this MBB.
4767 MVT::ValueType VT = TLI.getValueType(PN->getType());
4768 unsigned NumRegisters = TLI.getNumRegisters(VT);
4769 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4770 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4773 ConstantsOut.clear();
4775 // Lower the terminator after the copies are emitted.
4776 SDL.visit(*LLVMBB->getTerminator());
4778 // Copy over any CaseBlock records that may now exist due to SwitchInst
4779 // lowering, as well as any jump table information.
4780 SwitchCases.clear();
4781 SwitchCases = SDL.SwitchCases;
4783 JTCases = SDL.JTCases;
4784 BitTestCases.clear();
4785 BitTestCases = SDL.BitTestCases;
4787 // Make sure the root of the DAG is up-to-date.
4788 DAG.setRoot(SDL.getControlRoot());
4790 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4791 // with correct tailcall attribute so that the target can rely on the tailcall
4792 // attribute indicating whether the call is really eligible for tail call
4794 CheckDAGForTailCallsAndFixThem(DAG, TLI);
4797 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4798 DOUT << "Lowered selection DAG:\n";
4801 // Run the DAG combiner in pre-legalize mode.
4802 DAG.Combine(false, *AA);
4804 DOUT << "Optimized lowered selection DAG:\n";
4807 // Second step, hack on the DAG until it only uses operations and types that
4808 // the target supports.
4809 #if 0 // Enable this some day.
4810 DAG.LegalizeTypes();
4811 // Someday even later, enable a dag combine pass here.
4815 DOUT << "Legalized selection DAG:\n";
4818 // Run the DAG combiner in post-legalize mode.
4819 DAG.Combine(true, *AA);
4821 DOUT << "Optimized legalized selection DAG:\n";
4824 if (ViewISelDAGs) DAG.viewGraph();
4826 // Third, instruction select all of the operations to machine code, adding the
4827 // code to the MachineBasicBlock.
4828 InstructionSelectBasicBlock(DAG);
4830 DOUT << "Selected machine code:\n";
4834 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4835 FunctionLoweringInfo &FuncInfo) {
4836 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4838 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4841 // First step, lower LLVM code to some DAG. This DAG may use operations and
4842 // types that are not supported by the target.
4843 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4845 // Second step, emit the lowered DAG as machine code.
4846 CodeGenAndEmitDAG(DAG);
4849 DOUT << "Total amount of phi nodes to update: "
4850 << PHINodesToUpdate.size() << "\n";
4851 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4852 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4853 << ", " << PHINodesToUpdate[i].second << ")\n";);
4855 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4856 // PHI nodes in successors.
4857 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4858 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4859 MachineInstr *PHI = PHINodesToUpdate[i].first;
4860 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4861 "This is not a machine PHI node that we are updating!");
4862 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4864 PHI->addOperand(MachineOperand::CreateMBB(BB));
4869 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4870 // Lower header first, if it wasn't already lowered
4871 if (!BitTestCases[i].Emitted) {
4872 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4874 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
4875 // Set the current basic block to the mbb we wish to insert the code into
4876 BB = BitTestCases[i].Parent;
4877 HSDL.setCurrentBasicBlock(BB);
4879 HSDL.visitBitTestHeader(BitTestCases[i]);
4880 HSDAG.setRoot(HSDL.getRoot());
4881 CodeGenAndEmitDAG(HSDAG);
4884 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4885 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4887 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
4888 // Set the current basic block to the mbb we wish to insert the code into
4889 BB = BitTestCases[i].Cases[j].ThisBB;
4890 BSDL.setCurrentBasicBlock(BB);
4893 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4894 BitTestCases[i].Reg,
4895 BitTestCases[i].Cases[j]);
4897 BSDL.visitBitTestCase(BitTestCases[i].Default,
4898 BitTestCases[i].Reg,
4899 BitTestCases[i].Cases[j]);
4902 BSDAG.setRoot(BSDL.getRoot());
4903 CodeGenAndEmitDAG(BSDAG);
4907 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4908 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4909 MachineBasicBlock *PHIBB = PHI->getParent();
4910 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4911 "This is not a machine PHI node that we are updating!");
4912 // This is "default" BB. We have two jumps to it. From "header" BB and
4913 // from last "case" BB.
4914 if (PHIBB == BitTestCases[i].Default) {
4915 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4917 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
4918 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4920 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
4923 // One of "cases" BB.
4924 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4925 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4926 if (cBB->succ_end() !=
4927 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4928 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4930 PHI->addOperand(MachineOperand::CreateMBB(cBB));
4936 // If the JumpTable record is filled in, then we need to emit a jump table.
4937 // Updating the PHI nodes is tricky in this case, since we need to determine
4938 // whether the PHI is a successor of the range check MBB or the jump table MBB
4939 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4940 // Lower header first, if it wasn't already lowered
4941 if (!JTCases[i].first.Emitted) {
4942 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4944 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
4945 // Set the current basic block to the mbb we wish to insert the code into
4946 BB = JTCases[i].first.HeaderBB;
4947 HSDL.setCurrentBasicBlock(BB);
4949 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4950 HSDAG.setRoot(HSDL.getRoot());
4951 CodeGenAndEmitDAG(HSDAG);
4954 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4956 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
4957 // Set the current basic block to the mbb we wish to insert the code into
4958 BB = JTCases[i].second.MBB;
4959 JSDL.setCurrentBasicBlock(BB);
4961 JSDL.visitJumpTable(JTCases[i].second);
4962 JSDAG.setRoot(JSDL.getRoot());
4963 CodeGenAndEmitDAG(JSDAG);
4966 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4967 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4968 MachineBasicBlock *PHIBB = PHI->getParent();
4969 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4970 "This is not a machine PHI node that we are updating!");
4971 // "default" BB. We can go there only from header BB.
4972 if (PHIBB == JTCases[i].second.Default) {
4973 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4975 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
4977 // JT BB. Just iterate over successors here
4978 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4979 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4981 PHI->addOperand(MachineOperand::CreateMBB(BB));
4986 // If the switch block involved a branch to one of the actual successors, we
4987 // need to update PHI nodes in that block.
4988 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4989 MachineInstr *PHI = PHINodesToUpdate[i].first;
4990 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4991 "This is not a machine PHI node that we are updating!");
4992 if (BB->isSuccessor(PHI->getParent())) {
4993 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4995 PHI->addOperand(MachineOperand::CreateMBB(BB));
4999 // If we generated any switch lowering information, build and codegen any
5000 // additional DAGs necessary.
5001 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
5002 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5004 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
5006 // Set the current basic block to the mbb we wish to insert the code into
5007 BB = SwitchCases[i].ThisBB;
5008 SDL.setCurrentBasicBlock(BB);
5011 SDL.visitSwitchCase(SwitchCases[i]);
5012 SDAG.setRoot(SDL.getRoot());
5013 CodeGenAndEmitDAG(SDAG);
5015 // Handle any PHI nodes in successors of this chunk, as if we were coming
5016 // from the original BB before switch expansion. Note that PHI nodes can
5017 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5018 // handle them the right number of times.
5019 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
5020 for (MachineBasicBlock::iterator Phi = BB->begin();
5021 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5022 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5023 for (unsigned pn = 0; ; ++pn) {
5024 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5025 if (PHINodesToUpdate[pn].first == Phi) {
5026 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5028 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5034 // Don't process RHS if same block as LHS.
5035 if (BB == SwitchCases[i].FalseBB)
5036 SwitchCases[i].FalseBB = 0;
5038 // If we haven't handled the RHS, do so now. Otherwise, we're done.
5039 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5040 SwitchCases[i].FalseBB = 0;
5042 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5047 //===----------------------------------------------------------------------===//
5048 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5049 /// target node in the graph.
5050 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5051 if (ViewSchedDAGs) DAG.viewGraph();
5053 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5057 RegisterScheduler::setDefault(Ctor);
5060 ScheduleDAG *SL = Ctor(this, &DAG, BB);
5063 if (ViewSUnitDAGs) SL->viewGraph();
5069 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5070 return new HazardRecognizer();
5073 //===----------------------------------------------------------------------===//
5074 // Helper functions used by the generated instruction selector.
5075 //===----------------------------------------------------------------------===//
5076 // Calls to these methods are generated by tblgen.
5078 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
5079 /// the dag combiner simplified the 255, we still want to match. RHS is the
5080 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5081 /// specified in the .td file (e.g. 255).
5082 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5083 int64_t DesiredMaskS) const {
5084 const APInt &ActualMask = RHS->getAPIntValue();
5085 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5087 // If the actual mask exactly matches, success!
5088 if (ActualMask == DesiredMask)
5091 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5092 if (ActualMask.intersects(~DesiredMask))
5095 // Otherwise, the DAG Combiner may have proven that the value coming in is
5096 // either already zero or is not demanded. Check for known zero input bits.
5097 APInt NeededMask = DesiredMask & ~ActualMask;
5098 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5101 // TODO: check to see if missing bits are just not demanded.
5103 // Otherwise, this pattern doesn't match.
5107 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
5108 /// the dag combiner simplified the 255, we still want to match. RHS is the
5109 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5110 /// specified in the .td file (e.g. 255).
5111 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5112 int64_t DesiredMaskS) const {
5113 const APInt &ActualMask = RHS->getAPIntValue();
5114 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5116 // If the actual mask exactly matches, success!
5117 if (ActualMask == DesiredMask)
5120 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5121 if (ActualMask.intersects(~DesiredMask))
5124 // Otherwise, the DAG Combiner may have proven that the value coming in is
5125 // either already zero or is not demanded. Check for known zero input bits.
5126 APInt NeededMask = DesiredMask & ~ActualMask;
5128 APInt KnownZero, KnownOne;
5129 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5131 // If all the missing bits in the or are already known to be set, match!
5132 if ((NeededMask & KnownOne) == NeededMask)
5135 // TODO: check to see if missing bits are just not demanded.
5137 // Otherwise, this pattern doesn't match.
5142 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5143 /// by tblgen. Others should not call it.
5144 void SelectionDAGISel::
5145 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5146 std::vector<SDOperand> InOps;
5147 std::swap(InOps, Ops);
5149 Ops.push_back(InOps[0]); // input chain.
5150 Ops.push_back(InOps[1]); // input asm string.
5152 unsigned i = 2, e = InOps.size();
5153 if (InOps[e-1].getValueType() == MVT::Flag)
5154 --e; // Don't process a flag operand if it is here.
5157 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5158 if ((Flags & 7) != 4 /*MEM*/) {
5159 // Just skip over this operand, copying the operands verbatim.
5160 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5161 i += (Flags >> 3) + 1;
5163 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5164 // Otherwise, this is a memory operand. Ask the target to select it.
5165 std::vector<SDOperand> SelOps;
5166 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5167 cerr << "Could not match memory address. Inline asm failure!\n";
5171 // Add this to the output node.
5172 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5173 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5175 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5180 // Add the flag input back if present.
5181 if (e != InOps.size())
5182 Ops.push_back(InOps.back());
5185 char SelectionDAGISel::ID = 0;