1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/ParameterAttributes.h"
29 #include "llvm/CodeGen/Collector.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SchedulerRegistry.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetFrameInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Compiler.h"
53 ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
56 ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
59 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
60 cl::desc("Pop up a window to show SUnit dags after they are processed"));
62 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
65 //===---------------------------------------------------------------------===//
67 /// RegisterScheduler class - Track the registration of instruction schedulers.
69 //===---------------------------------------------------------------------===//
70 MachinePassRegistry RegisterScheduler::Registry;
72 //===---------------------------------------------------------------------===//
74 /// ISHeuristic command line option for instruction schedulers.
76 //===---------------------------------------------------------------------===//
78 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
80 ISHeuristic("pre-RA-sched",
81 cl::init(&createDefaultScheduler),
82 cl::desc("Instruction schedulers available (before register"
85 static RegisterScheduler
86 defaultListDAGScheduler("default", " Best scheduler for the target",
87 createDefaultScheduler);
90 namespace { struct SDISelAsmOperandInfo; }
93 /// RegsForValue - This struct represents the physical registers that a
94 /// particular value is assigned and the type information about the value.
95 /// This is needed because values can be promoted into larger registers and
96 /// expanded into multiple smaller registers than the value.
97 struct VISIBILITY_HIDDEN RegsForValue {
98 /// Regs - This list holds the register (for legal and promoted values)
99 /// or register set (for expanded values) that the value should be assigned
101 std::vector<unsigned> Regs;
103 /// RegVT - The value type of each register.
105 MVT::ValueType RegVT;
107 /// ValueVT - The value type of the LLVM value, which may be promoted from
108 /// RegVT or made from merging the two expanded parts.
109 MVT::ValueType ValueVT;
111 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
113 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
114 : RegVT(regvt), ValueVT(valuevt) {
117 RegsForValue(const std::vector<unsigned> ®s,
118 MVT::ValueType regvt, MVT::ValueType valuevt)
119 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
122 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
123 /// this value and returns the result as a ValueVT value. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 /// If the Flag pointer is NULL, no flag is used.
126 SDOperand getCopyFromRegs(SelectionDAG &DAG,
127 SDOperand &Chain, SDOperand *Flag) const;
129 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
130 /// specified value into the registers specified by this object. This uses
131 /// Chain/Flag as the input and updates them for the output Chain/Flag.
132 /// If the Flag pointer is NULL, no flag is used.
133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
134 SDOperand &Chain, SDOperand *Flag) const;
136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
137 /// operand list. This adds the code marker and includes the number of
138 /// values added into it.
139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
140 std::vector<SDOperand> &Ops) const;
145 //===--------------------------------------------------------------------===//
146 /// createDefaultScheduler - This creates an instruction scheduler appropriate
148 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
150 MachineBasicBlock *BB) {
151 TargetLowering &TLI = IS->getTargetLowering();
153 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
154 return createTDListDAGScheduler(IS, DAG, BB);
156 assert(TLI.getSchedulingPreference() ==
157 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
158 return createBURRListDAGScheduler(IS, DAG, BB);
163 //===--------------------------------------------------------------------===//
164 /// FunctionLoweringInfo - This contains information that is global to a
165 /// function that is used when lowering a region of the function.
166 class FunctionLoweringInfo {
171 MachineRegisterInfo &RegInfo;
172 bool needsExceptionHandling;
174 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
176 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
177 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
179 /// ValueMap - Since we emit code for the function a basic block at a time,
180 /// we must remember which virtual registers hold the values for
181 /// cross-basic-block values.
182 DenseMap<const Value*, unsigned> ValueMap;
184 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
185 /// the entry block. This allows the allocas to be efficiently referenced
186 /// anywhere in the function.
187 std::map<const AllocaInst*, int> StaticAllocaMap;
190 SmallSet<Instruction*, 8> CatchInfoLost;
191 SmallSet<Instruction*, 8> CatchInfoFound;
194 unsigned MakeReg(MVT::ValueType VT) {
195 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
198 /// isExportedInst - Return true if the specified value is an instruction
199 /// exported from its block.
200 bool isExportedInst(const Value *V) {
201 return ValueMap.count(V);
204 unsigned CreateRegForValue(const Value *V);
206 unsigned InitializeRegForValue(const Value *V) {
207 unsigned &R = ValueMap[V];
208 assert(R == 0 && "Already initialized this value register!");
209 return R = CreateRegForValue(V);
214 /// isSelector - Return true if this instruction is a call to the
215 /// eh.selector intrinsic.
216 static bool isSelector(Instruction *I) {
217 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
218 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
219 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
223 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
224 /// PHI nodes or outside of the basic block that defines it, or used by a
225 /// switch or atomic instruction, which may expand to multiple basic blocks.
226 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
227 if (isa<PHINode>(I)) return true;
228 BasicBlock *BB = I->getParent();
229 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
230 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
231 // FIXME: Remove switchinst special case.
232 isa<SwitchInst>(*UI))
237 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
238 /// entry block, return true. This includes arguments used by switches, since
239 /// the switch may expand into multiple basic blocks.
240 static bool isOnlyUsedInEntryBlock(Argument *A) {
241 BasicBlock *Entry = A->getParent()->begin();
242 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
243 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
244 return false; // Use not in entry block.
248 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
249 Function &fn, MachineFunction &mf)
250 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
252 // Create a vreg for each argument register that is not dead and is used
253 // outside of the entry block for the function.
254 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
256 if (!isOnlyUsedInEntryBlock(AI))
257 InitializeRegForValue(AI);
259 // Initialize the mapping of values to registers. This is only set up for
260 // instruction values that are used outside of the block that defines
262 Function::iterator BB = Fn.begin(), EB = Fn.end();
263 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
264 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
265 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
266 const Type *Ty = AI->getAllocatedType();
267 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
269 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
272 TySize *= CUI->getZExtValue(); // Get total allocated size.
273 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
274 StaticAllocaMap[AI] =
275 MF.getFrameInfo()->CreateStackObject(TySize, Align);
278 for (; BB != EB; ++BB)
279 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
280 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
281 if (!isa<AllocaInst>(I) ||
282 !StaticAllocaMap.count(cast<AllocaInst>(I)))
283 InitializeRegForValue(I);
285 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
286 // also creates the initial PHI MachineInstrs, though none of the input
287 // operands are populated.
288 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
289 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
291 MF.getBasicBlockList().push_back(MBB);
293 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
296 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
297 if (PN->use_empty()) continue;
299 MVT::ValueType VT = TLI.getValueType(PN->getType());
300 unsigned NumRegisters = TLI.getNumRegisters(VT);
301 unsigned PHIReg = ValueMap[PN];
302 assert(PHIReg && "PHI node does not have an assigned virtual register!");
303 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
304 for (unsigned i = 0; i != NumRegisters; ++i)
305 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
309 // Figure out whether we need to generate EH info. Currently we do this for
310 // all functions not marked no-unwind, or if requested via -enable-eh.
311 needsExceptionHandling = ExceptionHandling || !Fn.doesNotThrow();
314 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
315 /// the correctly promoted or expanded types. Assign these registers
316 /// consecutive vreg numbers and return the first assigned number.
317 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
318 MVT::ValueType VT = TLI.getValueType(V->getType());
320 unsigned NumRegisters = TLI.getNumRegisters(VT);
321 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
323 unsigned R = MakeReg(RegisterVT);
324 for (unsigned i = 1; i != NumRegisters; ++i)
330 //===----------------------------------------------------------------------===//
331 /// SelectionDAGLowering - This is the common target-independent lowering
332 /// implementation that is parameterized by a TargetLowering object.
333 /// Also, targets can overload any lowering method.
336 class SelectionDAGLowering {
337 MachineBasicBlock *CurMBB;
339 DenseMap<const Value*, SDOperand> NodeMap;
341 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
342 /// them up and then emit token factor nodes when possible. This allows us to
343 /// get simple disambiguation between loads without worrying about alias
345 std::vector<SDOperand> PendingLoads;
347 /// PendingExports - CopyToReg nodes that copy values to virtual registers
348 /// for export to other blocks need to be emitted before any terminator
349 /// instruction, but they have no other ordering requirements. We bunch them
350 /// up and the emit a single tokenfactor for them just before terminator
352 std::vector<SDOperand> PendingExports;
354 /// Case - A struct to record the Value for a switch case, and the
355 /// case's target basic block.
359 MachineBasicBlock* BB;
361 Case() : Low(0), High(0), BB(0) { }
362 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
363 Low(low), High(high), BB(bb) { }
364 uint64_t size() const {
365 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
366 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
367 return (rHigh - rLow + 1ULL);
373 MachineBasicBlock* BB;
376 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
377 Mask(mask), BB(bb), Bits(bits) { }
380 typedef std::vector<Case> CaseVector;
381 typedef std::vector<CaseBits> CaseBitsVector;
382 typedef CaseVector::iterator CaseItr;
383 typedef std::pair<CaseItr, CaseItr> CaseRange;
385 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
386 /// of conditional branches.
388 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
389 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
391 /// CaseBB - The MBB in which to emit the compare and branch
392 MachineBasicBlock *CaseBB;
393 /// LT, GE - If nonzero, we know the current case value must be less-than or
394 /// greater-than-or-equal-to these Constants.
397 /// Range - A pair of iterators representing the range of case values to be
398 /// processed at this point in the binary search tree.
402 typedef std::vector<CaseRec> CaseRecVector;
404 /// The comparison function for sorting the switch case values in the vector.
405 /// WARNING: Case ranges should be disjoint!
407 bool operator () (const Case& C1, const Case& C2) {
408 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
409 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
410 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
411 return CI1->getValue().slt(CI2->getValue());
416 bool operator () (const CaseBits& C1, const CaseBits& C2) {
417 return C1.Bits > C2.Bits;
421 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
424 // TLI - This is information that describes the available target features we
425 // need for lowering. This indicates when operations are unavailable,
426 // implemented with a libcall, etc.
429 const TargetData *TD;
432 /// SwitchCases - Vector of CaseBlock structures used to communicate
433 /// SwitchInst code generation information.
434 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
435 /// JTCases - Vector of JumpTable structures used to communicate
436 /// SwitchInst code generation information.
437 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
438 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
440 /// FuncInfo - Information about the function as a whole.
442 FunctionLoweringInfo &FuncInfo;
444 /// GCI - Garbage collection metadata for the function.
445 CollectorMetadata *GCI;
447 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
449 FunctionLoweringInfo &funcinfo,
450 CollectorMetadata *gci)
451 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
452 FuncInfo(funcinfo), GCI(gci) {
455 /// getRoot - Return the current virtual root of the Selection DAG,
456 /// flushing any PendingLoad items. This must be done before emitting
457 /// a store or any other node that may need to be ordered after any
458 /// prior load instructions.
460 SDOperand getRoot() {
461 if (PendingLoads.empty())
462 return DAG.getRoot();
464 if (PendingLoads.size() == 1) {
465 SDOperand Root = PendingLoads[0];
467 PendingLoads.clear();
471 // Otherwise, we have to make a token factor node.
472 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
473 &PendingLoads[0], PendingLoads.size());
474 PendingLoads.clear();
479 /// getControlRoot - Similar to getRoot, but instead of flushing all the
480 /// PendingLoad items, flush all the PendingExports items. It is necessary
481 /// to do this before emitting a terminator instruction.
483 SDOperand getControlRoot() {
484 SDOperand Root = DAG.getRoot();
486 if (PendingExports.empty())
489 // Turn all of the CopyToReg chains into one factored node.
490 if (Root.getOpcode() != ISD::EntryToken) {
491 unsigned i = 0, e = PendingExports.size();
492 for (; i != e; ++i) {
493 assert(PendingExports[i].Val->getNumOperands() > 1);
494 if (PendingExports[i].Val->getOperand(0) == Root)
495 break; // Don't add the root if we already indirectly depend on it.
499 PendingExports.push_back(Root);
502 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
504 PendingExports.size());
505 PendingExports.clear();
510 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
512 void visit(Instruction &I) { visit(I.getOpcode(), I); }
514 void visit(unsigned Opcode, User &I) {
515 // Note: this doesn't use InstVisitor, because it has to work with
516 // ConstantExpr's in addition to instructions.
518 default: assert(0 && "Unknown instruction type encountered!");
520 // Build the switch statement using the Instruction.def file.
521 #define HANDLE_INST(NUM, OPCODE, CLASS) \
522 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
523 #include "llvm/Instruction.def"
527 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
529 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
530 const Value *SV, SDOperand Root,
531 bool isVolatile, unsigned Alignment);
533 SDOperand getValue(const Value *V);
535 void setValue(const Value *V, SDOperand NewN) {
536 SDOperand &N = NodeMap[V];
537 assert(N.Val == 0 && "Already set a value for this node!");
541 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
542 std::set<unsigned> &OutputRegs,
543 std::set<unsigned> &InputRegs);
545 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
546 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
548 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
549 void ExportFromCurrentBlock(Value *V);
550 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
551 MachineBasicBlock *LandingPad = NULL);
553 // Terminator instructions.
554 void visitRet(ReturnInst &I);
555 void visitBr(BranchInst &I);
556 void visitSwitch(SwitchInst &I);
557 void visitUnreachable(UnreachableInst &I) { /* noop */ }
559 // Helpers for visitSwitch
560 bool handleSmallSwitchRange(CaseRec& CR,
561 CaseRecVector& WorkList,
563 MachineBasicBlock* Default);
564 bool handleJTSwitchCase(CaseRec& CR,
565 CaseRecVector& WorkList,
567 MachineBasicBlock* Default);
568 bool handleBTSplitSwitchCase(CaseRec& CR,
569 CaseRecVector& WorkList,
571 MachineBasicBlock* Default);
572 bool handleBitTestsSwitchCase(CaseRec& CR,
573 CaseRecVector& WorkList,
575 MachineBasicBlock* Default);
576 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
577 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
578 void visitBitTestCase(MachineBasicBlock* NextMBB,
580 SelectionDAGISel::BitTestCase &B);
581 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
582 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
583 SelectionDAGISel::JumpTableHeader &JTH);
585 // These all get lowered before this pass.
586 void visitInvoke(InvokeInst &I);
587 void visitUnwind(UnwindInst &I);
589 void visitBinary(User &I, unsigned OpCode);
590 void visitShift(User &I, unsigned Opcode);
591 void visitAdd(User &I) {
592 if (I.getType()->isFPOrFPVector())
593 visitBinary(I, ISD::FADD);
595 visitBinary(I, ISD::ADD);
597 void visitSub(User &I);
598 void visitMul(User &I) {
599 if (I.getType()->isFPOrFPVector())
600 visitBinary(I, ISD::FMUL);
602 visitBinary(I, ISD::MUL);
604 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
605 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
606 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
607 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
608 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
609 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
610 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
611 void visitOr (User &I) { visitBinary(I, ISD::OR); }
612 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
613 void visitShl (User &I) { visitShift(I, ISD::SHL); }
614 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
615 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
616 void visitICmp(User &I);
617 void visitFCmp(User &I);
618 // Visit the conversion instructions
619 void visitTrunc(User &I);
620 void visitZExt(User &I);
621 void visitSExt(User &I);
622 void visitFPTrunc(User &I);
623 void visitFPExt(User &I);
624 void visitFPToUI(User &I);
625 void visitFPToSI(User &I);
626 void visitUIToFP(User &I);
627 void visitSIToFP(User &I);
628 void visitPtrToInt(User &I);
629 void visitIntToPtr(User &I);
630 void visitBitCast(User &I);
632 void visitExtractElement(User &I);
633 void visitInsertElement(User &I);
634 void visitShuffleVector(User &I);
636 void visitGetElementPtr(User &I);
637 void visitSelect(User &I);
639 void visitMalloc(MallocInst &I);
640 void visitFree(FreeInst &I);
641 void visitAlloca(AllocaInst &I);
642 void visitLoad(LoadInst &I);
643 void visitStore(StoreInst &I);
644 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
645 void visitCall(CallInst &I);
646 void visitInlineAsm(CallSite CS);
647 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
648 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
650 void visitVAStart(CallInst &I);
651 void visitVAArg(VAArgInst &I);
652 void visitVAEnd(CallInst &I);
653 void visitVACopy(CallInst &I);
655 void visitMemIntrinsic(CallInst &I, unsigned Op);
657 void visitGetResult(GetResultInst &I);
659 void visitUserOp1(Instruction &I) {
660 assert(0 && "UserOp1 should not exist at instruction selection time!");
663 void visitUserOp2(Instruction &I) {
664 assert(0 && "UserOp2 should not exist at instruction selection time!");
668 } // end namespace llvm
671 /// getCopyFromParts - Create a value that contains the specified legal parts
672 /// combined into the value they represent. If the parts combine to a type
673 /// larger then ValueVT then AssertOp can be used to specify whether the extra
674 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
675 /// (ISD::AssertSext).
676 static SDOperand getCopyFromParts(SelectionDAG &DAG,
677 const SDOperand *Parts,
679 MVT::ValueType PartVT,
680 MVT::ValueType ValueVT,
681 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
682 assert(NumParts > 0 && "No parts to assemble!");
683 TargetLowering &TLI = DAG.getTargetLoweringInfo();
684 SDOperand Val = Parts[0];
687 // Assemble the value from multiple parts.
688 if (!MVT::isVector(ValueVT)) {
689 unsigned PartBits = MVT::getSizeInBits(PartVT);
690 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
692 // Assemble the power of 2 part.
693 unsigned RoundParts = NumParts & (NumParts - 1) ?
694 1 << Log2_32(NumParts) : NumParts;
695 unsigned RoundBits = PartBits * RoundParts;
696 MVT::ValueType RoundVT = RoundBits == ValueBits ?
697 ValueVT : MVT::getIntegerType(RoundBits);
700 if (RoundParts > 2) {
701 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
702 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
703 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
709 if (TLI.isBigEndian())
711 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
713 if (RoundParts < NumParts) {
714 // Assemble the trailing non-power-of-2 part.
715 unsigned OddParts = NumParts - RoundParts;
716 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
717 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
719 // Combine the round and odd parts.
721 if (TLI.isBigEndian())
723 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
724 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
725 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
726 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
727 TLI.getShiftAmountTy()));
728 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
729 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
732 // Handle a multi-element vector.
733 MVT::ValueType IntermediateVT, RegisterVT;
734 unsigned NumIntermediates;
736 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
739 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
740 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
741 assert(RegisterVT == Parts[0].getValueType() &&
742 "Part type doesn't match part!");
744 // Assemble the parts into intermediate operands.
745 SmallVector<SDOperand, 8> Ops(NumIntermediates);
746 if (NumIntermediates == NumParts) {
747 // If the register was not expanded, truncate or copy the value,
749 for (unsigned i = 0; i != NumParts; ++i)
750 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
751 PartVT, IntermediateVT);
752 } else if (NumParts > 0) {
753 // If the intermediate type was expanded, build the intermediate operands
755 assert(NumParts % NumIntermediates == 0 &&
756 "Must expand into a divisible number of parts!");
757 unsigned Factor = NumParts / NumIntermediates;
758 for (unsigned i = 0; i != NumIntermediates; ++i)
759 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
760 PartVT, IntermediateVT);
763 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
765 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
766 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
767 ValueVT, &Ops[0], NumIntermediates);
771 // There is now one part, held in Val. Correct it to match ValueVT.
772 PartVT = Val.getValueType();
774 if (PartVT == ValueVT)
777 if (MVT::isVector(PartVT)) {
778 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
779 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
782 if (MVT::isVector(ValueVT)) {
783 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
784 MVT::getVectorNumElements(ValueVT) == 1 &&
785 "Only trivial scalar-to-vector conversions should get here!");
786 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
789 if (MVT::isInteger(PartVT) &&
790 MVT::isInteger(ValueVT)) {
791 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
792 // For a truncate, see if we have any information to
793 // indicate whether the truncated bits will always be
794 // zero or sign-extension.
795 if (AssertOp != ISD::DELETED_NODE)
796 Val = DAG.getNode(AssertOp, PartVT, Val,
797 DAG.getValueType(ValueVT));
798 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
800 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
804 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
805 if (ValueVT < Val.getValueType())
806 // FP_ROUND's are always exact here.
807 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
808 DAG.getIntPtrConstant(1));
809 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
812 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
813 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
815 assert(0 && "Unknown mismatch!");
819 /// getCopyToParts - Create a series of nodes that contain the specified value
820 /// split into legal parts. If the parts contain more bits than Val, then, for
821 /// integers, ExtendKind can be used to specify how to generate the extra bits.
822 static void getCopyToParts(SelectionDAG &DAG,
826 MVT::ValueType PartVT,
827 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
828 TargetLowering &TLI = DAG.getTargetLoweringInfo();
829 MVT::ValueType PtrVT = TLI.getPointerTy();
830 MVT::ValueType ValueVT = Val.getValueType();
831 unsigned PartBits = MVT::getSizeInBits(PartVT);
832 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
837 if (!MVT::isVector(ValueVT)) {
838 if (PartVT == ValueVT) {
839 assert(NumParts == 1 && "No-op copy with multiple parts!");
844 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
845 // If the parts cover more bits than the value has, promote the value.
846 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
847 assert(NumParts == 1 && "Do not know what to promote to!");
848 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
849 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
850 ValueVT = MVT::getIntegerType(NumParts * PartBits);
851 Val = DAG.getNode(ExtendKind, ValueVT, Val);
853 assert(0 && "Unknown mismatch!");
855 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
856 // Different types of the same size.
857 assert(NumParts == 1 && PartVT != ValueVT);
858 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
859 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
860 // If the parts cover less bits than value has, truncate the value.
861 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
862 ValueVT = MVT::getIntegerType(NumParts * PartBits);
863 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
865 assert(0 && "Unknown mismatch!");
869 // The value may have changed - recompute ValueVT.
870 ValueVT = Val.getValueType();
871 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
872 "Failed to tile the value with PartVT!");
875 assert(PartVT == ValueVT && "Type conversion failed!");
880 // Expand the value into multiple parts.
881 if (NumParts & (NumParts - 1)) {
882 // The number of parts is not a power of 2. Split off and copy the tail.
883 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
884 "Do not know what to expand to!");
885 unsigned RoundParts = 1 << Log2_32(NumParts);
886 unsigned RoundBits = RoundParts * PartBits;
887 unsigned OddParts = NumParts - RoundParts;
888 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
889 DAG.getConstant(RoundBits,
890 TLI.getShiftAmountTy()));
891 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
892 if (TLI.isBigEndian())
893 // The odd parts were reversed by getCopyToParts - unreverse them.
894 std::reverse(Parts + RoundParts, Parts + NumParts);
895 NumParts = RoundParts;
896 ValueVT = MVT::getIntegerType(NumParts * PartBits);
897 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
900 // The number of parts is a power of 2. Repeatedly bisect the value using
902 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
903 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
905 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
906 for (unsigned i = 0; i < NumParts; i += StepSize) {
907 unsigned ThisBits = StepSize * PartBits / 2;
908 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
909 SDOperand &Part0 = Parts[i];
910 SDOperand &Part1 = Parts[i+StepSize/2];
912 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
913 DAG.getConstant(1, PtrVT));
914 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
915 DAG.getConstant(0, PtrVT));
917 if (ThisBits == PartBits && ThisVT != PartVT) {
918 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
919 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
924 if (TLI.isBigEndian())
925 std::reverse(Parts, Parts + NumParts);
932 if (PartVT != ValueVT) {
933 if (MVT::isVector(PartVT)) {
934 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
936 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
937 MVT::getVectorNumElements(ValueVT) == 1 &&
938 "Only trivial vector-to-scalar conversions should get here!");
939 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
940 DAG.getConstant(0, PtrVT));
948 // Handle a multi-element vector.
949 MVT::ValueType IntermediateVT, RegisterVT;
950 unsigned NumIntermediates;
952 DAG.getTargetLoweringInfo()
953 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
955 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
957 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
958 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
960 // Split the vector into intermediate operands.
961 SmallVector<SDOperand, 8> Ops(NumIntermediates);
962 for (unsigned i = 0; i != NumIntermediates; ++i)
963 if (MVT::isVector(IntermediateVT))
964 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
966 DAG.getConstant(i * (NumElements / NumIntermediates),
969 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
971 DAG.getConstant(i, PtrVT));
973 // Split the intermediate operands into legal parts.
974 if (NumParts == NumIntermediates) {
975 // If the register was not expanded, promote or copy the value,
977 for (unsigned i = 0; i != NumParts; ++i)
978 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
979 } else if (NumParts > 0) {
980 // If the intermediate type was expanded, split each the value into
982 assert(NumParts % NumIntermediates == 0 &&
983 "Must expand into a divisible number of parts!");
984 unsigned Factor = NumParts / NumIntermediates;
985 for (unsigned i = 0; i != NumIntermediates; ++i)
986 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
991 SDOperand SelectionDAGLowering::getValue(const Value *V) {
992 SDOperand &N = NodeMap[V];
995 const Type *VTy = V->getType();
996 MVT::ValueType VT = TLI.getValueType(VTy);
997 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
998 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
999 visit(CE->getOpcode(), *CE);
1000 SDOperand N1 = NodeMap[V];
1001 assert(N1.Val && "visit didn't populate the ValueMap!");
1003 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
1004 return N = DAG.getGlobalAddress(GV, VT);
1005 } else if (isa<ConstantPointerNull>(C)) {
1006 return N = DAG.getConstant(0, TLI.getPointerTy());
1007 } else if (isa<UndefValue>(C)) {
1008 if (!isa<VectorType>(VTy))
1009 return N = DAG.getNode(ISD::UNDEF, VT);
1011 // Create a BUILD_VECTOR of undef nodes.
1012 const VectorType *PTy = cast<VectorType>(VTy);
1013 unsigned NumElements = PTy->getNumElements();
1014 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1016 SmallVector<SDOperand, 8> Ops;
1017 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
1019 // Create a VConstant node with generic Vector type.
1020 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
1021 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
1022 &Ops[0], Ops.size());
1023 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1024 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1025 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
1026 unsigned NumElements = PTy->getNumElements();
1027 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1029 // Now that we know the number and type of the elements, push a
1030 // Constant or ConstantFP node onto the ops list for each element of
1031 // the vector constant.
1032 SmallVector<SDOperand, 8> Ops;
1033 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1034 for (unsigned i = 0; i != NumElements; ++i)
1035 Ops.push_back(getValue(CP->getOperand(i)));
1037 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1039 if (MVT::isFloatingPoint(PVT))
1040 Op = DAG.getConstantFP(0, PVT);
1042 Op = DAG.getConstant(0, PVT);
1043 Ops.assign(NumElements, Op);
1046 // Create a BUILD_VECTOR node.
1047 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
1048 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
1051 // Canonicalize all constant ints to be unsigned.
1052 return N = DAG.getConstant(cast<ConstantInt>(C)->getValue(),VT);
1056 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1057 std::map<const AllocaInst*, int>::iterator SI =
1058 FuncInfo.StaticAllocaMap.find(AI);
1059 if (SI != FuncInfo.StaticAllocaMap.end())
1060 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1063 unsigned InReg = FuncInfo.ValueMap[V];
1064 assert(InReg && "Value not in map!");
1066 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
1067 unsigned NumRegs = TLI.getNumRegisters(VT);
1069 std::vector<unsigned> Regs(NumRegs);
1070 for (unsigned i = 0; i != NumRegs; ++i)
1071 Regs[i] = InReg + i;
1073 RegsForValue RFV(Regs, RegisterVT, VT);
1074 SDOperand Chain = DAG.getEntryNode();
1076 return RFV.getCopyFromRegs(DAG, Chain, NULL);
1080 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1081 if (I.getNumOperands() == 0) {
1082 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1085 SmallVector<SDOperand, 8> NewValues;
1086 NewValues.push_back(getControlRoot());
1087 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1088 SDOperand RetOp = getValue(I.getOperand(i));
1089 MVT::ValueType VT = RetOp.getValueType();
1091 // FIXME: C calling convention requires the return type to be promoted to
1092 // at least 32-bit. But this is not necessary for non-C calling conventions.
1093 if (MVT::isInteger(VT)) {
1094 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1095 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1099 unsigned NumParts = TLI.getNumRegisters(VT);
1100 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1101 SmallVector<SDOperand, 4> Parts(NumParts);
1102 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1104 const Function *F = I.getParent()->getParent();
1105 if (F->paramHasAttr(0, ParamAttr::SExt))
1106 ExtendKind = ISD::SIGN_EXTEND;
1107 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1108 ExtendKind = ISD::ZERO_EXTEND;
1110 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1112 for (unsigned i = 0; i < NumParts; ++i) {
1113 NewValues.push_back(Parts[i]);
1114 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1117 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1118 &NewValues[0], NewValues.size()));
1121 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1122 /// the current basic block, add it to ValueMap now so that we'll get a
1124 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1125 // No need to export constants.
1126 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1128 // Already exported?
1129 if (FuncInfo.isExportedInst(V)) return;
1131 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1132 CopyValueToVirtualRegister(V, Reg);
1135 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1136 const BasicBlock *FromBB) {
1137 // The operands of the setcc have to be in this block. We don't know
1138 // how to export them from some other block.
1139 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1140 // Can export from current BB.
1141 if (VI->getParent() == FromBB)
1144 // Is already exported, noop.
1145 return FuncInfo.isExportedInst(V);
1148 // If this is an argument, we can export it if the BB is the entry block or
1149 // if it is already exported.
1150 if (isa<Argument>(V)) {
1151 if (FromBB == &FromBB->getParent()->getEntryBlock())
1154 // Otherwise, can only export this if it is already exported.
1155 return FuncInfo.isExportedInst(V);
1158 // Otherwise, constants can always be exported.
1162 static bool InBlock(const Value *V, const BasicBlock *BB) {
1163 if (const Instruction *I = dyn_cast<Instruction>(V))
1164 return I->getParent() == BB;
1168 /// FindMergedConditions - If Cond is an expression like
1169 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1170 MachineBasicBlock *TBB,
1171 MachineBasicBlock *FBB,
1172 MachineBasicBlock *CurBB,
1174 // If this node is not part of the or/and tree, emit it as a branch.
1175 Instruction *BOp = dyn_cast<Instruction>(Cond);
1177 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1178 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1179 BOp->getParent() != CurBB->getBasicBlock() ||
1180 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1181 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1182 const BasicBlock *BB = CurBB->getBasicBlock();
1184 // If the leaf of the tree is a comparison, merge the condition into
1186 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1187 // The operands of the cmp have to be in this block. We don't know
1188 // how to export them from some other block. If this is the first block
1189 // of the sequence, no exporting is needed.
1191 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1192 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1193 BOp = cast<Instruction>(Cond);
1194 ISD::CondCode Condition;
1195 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1196 switch (IC->getPredicate()) {
1197 default: assert(0 && "Unknown icmp predicate opcode!");
1198 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1199 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1200 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1201 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1202 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1203 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1204 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1205 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1206 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1207 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1209 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1210 ISD::CondCode FPC, FOC;
1211 switch (FC->getPredicate()) {
1212 default: assert(0 && "Unknown fcmp predicate opcode!");
1213 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1214 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1215 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1216 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1217 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1218 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1219 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1220 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1221 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1222 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1223 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1224 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1225 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1226 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1227 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1228 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1230 if (FiniteOnlyFPMath())
1235 Condition = ISD::SETEQ; // silence warning.
1236 assert(0 && "Unknown compare instruction");
1239 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1240 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1241 SwitchCases.push_back(CB);
1245 // Create a CaseBlock record representing this branch.
1246 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1247 NULL, TBB, FBB, CurBB);
1248 SwitchCases.push_back(CB);
1253 // Create TmpBB after CurBB.
1254 MachineFunction::iterator BBI = CurBB;
1255 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1256 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1258 if (Opc == Instruction::Or) {
1259 // Codegen X | Y as:
1267 // Emit the LHS condition.
1268 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1270 // Emit the RHS condition into TmpBB.
1271 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1273 assert(Opc == Instruction::And && "Unknown merge op!");
1274 // Codegen X & Y as:
1281 // This requires creation of TmpBB after CurBB.
1283 // Emit the LHS condition.
1284 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1286 // Emit the RHS condition into TmpBB.
1287 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1291 /// If the set of cases should be emitted as a series of branches, return true.
1292 /// If we should emit this as a bunch of and/or'd together conditions, return
1295 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1296 if (Cases.size() != 2) return true;
1298 // If this is two comparisons of the same values or'd or and'd together, they
1299 // will get folded into a single comparison, so don't emit two blocks.
1300 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1301 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1302 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1303 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1310 void SelectionDAGLowering::visitBr(BranchInst &I) {
1311 // Update machine-CFG edges.
1312 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1314 // Figure out which block is immediately after the current one.
1315 MachineBasicBlock *NextBlock = 0;
1316 MachineFunction::iterator BBI = CurMBB;
1317 if (++BBI != CurMBB->getParent()->end())
1320 if (I.isUnconditional()) {
1321 // If this is not a fall-through branch, emit the branch.
1322 if (Succ0MBB != NextBlock)
1323 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1324 DAG.getBasicBlock(Succ0MBB)));
1326 // Update machine-CFG edges.
1327 CurMBB->addSuccessor(Succ0MBB);
1331 // If this condition is one of the special cases we handle, do special stuff
1333 Value *CondVal = I.getCondition();
1334 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1336 // If this is a series of conditions that are or'd or and'd together, emit
1337 // this as a sequence of branches instead of setcc's with and/or operations.
1338 // For example, instead of something like:
1351 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1352 if (BOp->hasOneUse() &&
1353 (BOp->getOpcode() == Instruction::And ||
1354 BOp->getOpcode() == Instruction::Or)) {
1355 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1356 // If the compares in later blocks need to use values not currently
1357 // exported from this block, export them now. This block should always
1358 // be the first entry.
1359 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1361 // Allow some cases to be rejected.
1362 if (ShouldEmitAsBranches(SwitchCases)) {
1363 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1364 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1365 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1368 // Emit the branch for this block.
1369 visitSwitchCase(SwitchCases[0]);
1370 SwitchCases.erase(SwitchCases.begin());
1374 // Okay, we decided not to do this, remove any inserted MBB's and clear
1376 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1377 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1379 SwitchCases.clear();
1383 // Create a CaseBlock record representing this branch.
1384 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1385 NULL, Succ0MBB, Succ1MBB, CurMBB);
1386 // Use visitSwitchCase to actually insert the fast branch sequence for this
1388 visitSwitchCase(CB);
1391 /// visitSwitchCase - Emits the necessary code to represent a single node in
1392 /// the binary search tree resulting from lowering a switch instruction.
1393 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1395 SDOperand CondLHS = getValue(CB.CmpLHS);
1397 // Build the setcc now.
1398 if (CB.CmpMHS == NULL) {
1399 // Fold "(X == true)" to X and "(X == false)" to !X to
1400 // handle common cases produced by branch lowering.
1401 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1403 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1404 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1405 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1407 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1409 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1411 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1412 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1414 SDOperand CmpOp = getValue(CB.CmpMHS);
1415 MVT::ValueType VT = CmpOp.getValueType();
1417 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1418 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1420 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1421 Cond = DAG.getSetCC(MVT::i1, SUB,
1422 DAG.getConstant(High-Low, VT), ISD::SETULE);
1427 // Set NextBlock to be the MBB immediately after the current one, if any.
1428 // This is used to avoid emitting unnecessary branches to the next block.
1429 MachineBasicBlock *NextBlock = 0;
1430 MachineFunction::iterator BBI = CurMBB;
1431 if (++BBI != CurMBB->getParent()->end())
1434 // If the lhs block is the next block, invert the condition so that we can
1435 // fall through to the lhs instead of the rhs block.
1436 if (CB.TrueBB == NextBlock) {
1437 std::swap(CB.TrueBB, CB.FalseBB);
1438 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1439 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1441 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1442 DAG.getBasicBlock(CB.TrueBB));
1443 if (CB.FalseBB == NextBlock)
1444 DAG.setRoot(BrCond);
1446 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1447 DAG.getBasicBlock(CB.FalseBB)));
1448 // Update successor info
1449 CurMBB->addSuccessor(CB.TrueBB);
1450 CurMBB->addSuccessor(CB.FalseBB);
1453 /// visitJumpTable - Emit JumpTable node in the current MBB
1454 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1455 // Emit the code for the jump table
1456 assert(JT.Reg != -1U && "Should lower JT Header first!");
1457 MVT::ValueType PTy = TLI.getPointerTy();
1458 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1459 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1460 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1465 /// visitJumpTableHeader - This function emits necessary code to produce index
1466 /// in the JumpTable from switch case.
1467 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1468 SelectionDAGISel::JumpTableHeader &JTH) {
1469 // Subtract the lowest switch case value from the value being switched on
1470 // and conditional branch to default mbb if the result is greater than the
1471 // difference between smallest and largest cases.
1472 SDOperand SwitchOp = getValue(JTH.SValue);
1473 MVT::ValueType VT = SwitchOp.getValueType();
1474 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1475 DAG.getConstant(JTH.First, VT));
1477 // The SDNode we just created, which holds the value being switched on
1478 // minus the the smallest case value, needs to be copied to a virtual
1479 // register so it can be used as an index into the jump table in a
1480 // subsequent basic block. This value may be smaller or larger than the
1481 // target's pointer type, and therefore require extension or truncating.
1482 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
1483 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1485 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1487 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1488 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1489 JT.Reg = JumpTableReg;
1491 // Emit the range check for the jump table, and branch to the default
1492 // block for the switch statement if the value being switched on exceeds
1493 // the largest case in the switch.
1494 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1495 DAG.getConstant(JTH.Last-JTH.First,VT),
1498 // Set NextBlock to be the MBB immediately after the current one, if any.
1499 // This is used to avoid emitting unnecessary branches to the next block.
1500 MachineBasicBlock *NextBlock = 0;
1501 MachineFunction::iterator BBI = CurMBB;
1502 if (++BBI != CurMBB->getParent()->end())
1505 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1506 DAG.getBasicBlock(JT.Default));
1508 if (JT.MBB == NextBlock)
1509 DAG.setRoot(BrCond);
1511 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1512 DAG.getBasicBlock(JT.MBB)));
1517 /// visitBitTestHeader - This function emits necessary code to produce value
1518 /// suitable for "bit tests"
1519 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1520 // Subtract the minimum value
1521 SDOperand SwitchOp = getValue(B.SValue);
1522 MVT::ValueType VT = SwitchOp.getValueType();
1523 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1524 DAG.getConstant(B.First, VT));
1527 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1528 DAG.getConstant(B.Range, VT),
1532 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
1533 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1535 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1537 // Make desired shift
1538 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1539 DAG.getConstant(1, TLI.getPointerTy()),
1542 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1543 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1546 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1547 DAG.getBasicBlock(B.Default));
1549 // Set NextBlock to be the MBB immediately after the current one, if any.
1550 // This is used to avoid emitting unnecessary branches to the next block.
1551 MachineBasicBlock *NextBlock = 0;
1552 MachineFunction::iterator BBI = CurMBB;
1553 if (++BBI != CurMBB->getParent()->end())
1556 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1557 if (MBB == NextBlock)
1558 DAG.setRoot(BrRange);
1560 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1561 DAG.getBasicBlock(MBB)));
1563 CurMBB->addSuccessor(B.Default);
1564 CurMBB->addSuccessor(MBB);
1569 /// visitBitTestCase - this function produces one "bit test"
1570 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1572 SelectionDAGISel::BitTestCase &B) {
1573 // Emit bit tests and jumps
1574 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
1576 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1578 DAG.getConstant(B.Mask,
1579 TLI.getPointerTy()));
1580 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1581 DAG.getConstant(0, TLI.getPointerTy()),
1583 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1584 AndCmp, DAG.getBasicBlock(B.TargetBB));
1586 // Set NextBlock to be the MBB immediately after the current one, if any.
1587 // This is used to avoid emitting unnecessary branches to the next block.
1588 MachineBasicBlock *NextBlock = 0;
1589 MachineFunction::iterator BBI = CurMBB;
1590 if (++BBI != CurMBB->getParent()->end())
1593 if (NextMBB == NextBlock)
1596 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1597 DAG.getBasicBlock(NextMBB)));
1599 CurMBB->addSuccessor(B.TargetBB);
1600 CurMBB->addSuccessor(NextMBB);
1605 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1606 // Retrieve successors.
1607 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1608 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1610 if (isa<InlineAsm>(I.getCalledValue()))
1613 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1615 // If the value of the invoke is used outside of its defining block, make it
1616 // available as a virtual register.
1617 if (!I.use_empty()) {
1618 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1619 if (VMI != FuncInfo.ValueMap.end())
1620 CopyValueToVirtualRegister(&I, VMI->second);
1623 // Drop into normal successor.
1624 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1625 DAG.getBasicBlock(Return)));
1627 // Update successor info
1628 CurMBB->addSuccessor(Return);
1629 CurMBB->addSuccessor(LandingPad);
1632 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1635 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1636 /// small case ranges).
1637 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1638 CaseRecVector& WorkList,
1640 MachineBasicBlock* Default) {
1641 Case& BackCase = *(CR.Range.second-1);
1643 // Size is the number of Cases represented by this range.
1644 unsigned Size = CR.Range.second - CR.Range.first;
1648 // Get the MachineFunction which holds the current MBB. This is used when
1649 // inserting any additional MBBs necessary to represent the switch.
1650 MachineFunction *CurMF = CurMBB->getParent();
1652 // Figure out which block is immediately after the current one.
1653 MachineBasicBlock *NextBlock = 0;
1654 MachineFunction::iterator BBI = CR.CaseBB;
1656 if (++BBI != CurMBB->getParent()->end())
1659 // TODO: If any two of the cases has the same destination, and if one value
1660 // is the same as the other, but has one bit unset that the other has set,
1661 // use bit manipulation to do two compares at once. For example:
1662 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1664 // Rearrange the case blocks so that the last one falls through if possible.
1665 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1666 // The last case block won't fall through into 'NextBlock' if we emit the
1667 // branches in this order. See if rearranging a case value would help.
1668 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1669 if (I->BB == NextBlock) {
1670 std::swap(*I, BackCase);
1676 // Create a CaseBlock record representing a conditional branch to
1677 // the Case's target mbb if the value being switched on SV is equal
1679 MachineBasicBlock *CurBlock = CR.CaseBB;
1680 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1681 MachineBasicBlock *FallThrough;
1683 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1684 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1686 // If the last case doesn't match, go to the default block.
1687 FallThrough = Default;
1690 Value *RHS, *LHS, *MHS;
1692 if (I->High == I->Low) {
1693 // This is just small small case range :) containing exactly 1 case
1695 LHS = SV; RHS = I->High; MHS = NULL;
1698 LHS = I->Low; MHS = SV; RHS = I->High;
1700 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1701 I->BB, FallThrough, CurBlock);
1703 // If emitting the first comparison, just call visitSwitchCase to emit the
1704 // code into the current block. Otherwise, push the CaseBlock onto the
1705 // vector to be later processed by SDISel, and insert the node's MBB
1706 // before the next MBB.
1707 if (CurBlock == CurMBB)
1708 visitSwitchCase(CB);
1710 SwitchCases.push_back(CB);
1712 CurBlock = FallThrough;
1718 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1719 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1720 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1723 /// handleJTSwitchCase - Emit jumptable for current switch case range
1724 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1725 CaseRecVector& WorkList,
1727 MachineBasicBlock* Default) {
1728 Case& FrontCase = *CR.Range.first;
1729 Case& BackCase = *(CR.Range.second-1);
1731 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1732 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1735 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1739 if (!areJTsAllowed(TLI) || TSize <= 3)
1742 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1746 DOUT << "Lowering jump table\n"
1747 << "First entry: " << First << ". Last entry: " << Last << "\n"
1748 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1750 // Get the MachineFunction which holds the current MBB. This is used when
1751 // inserting any additional MBBs necessary to represent the switch.
1752 MachineFunction *CurMF = CurMBB->getParent();
1754 // Figure out which block is immediately after the current one.
1755 MachineBasicBlock *NextBlock = 0;
1756 MachineFunction::iterator BBI = CR.CaseBB;
1758 if (++BBI != CurMBB->getParent()->end())
1761 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1763 // Create a new basic block to hold the code for loading the address
1764 // of the jump table, and jumping to it. Update successor information;
1765 // we will either branch to the default case for the switch, or the jump
1767 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1768 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1769 CR.CaseBB->addSuccessor(Default);
1770 CR.CaseBB->addSuccessor(JumpTableBB);
1772 // Build a vector of destination BBs, corresponding to each target
1773 // of the jump table. If the value of the jump table slot corresponds to
1774 // a case statement, push the case's BB onto the vector, otherwise, push
1776 std::vector<MachineBasicBlock*> DestBBs;
1777 int64_t TEI = First;
1778 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1779 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1780 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1782 if ((Low <= TEI) && (TEI <= High)) {
1783 DestBBs.push_back(I->BB);
1787 DestBBs.push_back(Default);
1791 // Update successor info. Add one edge to each unique successor.
1792 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1793 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1794 E = DestBBs.end(); I != E; ++I) {
1795 if (!SuccsHandled[(*I)->getNumber()]) {
1796 SuccsHandled[(*I)->getNumber()] = true;
1797 JumpTableBB->addSuccessor(*I);
1801 // Create a jump table index for this jump table, or return an existing
1803 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1805 // Set the jump table information so that we can codegen it as a second
1806 // MachineBasicBlock
1807 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1808 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1809 (CR.CaseBB == CurMBB));
1810 if (CR.CaseBB == CurMBB)
1811 visitJumpTableHeader(JT, JTH);
1813 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1818 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1820 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1821 CaseRecVector& WorkList,
1823 MachineBasicBlock* Default) {
1824 // Get the MachineFunction which holds the current MBB. This is used when
1825 // inserting any additional MBBs necessary to represent the switch.
1826 MachineFunction *CurMF = CurMBB->getParent();
1828 // Figure out which block is immediately after the current one.
1829 MachineBasicBlock *NextBlock = 0;
1830 MachineFunction::iterator BBI = CR.CaseBB;
1832 if (++BBI != CurMBB->getParent()->end())
1835 Case& FrontCase = *CR.Range.first;
1836 Case& BackCase = *(CR.Range.second-1);
1837 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1839 // Size is the number of Cases represented by this range.
1840 unsigned Size = CR.Range.second - CR.Range.first;
1842 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1843 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1845 CaseItr Pivot = CR.Range.first + Size/2;
1847 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1848 // (heuristically) allow us to emit JumpTable's later.
1850 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1854 uint64_t LSize = FrontCase.size();
1855 uint64_t RSize = TSize-LSize;
1856 DOUT << "Selecting best pivot: \n"
1857 << "First: " << First << ", Last: " << Last <<"\n"
1858 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1859 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1861 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1862 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1863 assert((RBegin-LEnd>=1) && "Invalid case distance");
1864 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1865 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1866 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1867 // Should always split in some non-trivial place
1869 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1870 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1871 << "Metric: " << Metric << "\n";
1872 if (FMetric < Metric) {
1875 DOUT << "Current metric set to: " << FMetric << "\n";
1881 if (areJTsAllowed(TLI)) {
1882 // If our case is dense we *really* should handle it earlier!
1883 assert((FMetric > 0) && "Should handle dense range earlier!");
1885 Pivot = CR.Range.first + Size/2;
1888 CaseRange LHSR(CR.Range.first, Pivot);
1889 CaseRange RHSR(Pivot, CR.Range.second);
1890 Constant *C = Pivot->Low;
1891 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1893 // We know that we branch to the LHS if the Value being switched on is
1894 // less than the Pivot value, C. We use this to optimize our binary
1895 // tree a bit, by recognizing that if SV is greater than or equal to the
1896 // LHS's Case Value, and that Case Value is exactly one less than the
1897 // Pivot's Value, then we can branch directly to the LHS's Target,
1898 // rather than creating a leaf node for it.
1899 if ((LHSR.second - LHSR.first) == 1 &&
1900 LHSR.first->High == CR.GE &&
1901 cast<ConstantInt>(C)->getSExtValue() ==
1902 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1903 TrueBB = LHSR.first->BB;
1905 TrueBB = new MachineBasicBlock(LLVMBB);
1906 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1907 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1910 // Similar to the optimization above, if the Value being switched on is
1911 // known to be less than the Constant CR.LT, and the current Case Value
1912 // is CR.LT - 1, then we can branch directly to the target block for
1913 // the current Case Value, rather than emitting a RHS leaf node for it.
1914 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1915 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1916 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1917 FalseBB = RHSR.first->BB;
1919 FalseBB = new MachineBasicBlock(LLVMBB);
1920 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1921 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1924 // Create a CaseBlock record representing a conditional branch to
1925 // the LHS node if the value being switched on SV is less than C.
1926 // Otherwise, branch to LHS.
1927 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1928 TrueBB, FalseBB, CR.CaseBB);
1930 if (CR.CaseBB == CurMBB)
1931 visitSwitchCase(CB);
1933 SwitchCases.push_back(CB);
1938 /// handleBitTestsSwitchCase - if current case range has few destination and
1939 /// range span less, than machine word bitwidth, encode case range into series
1940 /// of masks and emit bit tests with these masks.
1941 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1942 CaseRecVector& WorkList,
1944 MachineBasicBlock* Default){
1945 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
1947 Case& FrontCase = *CR.Range.first;
1948 Case& BackCase = *(CR.Range.second-1);
1950 // Get the MachineFunction which holds the current MBB. This is used when
1951 // inserting any additional MBBs necessary to represent the switch.
1952 MachineFunction *CurMF = CurMBB->getParent();
1954 unsigned numCmps = 0;
1955 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1957 // Single case counts one, case range - two.
1958 if (I->Low == I->High)
1964 // Count unique destinations
1965 SmallSet<MachineBasicBlock*, 4> Dests;
1966 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1967 Dests.insert(I->BB);
1968 if (Dests.size() > 3)
1969 // Don't bother the code below, if there are too much unique destinations
1972 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1973 << "Total number of comparisons: " << numCmps << "\n";
1975 // Compute span of values.
1976 Constant* minValue = FrontCase.Low;
1977 Constant* maxValue = BackCase.High;
1978 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1979 cast<ConstantInt>(minValue)->getSExtValue();
1980 DOUT << "Compare range: " << range << "\n"
1981 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1982 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1984 if (range>=IntPtrBits ||
1985 (!(Dests.size() == 1 && numCmps >= 3) &&
1986 !(Dests.size() == 2 && numCmps >= 5) &&
1987 !(Dests.size() >= 3 && numCmps >= 6)))
1990 DOUT << "Emitting bit tests\n";
1991 int64_t lowBound = 0;
1993 // Optimize the case where all the case values fit in a
1994 // word without having to subtract minValue. In this case,
1995 // we can optimize away the subtraction.
1996 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1997 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1998 range = cast<ConstantInt>(maxValue)->getSExtValue();
2000 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2003 CaseBitsVector CasesBits;
2004 unsigned i, count = 0;
2006 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2007 MachineBasicBlock* Dest = I->BB;
2008 for (i = 0; i < count; ++i)
2009 if (Dest == CasesBits[i].BB)
2013 assert((count < 3) && "Too much destinations to test!");
2014 CasesBits.push_back(CaseBits(0, Dest, 0));
2018 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2019 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2021 for (uint64_t j = lo; j <= hi; j++) {
2022 CasesBits[i].Mask |= 1ULL << j;
2023 CasesBits[i].Bits++;
2027 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2029 SelectionDAGISel::BitTestInfo BTC;
2031 // Figure out which block is immediately after the current one.
2032 MachineFunction::iterator BBI = CR.CaseBB;
2035 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2038 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2039 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2040 << ", BB: " << CasesBits[i].BB << "\n";
2042 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2043 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2044 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2049 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2050 -1U, (CR.CaseBB == CurMBB),
2051 CR.CaseBB, Default, BTC);
2053 if (CR.CaseBB == CurMBB)
2054 visitBitTestHeader(BTB);
2056 BitTestCases.push_back(BTB);
2062 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2063 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2064 const SwitchInst& SI) {
2065 unsigned numCmps = 0;
2067 // Start with "simple" cases
2068 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2069 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2070 Cases.push_back(Case(SI.getSuccessorValue(i),
2071 SI.getSuccessorValue(i),
2074 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2076 // Merge case into clusters
2077 if (Cases.size()>=2)
2078 // Must recompute end() each iteration because it may be
2079 // invalidated by erase if we hold on to it
2080 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2081 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2082 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2083 MachineBasicBlock* nextBB = J->BB;
2084 MachineBasicBlock* currentBB = I->BB;
2086 // If the two neighboring cases go to the same destination, merge them
2087 // into a single case.
2088 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2096 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2097 if (I->Low != I->High)
2098 // A range counts double, since it requires two compares.
2105 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2106 // Figure out which block is immediately after the current one.
2107 MachineBasicBlock *NextBlock = 0;
2108 MachineFunction::iterator BBI = CurMBB;
2110 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2112 // If there is only the default destination, branch to it if it is not the
2113 // next basic block. Otherwise, just fall through.
2114 if (SI.getNumOperands() == 2) {
2115 // Update machine-CFG edges.
2117 // If this is not a fall-through branch, emit the branch.
2118 if (Default != NextBlock)
2119 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2120 DAG.getBasicBlock(Default)));
2122 CurMBB->addSuccessor(Default);
2126 // If there are any non-default case statements, create a vector of Cases
2127 // representing each one, and sort the vector so that we can efficiently
2128 // create a binary search tree from them.
2130 unsigned numCmps = Clusterify(Cases, SI);
2131 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2132 << ". Total compares: " << numCmps << "\n";
2134 // Get the Value to be switched on and default basic blocks, which will be
2135 // inserted into CaseBlock records, representing basic blocks in the binary
2137 Value *SV = SI.getOperand(0);
2139 // Push the initial CaseRec onto the worklist
2140 CaseRecVector WorkList;
2141 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2143 while (!WorkList.empty()) {
2144 // Grab a record representing a case range to process off the worklist
2145 CaseRec CR = WorkList.back();
2146 WorkList.pop_back();
2148 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2151 // If the range has few cases (two or less) emit a series of specific
2153 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2156 // If the switch has more than 5 blocks, and at least 40% dense, and the
2157 // target supports indirect branches, then emit a jump table rather than
2158 // lowering the switch to a binary tree of conditional branches.
2159 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2162 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2163 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2164 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2169 void SelectionDAGLowering::visitSub(User &I) {
2170 // -0.0 - X --> fneg
2171 const Type *Ty = I.getType();
2172 if (isa<VectorType>(Ty)) {
2173 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2174 const VectorType *DestTy = cast<VectorType>(I.getType());
2175 const Type *ElTy = DestTy->getElementType();
2176 if (ElTy->isFloatingPoint()) {
2177 unsigned VL = DestTy->getNumElements();
2178 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2179 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2181 SDOperand Op2 = getValue(I.getOperand(1));
2182 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2188 if (Ty->isFloatingPoint()) {
2189 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2190 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2191 SDOperand Op2 = getValue(I.getOperand(1));
2192 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2197 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2200 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2201 SDOperand Op1 = getValue(I.getOperand(0));
2202 SDOperand Op2 = getValue(I.getOperand(1));
2204 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2207 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2208 SDOperand Op1 = getValue(I.getOperand(0));
2209 SDOperand Op2 = getValue(I.getOperand(1));
2211 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2212 MVT::getSizeInBits(Op2.getValueType()))
2213 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2214 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2215 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2217 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2220 void SelectionDAGLowering::visitICmp(User &I) {
2221 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2222 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2223 predicate = IC->getPredicate();
2224 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2225 predicate = ICmpInst::Predicate(IC->getPredicate());
2226 SDOperand Op1 = getValue(I.getOperand(0));
2227 SDOperand Op2 = getValue(I.getOperand(1));
2228 ISD::CondCode Opcode;
2229 switch (predicate) {
2230 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2231 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2232 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2233 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2234 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2235 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2236 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2237 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2238 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2239 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2241 assert(!"Invalid ICmp predicate value");
2242 Opcode = ISD::SETEQ;
2245 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2248 void SelectionDAGLowering::visitFCmp(User &I) {
2249 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2250 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2251 predicate = FC->getPredicate();
2252 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2253 predicate = FCmpInst::Predicate(FC->getPredicate());
2254 SDOperand Op1 = getValue(I.getOperand(0));
2255 SDOperand Op2 = getValue(I.getOperand(1));
2256 ISD::CondCode Condition, FOC, FPC;
2257 switch (predicate) {
2258 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2259 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2260 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2261 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2262 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2263 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2264 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2265 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2266 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2267 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2268 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2269 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2270 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2271 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2272 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2273 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2275 assert(!"Invalid FCmp predicate value");
2276 FOC = FPC = ISD::SETFALSE;
2279 if (FiniteOnlyFPMath())
2283 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2286 void SelectionDAGLowering::visitSelect(User &I) {
2287 SDOperand Cond = getValue(I.getOperand(0));
2288 SDOperand TrueVal = getValue(I.getOperand(1));
2289 SDOperand FalseVal = getValue(I.getOperand(2));
2290 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2291 TrueVal, FalseVal));
2295 void SelectionDAGLowering::visitTrunc(User &I) {
2296 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2297 SDOperand N = getValue(I.getOperand(0));
2298 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2299 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2302 void SelectionDAGLowering::visitZExt(User &I) {
2303 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2304 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2305 SDOperand N = getValue(I.getOperand(0));
2306 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2307 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2310 void SelectionDAGLowering::visitSExt(User &I) {
2311 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2312 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2313 SDOperand N = getValue(I.getOperand(0));
2314 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2315 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2318 void SelectionDAGLowering::visitFPTrunc(User &I) {
2319 // FPTrunc is never a no-op cast, no need to check
2320 SDOperand N = getValue(I.getOperand(0));
2321 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2322 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2325 void SelectionDAGLowering::visitFPExt(User &I){
2326 // FPTrunc is never a no-op cast, no need to check
2327 SDOperand N = getValue(I.getOperand(0));
2328 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2329 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2332 void SelectionDAGLowering::visitFPToUI(User &I) {
2333 // FPToUI is never a no-op cast, no need to check
2334 SDOperand N = getValue(I.getOperand(0));
2335 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2336 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2339 void SelectionDAGLowering::visitFPToSI(User &I) {
2340 // FPToSI is never a no-op cast, no need to check
2341 SDOperand N = getValue(I.getOperand(0));
2342 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2343 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2346 void SelectionDAGLowering::visitUIToFP(User &I) {
2347 // UIToFP is never a no-op cast, no need to check
2348 SDOperand N = getValue(I.getOperand(0));
2349 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2350 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2353 void SelectionDAGLowering::visitSIToFP(User &I){
2354 // UIToFP is never a no-op cast, no need to check
2355 SDOperand N = getValue(I.getOperand(0));
2356 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2357 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2360 void SelectionDAGLowering::visitPtrToInt(User &I) {
2361 // What to do depends on the size of the integer and the size of the pointer.
2362 // We can either truncate, zero extend, or no-op, accordingly.
2363 SDOperand N = getValue(I.getOperand(0));
2364 MVT::ValueType SrcVT = N.getValueType();
2365 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2367 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2368 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2370 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2371 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2372 setValue(&I, Result);
2375 void SelectionDAGLowering::visitIntToPtr(User &I) {
2376 // What to do depends on the size of the integer and the size of the pointer.
2377 // We can either truncate, zero extend, or no-op, accordingly.
2378 SDOperand N = getValue(I.getOperand(0));
2379 MVT::ValueType SrcVT = N.getValueType();
2380 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2381 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2382 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2384 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2385 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2388 void SelectionDAGLowering::visitBitCast(User &I) {
2389 SDOperand N = getValue(I.getOperand(0));
2390 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2392 // BitCast assures us that source and destination are the same size so this
2393 // is either a BIT_CONVERT or a no-op.
2394 if (DestVT != N.getValueType())
2395 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2397 setValue(&I, N); // noop cast.
2400 void SelectionDAGLowering::visitInsertElement(User &I) {
2401 SDOperand InVec = getValue(I.getOperand(0));
2402 SDOperand InVal = getValue(I.getOperand(1));
2403 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2404 getValue(I.getOperand(2)));
2406 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2407 TLI.getValueType(I.getType()),
2408 InVec, InVal, InIdx));
2411 void SelectionDAGLowering::visitExtractElement(User &I) {
2412 SDOperand InVec = getValue(I.getOperand(0));
2413 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2414 getValue(I.getOperand(1)));
2415 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2416 TLI.getValueType(I.getType()), InVec, InIdx));
2419 void SelectionDAGLowering::visitShuffleVector(User &I) {
2420 SDOperand V1 = getValue(I.getOperand(0));
2421 SDOperand V2 = getValue(I.getOperand(1));
2422 SDOperand Mask = getValue(I.getOperand(2));
2424 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2425 TLI.getValueType(I.getType()),
2430 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2431 SDOperand N = getValue(I.getOperand(0));
2432 const Type *Ty = I.getOperand(0)->getType();
2434 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2437 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2438 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2441 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2442 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2443 DAG.getIntPtrConstant(Offset));
2445 Ty = StTy->getElementType(Field);
2447 Ty = cast<SequentialType>(Ty)->getElementType();
2449 // If this is a constant subscript, handle it quickly.
2450 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2451 if (CI->getZExtValue() == 0) continue;
2453 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2454 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2455 DAG.getIntPtrConstant(Offs));
2459 // N = N + Idx * ElementSize;
2460 uint64_t ElementSize = TD->getABITypeSize(Ty);
2461 SDOperand IdxN = getValue(Idx);
2463 // If the index is smaller or larger than intptr_t, truncate or extend
2465 if (IdxN.getValueType() < N.getValueType()) {
2466 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2467 } else if (IdxN.getValueType() > N.getValueType())
2468 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2470 // If this is a multiply by a power of two, turn it into a shl
2471 // immediately. This is a very common case.
2472 if (isPowerOf2_64(ElementSize)) {
2473 unsigned Amt = Log2_64(ElementSize);
2474 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2475 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2476 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2480 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2481 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2482 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2488 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2489 // If this is a fixed sized alloca in the entry block of the function,
2490 // allocate it statically on the stack.
2491 if (FuncInfo.StaticAllocaMap.count(&I))
2492 return; // getValue will auto-populate this.
2494 const Type *Ty = I.getAllocatedType();
2495 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2497 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2500 SDOperand AllocSize = getValue(I.getArraySize());
2501 MVT::ValueType IntPtr = TLI.getPointerTy();
2502 if (IntPtr < AllocSize.getValueType())
2503 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2504 else if (IntPtr > AllocSize.getValueType())
2505 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2507 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2508 DAG.getIntPtrConstant(TySize));
2510 // Handle alignment. If the requested alignment is less than or equal to
2511 // the stack alignment, ignore it. If the size is greater than or equal to
2512 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2513 unsigned StackAlign =
2514 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2515 if (Align <= StackAlign)
2518 // Round the size of the allocation up to the stack alignment size
2519 // by add SA-1 to the size.
2520 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2521 DAG.getIntPtrConstant(StackAlign-1));
2522 // Mask out the low bits for alignment purposes.
2523 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2524 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2526 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2527 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2529 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2531 DAG.setRoot(DSA.getValue(1));
2533 // Inform the Frame Information that we have just allocated a variable-sized
2535 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2538 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2539 SDOperand Ptr = getValue(I.getOperand(0));
2545 // Do not serialize non-volatile loads against each other.
2546 Root = DAG.getRoot();
2549 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2550 Root, I.isVolatile(), I.getAlignment()));
2553 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2554 const Value *SV, SDOperand Root,
2556 unsigned Alignment) {
2558 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2559 isVolatile, Alignment);
2562 DAG.setRoot(L.getValue(1));
2564 PendingLoads.push_back(L.getValue(1));
2570 void SelectionDAGLowering::visitStore(StoreInst &I) {
2571 Value *SrcV = I.getOperand(0);
2572 SDOperand Src = getValue(SrcV);
2573 SDOperand Ptr = getValue(I.getOperand(1));
2574 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2575 I.isVolatile(), I.getAlignment()));
2578 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2580 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2581 unsigned Intrinsic) {
2582 bool HasChain = !I.doesNotAccessMemory();
2583 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2585 // Build the operand list.
2586 SmallVector<SDOperand, 8> Ops;
2587 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2589 // We don't need to serialize loads against other loads.
2590 Ops.push_back(DAG.getRoot());
2592 Ops.push_back(getRoot());
2596 // Add the intrinsic ID as an integer operand.
2597 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2599 // Add all operands of the call to the operand list.
2600 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2601 SDOperand Op = getValue(I.getOperand(i));
2602 assert(TLI.isTypeLegal(Op.getValueType()) &&
2603 "Intrinsic uses a non-legal type?");
2607 std::vector<MVT::ValueType> VTs;
2608 if (I.getType() != Type::VoidTy) {
2609 MVT::ValueType VT = TLI.getValueType(I.getType());
2610 if (MVT::isVector(VT)) {
2611 const VectorType *DestTy = cast<VectorType>(I.getType());
2612 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2614 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2615 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2618 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2622 VTs.push_back(MVT::Other);
2624 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2629 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2630 &Ops[0], Ops.size());
2631 else if (I.getType() != Type::VoidTy)
2632 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2633 &Ops[0], Ops.size());
2635 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2636 &Ops[0], Ops.size());
2639 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2641 PendingLoads.push_back(Chain);
2645 if (I.getType() != Type::VoidTy) {
2646 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2647 MVT::ValueType VT = TLI.getValueType(PTy);
2648 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2650 setValue(&I, Result);
2654 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2655 static GlobalVariable *ExtractTypeInfo (Value *V) {
2656 V = IntrinsicInst::StripPointerCasts(V);
2657 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2658 assert ((GV || isa<ConstantPointerNull>(V)) &&
2659 "TypeInfo must be a global variable or NULL");
2663 /// addCatchInfo - Extract the personality and type infos from an eh.selector
2664 /// call, and add them to the specified machine basic block.
2665 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2666 MachineBasicBlock *MBB) {
2667 // Inform the MachineModuleInfo of the personality for this landing pad.
2668 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2669 assert(CE->getOpcode() == Instruction::BitCast &&
2670 isa<Function>(CE->getOperand(0)) &&
2671 "Personality should be a function");
2672 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2674 // Gather all the type infos for this landing pad and pass them along to
2675 // MachineModuleInfo.
2676 std::vector<GlobalVariable *> TyInfo;
2677 unsigned N = I.getNumOperands();
2679 for (unsigned i = N - 1; i > 2; --i) {
2680 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2681 unsigned FilterLength = CI->getZExtValue();
2682 unsigned FirstCatch = i + FilterLength + !FilterLength;
2683 assert (FirstCatch <= N && "Invalid filter length");
2685 if (FirstCatch < N) {
2686 TyInfo.reserve(N - FirstCatch);
2687 for (unsigned j = FirstCatch; j < N; ++j)
2688 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2689 MMI->addCatchTypeInfo(MBB, TyInfo);
2693 if (!FilterLength) {
2695 MMI->addCleanup(MBB);
2698 TyInfo.reserve(FilterLength - 1);
2699 for (unsigned j = i + 1; j < FirstCatch; ++j)
2700 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2701 MMI->addFilterTypeInfo(MBB, TyInfo);
2710 TyInfo.reserve(N - 3);
2711 for (unsigned j = 3; j < N; ++j)
2712 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2713 MMI->addCatchTypeInfo(MBB, TyInfo);
2717 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2718 /// we want to emit this as a call to a named external function, return the name
2719 /// otherwise lower it and return null.
2721 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2722 switch (Intrinsic) {
2724 // By default, turn this into a target intrinsic node.
2725 visitTargetIntrinsic(I, Intrinsic);
2727 case Intrinsic::vastart: visitVAStart(I); return 0;
2728 case Intrinsic::vaend: visitVAEnd(I); return 0;
2729 case Intrinsic::vacopy: visitVACopy(I); return 0;
2730 case Intrinsic::returnaddress:
2731 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2732 getValue(I.getOperand(1))));
2734 case Intrinsic::frameaddress:
2735 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2736 getValue(I.getOperand(1))));
2738 case Intrinsic::setjmp:
2739 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2741 case Intrinsic::longjmp:
2742 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2744 case Intrinsic::memcpy_i32:
2745 case Intrinsic::memcpy_i64:
2746 visitMemIntrinsic(I, ISD::MEMCPY);
2748 case Intrinsic::memset_i32:
2749 case Intrinsic::memset_i64:
2750 visitMemIntrinsic(I, ISD::MEMSET);
2752 case Intrinsic::memmove_i32:
2753 case Intrinsic::memmove_i64:
2754 visitMemIntrinsic(I, ISD::MEMMOVE);
2757 case Intrinsic::dbg_stoppoint: {
2758 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2759 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2760 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2764 Ops[1] = getValue(SPI.getLineValue());
2765 Ops[2] = getValue(SPI.getColumnValue());
2767 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2768 assert(DD && "Not a debug information descriptor");
2769 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2771 Ops[3] = DAG.getString(CompileUnit->getFileName());
2772 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2774 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2779 case Intrinsic::dbg_region_start: {
2780 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2781 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2782 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2783 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2784 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2785 DAG.getConstant(LabelID, MVT::i32),
2786 DAG.getConstant(0, MVT::i32)));
2791 case Intrinsic::dbg_region_end: {
2792 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2793 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2794 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2795 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2796 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2797 DAG.getConstant(LabelID, MVT::i32),
2798 DAG.getConstant(0, MVT::i32)));
2803 case Intrinsic::dbg_func_start: {
2804 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2806 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2807 Value *SP = FSI.getSubprogram();
2808 if (SP && MMI->Verify(SP)) {
2809 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2810 // what (most?) gdb expects.
2811 DebugInfoDesc *DD = MMI->getDescFor(SP);
2812 assert(DD && "Not a debug information descriptor");
2813 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2814 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2815 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2816 CompileUnit->getFileName());
2817 // Record the source line but does create a label. It will be emitted
2818 // at asm emission time.
2819 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
2824 case Intrinsic::dbg_declare: {
2825 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2826 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2827 Value *Variable = DI.getVariable();
2828 if (MMI && Variable && MMI->Verify(Variable))
2829 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2830 getValue(DI.getAddress()), getValue(Variable)));
2834 case Intrinsic::eh_exception: {
2835 if (FuncInfo.needsExceptionHandling) {
2836 if (!CurMBB->isLandingPad()) {
2837 // FIXME: Mark exception register as live in. Hack for PR1508.
2838 unsigned Reg = TLI.getExceptionAddressRegister();
2839 if (Reg) CurMBB->addLiveIn(Reg);
2841 // Insert the EXCEPTIONADDR instruction.
2842 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2844 Ops[0] = DAG.getRoot();
2845 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2847 DAG.setRoot(Op.getValue(1));
2849 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2854 case Intrinsic::eh_selector_i32:
2855 case Intrinsic::eh_selector_i64: {
2856 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2857 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2858 MVT::i32 : MVT::i64);
2860 if (FuncInfo.needsExceptionHandling && MMI) {
2861 if (CurMBB->isLandingPad())
2862 addCatchInfo(I, MMI, CurMBB);
2865 FuncInfo.CatchInfoLost.insert(&I);
2867 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2868 unsigned Reg = TLI.getExceptionSelectorRegister();
2869 if (Reg) CurMBB->addLiveIn(Reg);
2872 // Insert the EHSELECTION instruction.
2873 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2875 Ops[0] = getValue(I.getOperand(1));
2877 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2879 DAG.setRoot(Op.getValue(1));
2881 setValue(&I, DAG.getConstant(0, VT));
2887 case Intrinsic::eh_typeid_for_i32:
2888 case Intrinsic::eh_typeid_for_i64: {
2889 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2890 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2891 MVT::i32 : MVT::i64);
2894 // Find the type id for the given typeinfo.
2895 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
2897 unsigned TypeID = MMI->getTypeIDFor(GV);
2898 setValue(&I, DAG.getConstant(TypeID, VT));
2900 // Return something different to eh_selector.
2901 setValue(&I, DAG.getConstant(1, VT));
2907 case Intrinsic::eh_return: {
2908 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2910 if (MMI && FuncInfo.needsExceptionHandling) {
2911 MMI->setCallsEHReturn(true);
2912 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2915 getValue(I.getOperand(1)),
2916 getValue(I.getOperand(2))));
2918 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2924 case Intrinsic::eh_unwind_init: {
2925 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2926 MMI->setCallsUnwindInit(true);
2932 case Intrinsic::eh_dwarf_cfa: {
2933 if (FuncInfo.needsExceptionHandling) {
2934 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
2936 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
2937 CfaArg = DAG.getNode(ISD::TRUNCATE,
2938 TLI.getPointerTy(), getValue(I.getOperand(1)));
2940 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
2941 TLI.getPointerTy(), getValue(I.getOperand(1)));
2943 SDOperand Offset = DAG.getNode(ISD::ADD,
2945 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
2946 TLI.getPointerTy()),
2948 setValue(&I, DAG.getNode(ISD::ADD,
2950 DAG.getNode(ISD::FRAMEADDR,
2953 TLI.getPointerTy())),
2956 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2962 case Intrinsic::sqrt:
2963 setValue(&I, DAG.getNode(ISD::FSQRT,
2964 getValue(I.getOperand(1)).getValueType(),
2965 getValue(I.getOperand(1))));
2967 case Intrinsic::powi:
2968 setValue(&I, DAG.getNode(ISD::FPOWI,
2969 getValue(I.getOperand(1)).getValueType(),
2970 getValue(I.getOperand(1)),
2971 getValue(I.getOperand(2))));
2973 case Intrinsic::sin:
2974 setValue(&I, DAG.getNode(ISD::FSIN,
2975 getValue(I.getOperand(1)).getValueType(),
2976 getValue(I.getOperand(1))));
2978 case Intrinsic::cos:
2979 setValue(&I, DAG.getNode(ISD::FCOS,
2980 getValue(I.getOperand(1)).getValueType(),
2981 getValue(I.getOperand(1))));
2983 case Intrinsic::pow:
2984 setValue(&I, DAG.getNode(ISD::FPOW,
2985 getValue(I.getOperand(1)).getValueType(),
2986 getValue(I.getOperand(1)),
2987 getValue(I.getOperand(2))));
2989 case Intrinsic::pcmarker: {
2990 SDOperand Tmp = getValue(I.getOperand(1));
2991 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2994 case Intrinsic::readcyclecounter: {
2995 SDOperand Op = getRoot();
2996 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2997 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3000 DAG.setRoot(Tmp.getValue(1));
3003 case Intrinsic::part_select: {
3004 // Currently not implemented: just abort
3005 assert(0 && "part_select intrinsic not implemented");
3008 case Intrinsic::part_set: {
3009 // Currently not implemented: just abort
3010 assert(0 && "part_set intrinsic not implemented");
3013 case Intrinsic::bswap:
3014 setValue(&I, DAG.getNode(ISD::BSWAP,
3015 getValue(I.getOperand(1)).getValueType(),
3016 getValue(I.getOperand(1))));
3018 case Intrinsic::cttz: {
3019 SDOperand Arg = getValue(I.getOperand(1));
3020 MVT::ValueType Ty = Arg.getValueType();
3021 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3022 setValue(&I, result);
3025 case Intrinsic::ctlz: {
3026 SDOperand Arg = getValue(I.getOperand(1));
3027 MVT::ValueType Ty = Arg.getValueType();
3028 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3029 setValue(&I, result);
3032 case Intrinsic::ctpop: {
3033 SDOperand Arg = getValue(I.getOperand(1));
3034 MVT::ValueType Ty = Arg.getValueType();
3035 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3036 setValue(&I, result);
3039 case Intrinsic::stacksave: {
3040 SDOperand Op = getRoot();
3041 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3042 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3044 DAG.setRoot(Tmp.getValue(1));
3047 case Intrinsic::stackrestore: {
3048 SDOperand Tmp = getValue(I.getOperand(1));
3049 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3052 case Intrinsic::var_annotation:
3053 // Discard annotate attributes
3056 case Intrinsic::init_trampoline: {
3058 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3062 Ops[1] = getValue(I.getOperand(1));
3063 Ops[2] = getValue(I.getOperand(2));
3064 Ops[3] = getValue(I.getOperand(3));
3065 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3066 Ops[5] = DAG.getSrcValue(F);
3068 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3069 DAG.getNodeValueTypes(TLI.getPointerTy(),
3074 DAG.setRoot(Tmp.getValue(1));
3078 case Intrinsic::gcroot:
3080 Value *Alloca = I.getOperand(1);
3081 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3083 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3084 GCI->addStackRoot(FI->getIndex(), TypeMap);
3088 case Intrinsic::gcread:
3089 case Intrinsic::gcwrite:
3090 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3093 case Intrinsic::flt_rounds: {
3094 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3098 case Intrinsic::trap: {
3099 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3102 case Intrinsic::prefetch: {
3105 Ops[1] = getValue(I.getOperand(1));
3106 Ops[2] = getValue(I.getOperand(2));
3107 Ops[3] = getValue(I.getOperand(3));
3108 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3112 case Intrinsic::memory_barrier: {
3115 for (int x = 1; x < 6; ++x)
3116 Ops[x] = getValue(I.getOperand(x));
3118 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3121 case Intrinsic::atomic_lcs: {
3122 SDOperand Root = getRoot();
3123 SDOperand O3 = getValue(I.getOperand(3));
3124 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3125 getValue(I.getOperand(1)),
3126 getValue(I.getOperand(2)),
3127 O3, O3.getValueType());
3129 DAG.setRoot(L.getValue(1));
3132 case Intrinsic::atomic_las: {
3133 SDOperand Root = getRoot();
3134 SDOperand O2 = getValue(I.getOperand(2));
3135 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root,
3136 getValue(I.getOperand(1)),
3137 O2, O2.getValueType());
3139 DAG.setRoot(L.getValue(1));
3142 case Intrinsic::atomic_swap: {
3143 SDOperand Root = getRoot();
3144 SDOperand O2 = getValue(I.getOperand(2));
3145 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root,
3146 getValue(I.getOperand(1)),
3147 O2, O2.getValueType());
3149 DAG.setRoot(L.getValue(1));
3157 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3159 MachineBasicBlock *LandingPad) {
3160 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3161 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3162 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3163 unsigned BeginLabel = 0, EndLabel = 0;
3165 TargetLowering::ArgListTy Args;
3166 TargetLowering::ArgListEntry Entry;
3167 Args.reserve(CS.arg_size());
3168 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3170 SDOperand ArgNode = getValue(*i);
3171 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3173 unsigned attrInd = i - CS.arg_begin() + 1;
3174 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3175 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3176 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3177 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3178 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3179 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3180 Entry.Alignment = CS.getParamAlignment(attrInd);
3181 Args.push_back(Entry);
3184 if (LandingPad && FuncInfo.needsExceptionHandling && MMI) {
3185 // Insert a label before the invoke call to mark the try range. This can be
3186 // used to detect deletion of the invoke via the MachineModuleInfo.
3187 BeginLabel = MMI->NextLabelID();
3188 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3189 DAG.getConstant(BeginLabel, MVT::i32),
3190 DAG.getConstant(1, MVT::i32)));
3193 std::pair<SDOperand,SDOperand> Result =
3194 TLI.LowerCallTo(getRoot(), CS.getType(),
3195 CS.paramHasAttr(0, ParamAttr::SExt),
3196 CS.paramHasAttr(0, ParamAttr::ZExt),
3197 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3199 if (CS.getType() != Type::VoidTy)
3200 setValue(CS.getInstruction(), Result.first);
3201 DAG.setRoot(Result.second);
3203 if (LandingPad && FuncInfo.needsExceptionHandling && MMI) {
3204 // Insert a label at the end of the invoke call to mark the try range. This
3205 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3206 EndLabel = MMI->NextLabelID();
3207 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3208 DAG.getConstant(EndLabel, MVT::i32),
3209 DAG.getConstant(1, MVT::i32)));
3211 // Inform MachineModuleInfo of range.
3212 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3217 void SelectionDAGLowering::visitCall(CallInst &I) {
3218 const char *RenameFn = 0;
3219 if (Function *F = I.getCalledFunction()) {
3220 if (F->isDeclaration()) {
3221 if (unsigned IID = F->getIntrinsicID()) {
3222 RenameFn = visitIntrinsicCall(I, IID);
3228 // Check for well-known libc/libm calls. If the function is internal, it
3229 // can't be a library call.
3230 unsigned NameLen = F->getNameLen();
3231 if (!F->hasInternalLinkage() && NameLen) {
3232 const char *NameStr = F->getNameStart();
3233 if (NameStr[0] == 'c' &&
3234 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3235 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3236 if (I.getNumOperands() == 3 && // Basic sanity checks.
3237 I.getOperand(1)->getType()->isFloatingPoint() &&
3238 I.getType() == I.getOperand(1)->getType() &&
3239 I.getType() == I.getOperand(2)->getType()) {
3240 SDOperand LHS = getValue(I.getOperand(1));
3241 SDOperand RHS = getValue(I.getOperand(2));
3242 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3246 } else if (NameStr[0] == 'f' &&
3247 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3248 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3249 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3250 if (I.getNumOperands() == 2 && // Basic sanity checks.
3251 I.getOperand(1)->getType()->isFloatingPoint() &&
3252 I.getType() == I.getOperand(1)->getType()) {
3253 SDOperand Tmp = getValue(I.getOperand(1));
3254 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3257 } else if (NameStr[0] == 's' &&
3258 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3259 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3260 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3261 if (I.getNumOperands() == 2 && // Basic sanity checks.
3262 I.getOperand(1)->getType()->isFloatingPoint() &&
3263 I.getType() == I.getOperand(1)->getType()) {
3264 SDOperand Tmp = getValue(I.getOperand(1));
3265 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3268 } else if (NameStr[0] == 'c' &&
3269 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3270 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3271 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3272 if (I.getNumOperands() == 2 && // Basic sanity checks.
3273 I.getOperand(1)->getType()->isFloatingPoint() &&
3274 I.getType() == I.getOperand(1)->getType()) {
3275 SDOperand Tmp = getValue(I.getOperand(1));
3276 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3281 } else if (isa<InlineAsm>(I.getOperand(0))) {
3288 Callee = getValue(I.getOperand(0));
3290 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3292 LowerCallTo(&I, Callee, I.isTailCall());
3296 void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3297 SDOperand Call = getValue(I.getOperand(0));
3298 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3302 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3303 /// this value and returns the result as a ValueVT value. This uses
3304 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3305 /// If the Flag pointer is NULL, no flag is used.
3306 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3307 SDOperand &Chain, SDOperand *Flag)const{
3308 // Copy the legal parts from the registers.
3309 unsigned NumParts = Regs.size();
3310 SmallVector<SDOperand, 8> Parts(NumParts);
3311 for (unsigned i = 0; i != NumParts; ++i) {
3312 SDOperand Part = Flag ?
3313 DAG.getCopyFromReg(Chain, Regs[i], RegVT, *Flag) :
3314 DAG.getCopyFromReg(Chain, Regs[i], RegVT);
3315 Chain = Part.getValue(1);
3317 *Flag = Part.getValue(2);
3321 // Assemble the legal parts into the final value.
3322 return getCopyFromParts(DAG, &Parts[0], NumParts, RegVT, ValueVT);
3325 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3326 /// specified value into the registers specified by this object. This uses
3327 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3328 /// If the Flag pointer is NULL, no flag is used.
3329 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3330 SDOperand &Chain, SDOperand *Flag) const {
3331 // Get the list of the values's legal parts.
3332 unsigned NumParts = Regs.size();
3333 SmallVector<SDOperand, 8> Parts(NumParts);
3334 getCopyToParts(DAG, Val, &Parts[0], NumParts, RegVT);
3336 // Copy the parts into the registers.
3337 for (unsigned i = 0; i != NumParts; ++i) {
3338 SDOperand Part = Flag ?
3339 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) :
3340 DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3341 Chain = Part.getValue(0);
3343 *Flag = Part.getValue(1);
3347 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3348 /// operand list. This adds the code marker and includes the number of
3349 /// values added into it.
3350 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3351 std::vector<SDOperand> &Ops) const {
3352 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3353 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3354 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
3355 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
3358 /// isAllocatableRegister - If the specified register is safe to allocate,
3359 /// i.e. it isn't a stack pointer or some other special register, return the
3360 /// register class for the register. Otherwise, return null.
3361 static const TargetRegisterClass *
3362 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3363 const TargetLowering &TLI,
3364 const TargetRegisterInfo *TRI) {
3365 MVT::ValueType FoundVT = MVT::Other;
3366 const TargetRegisterClass *FoundRC = 0;
3367 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3368 E = TRI->regclass_end(); RCI != E; ++RCI) {
3369 MVT::ValueType ThisVT = MVT::Other;
3371 const TargetRegisterClass *RC = *RCI;
3372 // If none of the the value types for this register class are valid, we
3373 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3374 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3376 if (TLI.isTypeLegal(*I)) {
3377 // If we have already found this register in a different register class,
3378 // choose the one with the largest VT specified. For example, on
3379 // PowerPC, we favor f64 register classes over f32.
3380 if (FoundVT == MVT::Other ||
3381 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3388 if (ThisVT == MVT::Other) continue;
3390 // NOTE: This isn't ideal. In particular, this might allocate the
3391 // frame pointer in functions that need it (due to them not being taken
3392 // out of allocation, because a variable sized allocation hasn't been seen
3393 // yet). This is a slight code pessimization, but should still work.
3394 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3395 E = RC->allocation_order_end(MF); I != E; ++I)
3397 // We found a matching register class. Keep looking at others in case
3398 // we find one with larger registers that this physreg is also in.
3409 /// AsmOperandInfo - This contains information for each constraint that we are
3411 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3412 /// CallOperand - If this is the result output operand or a clobber
3413 /// this is null, otherwise it is the incoming operand to the CallInst.
3414 /// This gets modified as the asm is processed.
3415 SDOperand CallOperand;
3417 /// AssignedRegs - If this is a register or register class operand, this
3418 /// contains the set of register corresponding to the operand.
3419 RegsForValue AssignedRegs;
3421 SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3422 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3425 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3426 /// busy in OutputRegs/InputRegs.
3427 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3428 std::set<unsigned> &OutputRegs,
3429 std::set<unsigned> &InputRegs,
3430 const TargetRegisterInfo &TRI) const {
3432 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3433 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3436 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3437 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3442 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3444 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3445 const TargetRegisterInfo &TRI) {
3446 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3448 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3449 for (; *Aliases; ++Aliases)
3450 Regs.insert(*Aliases);
3453 } // end anon namespace.
3456 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3457 /// specified operand. We prefer to assign virtual registers, to allow the
3458 /// register allocator handle the assignment process. However, if the asm uses
3459 /// features that we can't model on machineinstrs, we have SDISel do the
3460 /// allocation. This produces generally horrible, but correct, code.
3462 /// OpInfo describes the operand.
3463 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3464 /// or any explicitly clobbered registers.
3465 /// Input and OutputRegs are the set of already allocated physical registers.
3467 void SelectionDAGLowering::
3468 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3469 std::set<unsigned> &OutputRegs,
3470 std::set<unsigned> &InputRegs) {
3471 // Compute whether this value requires an input register, an output register,
3473 bool isOutReg = false;
3474 bool isInReg = false;
3475 switch (OpInfo.Type) {
3476 case InlineAsm::isOutput:
3479 // If this is an early-clobber output, or if there is an input
3480 // constraint that matches this, we need to reserve the input register
3481 // so no other inputs allocate to it.
3482 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3484 case InlineAsm::isInput:
3488 case InlineAsm::isClobber:
3495 MachineFunction &MF = DAG.getMachineFunction();
3496 std::vector<unsigned> Regs;
3498 // If this is a constraint for a single physreg, or a constraint for a
3499 // register class, find it.
3500 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3501 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3502 OpInfo.ConstraintVT);
3504 unsigned NumRegs = 1;
3505 if (OpInfo.ConstraintVT != MVT::Other)
3506 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3507 MVT::ValueType RegVT;
3508 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3511 // If this is a constraint for a specific physical register, like {r17},
3513 if (PhysReg.first) {
3514 if (OpInfo.ConstraintVT == MVT::Other)
3515 ValueVT = *PhysReg.second->vt_begin();
3517 // Get the actual register value type. This is important, because the user
3518 // may have asked for (e.g.) the AX register in i32 type. We need to
3519 // remember that AX is actually i16 to get the right extension.
3520 RegVT = *PhysReg.second->vt_begin();
3522 // This is a explicit reference to a physical register.
3523 Regs.push_back(PhysReg.first);
3525 // If this is an expanded reference, add the rest of the regs to Regs.
3527 TargetRegisterClass::iterator I = PhysReg.second->begin();
3528 TargetRegisterClass::iterator E = PhysReg.second->end();
3529 for (; *I != PhysReg.first; ++I)
3530 assert(I != E && "Didn't find reg!");
3532 // Already added the first reg.
3534 for (; NumRegs; --NumRegs, ++I) {
3535 assert(I != E && "Ran out of registers to allocate!");
3539 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3540 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3541 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3545 // Otherwise, if this was a reference to an LLVM register class, create vregs
3546 // for this reference.
3547 std::vector<unsigned> RegClassRegs;
3548 const TargetRegisterClass *RC = PhysReg.second;
3550 // If this is an early clobber or tied register, our regalloc doesn't know
3551 // how to maintain the constraint. If it isn't, go ahead and create vreg
3552 // and let the regalloc do the right thing.
3553 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3554 // If there is some other early clobber and this is an input register,
3555 // then we are forced to pre-allocate the input reg so it doesn't
3556 // conflict with the earlyclobber.
3557 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3558 RegVT = *PhysReg.second->vt_begin();
3560 if (OpInfo.ConstraintVT == MVT::Other)
3563 // Create the appropriate number of virtual registers.
3564 MachineRegisterInfo &RegInfo = MF.getRegInfo();
3565 for (; NumRegs; --NumRegs)
3566 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
3568 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3572 // Otherwise, we can't allocate it. Let the code below figure out how to
3573 // maintain these constraints.
3574 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3577 // This is a reference to a register class that doesn't directly correspond
3578 // to an LLVM register class. Allocate NumRegs consecutive, available,
3579 // registers from the class.
3580 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3581 OpInfo.ConstraintVT);
3584 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3585 unsigned NumAllocated = 0;
3586 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3587 unsigned Reg = RegClassRegs[i];
3588 // See if this register is available.
3589 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3590 (isInReg && InputRegs.count(Reg))) { // Already used.
3591 // Make sure we find consecutive registers.
3596 // Check to see if this register is allocatable (i.e. don't give out the
3599 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
3600 if (!RC) { // Couldn't allocate this register.
3601 // Reset NumAllocated to make sure we return consecutive registers.
3607 // Okay, this register is good, we can use it.
3610 // If we allocated enough consecutive registers, succeed.
3611 if (NumAllocated == NumRegs) {
3612 unsigned RegStart = (i-NumAllocated)+1;
3613 unsigned RegEnd = i+1;
3614 // Mark all of the allocated registers used.
3615 for (unsigned i = RegStart; i != RegEnd; ++i)
3616 Regs.push_back(RegClassRegs[i]);
3618 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3619 OpInfo.ConstraintVT);
3620 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3625 // Otherwise, we couldn't allocate enough registers for this.
3630 /// visitInlineAsm - Handle a call to an InlineAsm object.
3632 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3633 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3635 /// ConstraintOperands - Information about all of the constraints.
3636 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
3638 SDOperand Chain = getRoot();
3641 std::set<unsigned> OutputRegs, InputRegs;
3643 // Do a prepass over the constraints, canonicalizing them, and building up the
3644 // ConstraintOperands list.
3645 std::vector<InlineAsm::ConstraintInfo>
3646 ConstraintInfos = IA->ParseConstraints();
3648 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3649 // constraint. If so, we can't let the register allocator allocate any input
3650 // registers, because it will not know to avoid the earlyclobbered output reg.
3651 bool SawEarlyClobber = false;
3653 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3654 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3655 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3656 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
3658 MVT::ValueType OpVT = MVT::Other;
3660 // Compute the value type for each operand.
3661 switch (OpInfo.Type) {
3662 case InlineAsm::isOutput:
3663 if (!OpInfo.isIndirect) {
3664 // The return value of the call is this value. As such, there is no
3665 // corresponding argument.
3666 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3667 OpVT = TLI.getValueType(CS.getType());
3669 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3672 case InlineAsm::isInput:
3673 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3675 case InlineAsm::isClobber:
3680 // If this is an input or an indirect output, process the call argument.
3681 // BasicBlocks are labels, currently appearing only in asm's.
3682 if (OpInfo.CallOperandVal) {
3683 if (isa<BasicBlock>(OpInfo.CallOperandVal))
3684 OpInfo.CallOperand =
3685 DAG.getBasicBlock(FuncInfo.MBBMap[cast<BasicBlock>(
3686 OpInfo.CallOperandVal)]);
3688 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3689 const Type *OpTy = OpInfo.CallOperandVal->getType();
3690 // If this is an indirect operand, the operand is a pointer to the
3692 if (OpInfo.isIndirect)
3693 OpTy = cast<PointerType>(OpTy)->getElementType();
3695 // If OpTy is not a first-class value, it may be a struct/union that we
3696 // can tile with integers.
3697 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3698 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3706 OpTy = IntegerType::get(BitSize);
3711 OpVT = TLI.getValueType(OpTy, true);
3715 OpInfo.ConstraintVT = OpVT;
3717 // Compute the constraint code and ConstraintType to use.
3718 OpInfo.ComputeConstraintToUse(TLI);
3720 // Keep track of whether we see an earlyclobber.
3721 SawEarlyClobber |= OpInfo.isEarlyClobber;
3723 // If we see a clobber of a register, it is an early clobber.
3724 if (!SawEarlyClobber &&
3725 OpInfo.Type == InlineAsm::isClobber &&
3726 OpInfo.ConstraintType == TargetLowering::C_Register) {
3727 // Note that we want to ignore things that we don't trick here, like
3728 // dirflag, fpsr, flags, etc.
3729 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3730 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3731 OpInfo.ConstraintVT);
3732 if (PhysReg.first || PhysReg.second) {
3733 // This is a register we know of.
3734 SawEarlyClobber = true;
3738 // If this is a memory input, and if the operand is not indirect, do what we
3739 // need to to provide an address for the memory input.
3740 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3741 !OpInfo.isIndirect) {
3742 assert(OpInfo.Type == InlineAsm::isInput &&
3743 "Can only indirectify direct input operands!");
3745 // Memory operands really want the address of the value. If we don't have
3746 // an indirect input, put it in the constpool if we can, otherwise spill
3747 // it to a stack slot.
3749 // If the operand is a float, integer, or vector constant, spill to a
3750 // constant pool entry to get its address.
3751 Value *OpVal = OpInfo.CallOperandVal;
3752 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3753 isa<ConstantVector>(OpVal)) {
3754 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3755 TLI.getPointerTy());
3757 // Otherwise, create a stack slot and emit a store to it before the
3759 const Type *Ty = OpVal->getType();
3760 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
3761 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3762 MachineFunction &MF = DAG.getMachineFunction();
3763 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3764 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3765 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3766 OpInfo.CallOperand = StackSlot;
3769 // There is no longer a Value* corresponding to this operand.
3770 OpInfo.CallOperandVal = 0;
3771 // It is now an indirect operand.
3772 OpInfo.isIndirect = true;
3775 // If this constraint is for a specific register, allocate it before
3777 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3778 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3780 ConstraintInfos.clear();
3783 // Second pass - Loop over all of the operands, assigning virtual or physregs
3784 // to registerclass operands.
3785 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3786 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3788 // C_Register operands have already been allocated, Other/Memory don't need
3790 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3791 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3794 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3795 std::vector<SDOperand> AsmNodeOperands;
3796 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3797 AsmNodeOperands.push_back(
3798 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3801 // Loop over all of the inputs, copying the operand values into the
3802 // appropriate registers and processing the output regs.
3803 RegsForValue RetValRegs;
3805 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3806 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3808 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3809 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3811 switch (OpInfo.Type) {
3812 case InlineAsm::isOutput: {
3813 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3814 OpInfo.ConstraintType != TargetLowering::C_Register) {
3815 // Memory output, or 'other' output (e.g. 'X' constraint).
3816 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3818 // Add information to the INLINEASM node to know about this output.
3819 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3820 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3821 TLI.getPointerTy()));
3822 AsmNodeOperands.push_back(OpInfo.CallOperand);
3826 // Otherwise, this is a register or register class output.
3828 // Copy the output from the appropriate register. Find a register that
3830 if (OpInfo.AssignedRegs.Regs.empty()) {
3831 cerr << "Couldn't allocate output reg for contraint '"
3832 << OpInfo.ConstraintCode << "'!\n";
3836 if (!OpInfo.isIndirect) {
3837 // This is the result value of the call.
3838 assert(RetValRegs.Regs.empty() &&
3839 "Cannot have multiple output constraints yet!");
3840 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3841 RetValRegs = OpInfo.AssignedRegs;
3843 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
3844 OpInfo.CallOperandVal));
3847 // Add information to the INLINEASM node to know that this register is
3849 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3853 case InlineAsm::isInput: {
3854 SDOperand InOperandVal = OpInfo.CallOperand;
3856 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
3857 // If this is required to match an output register we have already set,
3858 // just use its register.
3859 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
3861 // Scan until we find the definition we already emitted of this operand.
3862 // When we find it, create a RegsForValue operand.
3863 unsigned CurOp = 2; // The first operand.
3864 for (; OperandNo; --OperandNo) {
3865 // Advance to the next operand.
3867 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3868 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3869 (NumOps & 7) == 4 /*MEM*/) &&
3870 "Skipped past definitions?");
3871 CurOp += (NumOps>>3)+1;
3875 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3876 if ((NumOps & 7) == 2 /*REGDEF*/) {
3877 // Add NumOps>>3 registers to MatchedRegs.
3878 RegsForValue MatchedRegs;
3879 MatchedRegs.ValueVT = InOperandVal.getValueType();
3880 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3881 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3883 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3884 MatchedRegs.Regs.push_back(Reg);
3887 // Use the produced MatchedRegs object to
3888 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
3889 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3892 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3893 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
3894 // Add information to the INLINEASM node to know about this input.
3895 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3896 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3897 TLI.getPointerTy()));
3898 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
3903 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
3904 assert(!OpInfo.isIndirect &&
3905 "Don't know how to handle indirect other inputs yet!");
3907 std::vector<SDOperand> Ops;
3908 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
3911 cerr << "Invalid operand for inline asm constraint '"
3912 << OpInfo.ConstraintCode << "'!\n";
3916 // Add information to the INLINEASM node to know about this input.
3917 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
3918 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3919 TLI.getPointerTy()));
3920 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
3922 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
3923 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
3924 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3925 "Memory operands expect pointer values");
3927 // Add information to the INLINEASM node to know about this input.
3928 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3929 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3930 TLI.getPointerTy()));
3931 AsmNodeOperands.push_back(InOperandVal);
3935 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3936 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3937 "Unknown constraint type!");
3938 assert(!OpInfo.isIndirect &&
3939 "Don't know how to handle indirect register inputs yet!");
3941 // Copy the input into the appropriate registers.
3942 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3943 "Couldn't allocate input reg!");
3945 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
3947 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3951 case InlineAsm::isClobber: {
3952 // Add the clobbered value to the operand list, so that the register
3953 // allocator is aware that the physreg got clobbered.
3954 if (!OpInfo.AssignedRegs.Regs.empty())
3955 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3962 // Finish up input operands.
3963 AsmNodeOperands[0] = Chain;
3964 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3966 Chain = DAG.getNode(ISD::INLINEASM,
3967 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
3968 &AsmNodeOperands[0], AsmNodeOperands.size());
3969 Flag = Chain.getValue(1);
3971 // If this asm returns a register value, copy the result from that register
3972 // and set it as the value of the call.
3973 if (!RetValRegs.Regs.empty()) {
3974 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
3976 // If the result of the inline asm is a vector, it may have the wrong
3977 // width/num elts. Make sure to convert it to the right type with
3979 if (MVT::isVector(Val.getValueType())) {
3980 const VectorType *VTy = cast<VectorType>(CS.getType());
3981 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
3983 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
3986 setValue(CS.getInstruction(), Val);
3989 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3991 // Process indirect outputs, first output all of the flagged copies out of
3993 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
3994 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
3995 Value *Ptr = IndirectStoresToEmit[i].second;
3996 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
3997 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4000 // Emit the non-flagged stores from the physregs.
4001 SmallVector<SDOperand, 8> OutChains;
4002 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4003 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4004 getValue(StoresToEmit[i].second),
4005 StoresToEmit[i].second, 0));
4006 if (!OutChains.empty())
4007 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4008 &OutChains[0], OutChains.size());
4013 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4014 SDOperand Src = getValue(I.getOperand(0));
4016 MVT::ValueType IntPtr = TLI.getPointerTy();
4018 if (IntPtr < Src.getValueType())
4019 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4020 else if (IntPtr > Src.getValueType())
4021 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4023 // Scale the source by the type size.
4024 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4025 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4026 Src, DAG.getIntPtrConstant(ElementSize));
4028 TargetLowering::ArgListTy Args;
4029 TargetLowering::ArgListEntry Entry;
4031 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4032 Args.push_back(Entry);
4034 std::pair<SDOperand,SDOperand> Result =
4035 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4036 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4037 setValue(&I, Result.first); // Pointers always fit in registers
4038 DAG.setRoot(Result.second);
4041 void SelectionDAGLowering::visitFree(FreeInst &I) {
4042 TargetLowering::ArgListTy Args;
4043 TargetLowering::ArgListEntry Entry;
4044 Entry.Node = getValue(I.getOperand(0));
4045 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4046 Args.push_back(Entry);
4047 MVT::ValueType IntPtr = TLI.getPointerTy();
4048 std::pair<SDOperand,SDOperand> Result =
4049 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4050 CallingConv::C, true,
4051 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4052 DAG.setRoot(Result.second);
4055 // EmitInstrWithCustomInserter - This method should be implemented by targets
4056 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
4057 // instructions are special in various ways, which require special support to
4058 // insert. The specified MachineInstr is created but not inserted into any
4059 // basic blocks, and the scheduler passes ownership of it to this method.
4060 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4061 MachineBasicBlock *MBB) {
4062 cerr << "If a target marks an instruction with "
4063 << "'usesCustomDAGSchedInserter', it must implement "
4064 << "TargetLowering::EmitInstrWithCustomInserter!\n";
4069 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4070 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4071 getValue(I.getOperand(1)),
4072 DAG.getSrcValue(I.getOperand(1))));
4075 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4076 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4077 getValue(I.getOperand(0)),
4078 DAG.getSrcValue(I.getOperand(0)));
4080 DAG.setRoot(V.getValue(1));
4083 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4084 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4085 getValue(I.getOperand(1)),
4086 DAG.getSrcValue(I.getOperand(1))));
4089 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4090 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4091 getValue(I.getOperand(1)),
4092 getValue(I.getOperand(2)),
4093 DAG.getSrcValue(I.getOperand(1)),
4094 DAG.getSrcValue(I.getOperand(2))));
4097 /// TargetLowering::LowerArguments - This is the default LowerArguments
4098 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4099 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4100 /// integrated into SDISel.
4101 std::vector<SDOperand>
4102 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4103 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4104 std::vector<SDOperand> Ops;
4105 Ops.push_back(DAG.getRoot());
4106 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4107 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4109 // Add one result value for each formal argument.
4110 std::vector<MVT::ValueType> RetVals;
4112 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4114 MVT::ValueType VT = getValueType(I->getType());
4115 ISD::ArgFlagsTy Flags;
4116 unsigned OriginalAlignment =
4117 getTargetData()->getABITypeAlignment(I->getType());
4119 if (F.paramHasAttr(j, ParamAttr::ZExt))
4121 if (F.paramHasAttr(j, ParamAttr::SExt))
4123 if (F.paramHasAttr(j, ParamAttr::InReg))
4125 if (F.paramHasAttr(j, ParamAttr::StructRet))
4127 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4129 const PointerType *Ty = cast<PointerType>(I->getType());
4130 const Type *ElementTy = Ty->getElementType();
4131 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4132 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4133 // For ByVal, alignment should be passed from FE. BE will guess if
4134 // this info is not there but there are cases it cannot get right.
4135 if (F.getParamAlignment(j))
4136 FrameAlign = F.getParamAlignment(j);
4137 Flags.setByValAlign(FrameAlign);
4138 Flags.setByValSize(FrameSize);
4140 if (F.paramHasAttr(j, ParamAttr::Nest))
4142 Flags.setOrigAlign(OriginalAlignment);
4144 MVT::ValueType RegisterVT = getRegisterType(VT);
4145 unsigned NumRegs = getNumRegisters(VT);
4146 for (unsigned i = 0; i != NumRegs; ++i) {
4147 RetVals.push_back(RegisterVT);
4148 // if it isn't first piece, alignment must be 1
4150 Flags.setOrigAlign(1);
4151 Ops.push_back(DAG.getArgFlags(Flags));
4155 RetVals.push_back(MVT::Other);
4158 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4159 DAG.getVTList(&RetVals[0], RetVals.size()),
4160 &Ops[0], Ops.size()).Val;
4162 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4163 // allows exposing the loads that may be part of the argument access to the
4164 // first DAGCombiner pass.
4165 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4167 // The number of results should match up, except that the lowered one may have
4168 // an extra flag result.
4169 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4170 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4171 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4172 && "Lowering produced unexpected number of results!");
4173 Result = TmpRes.Val;
4175 unsigned NumArgRegs = Result->getNumValues() - 1;
4176 DAG.setRoot(SDOperand(Result, NumArgRegs));
4178 // Set up the return result vector.
4182 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4184 MVT::ValueType VT = getValueType(I->getType());
4185 MVT::ValueType PartVT = getRegisterType(VT);
4187 unsigned NumParts = getNumRegisters(VT);
4188 SmallVector<SDOperand, 4> Parts(NumParts);
4189 for (unsigned j = 0; j != NumParts; ++j)
4190 Parts[j] = SDOperand(Result, i++);
4192 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4193 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4194 AssertOp = ISD::AssertSext;
4195 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4196 AssertOp = ISD::AssertZext;
4198 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4201 assert(i == NumArgRegs && "Argument register count mismatch!");
4206 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4207 /// implementation, which just inserts an ISD::CALL node, which is later custom
4208 /// lowered by the target to something concrete. FIXME: When all targets are
4209 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4210 std::pair<SDOperand, SDOperand>
4211 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4212 bool RetSExt, bool RetZExt, bool isVarArg,
4213 unsigned CallingConv, bool isTailCall,
4215 ArgListTy &Args, SelectionDAG &DAG) {
4216 SmallVector<SDOperand, 32> Ops;
4217 Ops.push_back(Chain); // Op#0 - Chain
4218 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4219 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4220 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4221 Ops.push_back(Callee);
4223 // Handle all of the outgoing arguments.
4224 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4225 MVT::ValueType VT = getValueType(Args[i].Ty);
4226 SDOperand Op = Args[i].Node;
4227 ISD::ArgFlagsTy Flags;
4228 unsigned OriginalAlignment =
4229 getTargetData()->getABITypeAlignment(Args[i].Ty);
4235 if (Args[i].isInReg)
4239 if (Args[i].isByVal) {
4241 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4242 const Type *ElementTy = Ty->getElementType();
4243 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4244 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4245 // For ByVal, alignment should come from FE. BE will guess if this
4246 // info is not there but there are cases it cannot get right.
4247 if (Args[i].Alignment)
4248 FrameAlign = Args[i].Alignment;
4249 Flags.setByValAlign(FrameAlign);
4250 Flags.setByValSize(FrameSize);
4254 Flags.setOrigAlign(OriginalAlignment);
4256 MVT::ValueType PartVT = getRegisterType(VT);
4257 unsigned NumParts = getNumRegisters(VT);
4258 SmallVector<SDOperand, 4> Parts(NumParts);
4259 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4262 ExtendKind = ISD::SIGN_EXTEND;
4263 else if (Args[i].isZExt)
4264 ExtendKind = ISD::ZERO_EXTEND;
4266 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4268 for (unsigned i = 0; i != NumParts; ++i) {
4269 // if it isn't first piece, alignment must be 1
4270 ISD::ArgFlagsTy MyFlags = Flags;
4272 MyFlags.setOrigAlign(1);
4274 Ops.push_back(Parts[i]);
4275 Ops.push_back(DAG.getArgFlags(MyFlags));
4279 // Figure out the result value types. We start by making a list of
4280 // the high-level LLVM return types.
4281 SmallVector<const Type *, 4> LLVMRetTys;
4282 if (const StructType *ST = dyn_cast<StructType>(RetTy))
4283 // A struct return type in the LLVM IR means we have multiple return values.
4284 LLVMRetTys.insert(LLVMRetTys.end(), ST->element_begin(), ST->element_end());
4286 LLVMRetTys.push_back(RetTy);
4288 // Then we translate that to a list of lowered codegen result types.
4289 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4290 SmallVector<MVT::ValueType, 4> RetTys;
4291 for (unsigned I = 0, E = LLVMRetTys.size(); I != E; ++I) {
4292 MVT::ValueType VT = getValueType(LLVMRetTys[I]);
4293 RetTys.push_back(VT);
4295 MVT::ValueType RegisterVT = getRegisterType(VT);
4296 unsigned NumRegs = getNumRegisters(VT);
4297 for (unsigned i = 0; i != NumRegs; ++i)
4298 LoweredRetTys.push_back(RegisterVT);
4301 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4303 // Create the CALL node.
4304 SDOperand Res = DAG.getNode(ISD::CALL,
4305 DAG.getVTList(&LoweredRetTys[0],
4306 LoweredRetTys.size()),
4307 &Ops[0], Ops.size());
4308 Chain = Res.getValue(LoweredRetTys.size() - 1);
4310 // Gather up the call result into a single value.
4311 if (RetTy != Type::VoidTy) {
4312 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4315 AssertOp = ISD::AssertSext;
4317 AssertOp = ISD::AssertZext;
4319 SmallVector<SDOperand, 4> ReturnValues;
4321 for (unsigned I = 0, E = LLVMRetTys.size(); I != E; ++I) {
4322 MVT::ValueType VT = getValueType(LLVMRetTys[I]);
4323 MVT::ValueType RegisterVT = getRegisterType(VT);
4324 unsigned NumRegs = getNumRegisters(VT);
4325 unsigned RegNoEnd = NumRegs + RegNo;
4326 SmallVector<SDOperand, 4> Results;
4327 for (; RegNo != RegNoEnd; ++RegNo)
4328 Results.push_back(Res.getValue(RegNo));
4329 SDOperand ReturnValue =
4330 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4332 ReturnValues.push_back(ReturnValue);
4334 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4335 DAG.getNode(ISD::MERGE_VALUES,
4336 DAG.getVTList(&RetTys[0], RetTys.size()),
4337 &ReturnValues[0], ReturnValues.size());
4340 return std::make_pair(Res, Chain);
4343 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4344 assert(0 && "LowerOperation not implemented for this target!");
4349 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4350 SelectionDAG &DAG) {
4351 assert(0 && "CustomPromoteOperation not implemented for this target!");
4356 /// getMemsetValue - Vectorized representation of the memset value
4358 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
4359 SelectionDAG &DAG) {
4360 MVT::ValueType CurVT = VT;
4361 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4362 uint64_t Val = C->getValue() & 255;
4364 while (CurVT != MVT::i8) {
4365 Val = (Val << Shift) | Val;
4367 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4369 return DAG.getConstant(Val, VT);
4371 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4373 while (CurVT != MVT::i8) {
4375 DAG.getNode(ISD::OR, VT,
4376 DAG.getNode(ISD::SHL, VT, Value,
4377 DAG.getConstant(Shift, MVT::i8)), Value);
4379 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4386 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4387 /// used when a memcpy is turned into a memset when the source is a constant
4389 static SDOperand getMemsetStringVal(MVT::ValueType VT,
4390 SelectionDAG &DAG, TargetLowering &TLI,
4391 std::string &Str, unsigned Offset) {
4393 unsigned MSB = MVT::getSizeInBits(VT) / 8;
4394 if (TLI.isLittleEndian())
4395 Offset = Offset + MSB - 1;
4396 for (unsigned i = 0; i != MSB; ++i) {
4397 Val = (Val << 8) | (unsigned char)Str[Offset];
4398 Offset += TLI.isLittleEndian() ? -1 : 1;
4400 return DAG.getConstant(Val, VT);
4403 /// getMemBasePlusOffset - Returns base and offset node for the
4404 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4405 SelectionDAG &DAG, TargetLowering &TLI) {
4406 MVT::ValueType VT = Base.getValueType();
4407 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4410 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
4411 /// to replace the memset / memcpy is below the threshold. It also returns the
4412 /// types of the sequence of memory ops to perform memset / memcpy.
4413 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4414 unsigned Limit, uint64_t Size,
4415 unsigned Align, TargetLowering &TLI) {
4418 if (TLI.allowsUnalignedMemoryAccesses()) {
4421 switch (Align & 7) {
4437 MVT::ValueType LVT = MVT::i64;
4438 while (!TLI.isTypeLegal(LVT))
4439 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4440 assert(MVT::isInteger(LVT));
4445 unsigned NumMemOps = 0;
4447 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4448 while (VTSize > Size) {
4449 VT = (MVT::ValueType)((unsigned)VT - 1);
4452 assert(MVT::isInteger(VT));
4454 if (++NumMemOps > Limit)
4456 MemOps.push_back(VT);
4463 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
4464 SDOperand Op1 = getValue(I.getOperand(1));
4465 SDOperand Op2 = getValue(I.getOperand(2));
4466 SDOperand Op3 = getValue(I.getOperand(3));
4467 SDOperand Op4 = getValue(I.getOperand(4));
4468 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4469 if (Align == 0) Align = 1;
4471 // If the source and destination are known to not be aliases, we can
4472 // lower memmove as memcpy.
4473 if (Op == ISD::MEMMOVE) {
4474 uint64_t Size = -1ULL;
4475 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
4476 Size = C->getValue();
4477 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
4478 AliasAnalysis::NoAlias)
4482 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4483 std::vector<MVT::ValueType> MemOps;
4485 // Expand memset / memcpy to a series of load / store ops
4486 // if the size operand falls below a certain threshold.
4487 SmallVector<SDOperand, 8> OutChains;
4489 default: break; // Do nothing for now.
4491 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4492 Size->getValue(), Align, TLI)) {
4493 unsigned NumMemOps = MemOps.size();
4494 unsigned Offset = 0;
4495 for (unsigned i = 0; i < NumMemOps; i++) {
4496 MVT::ValueType VT = MemOps[i];
4497 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4498 SDOperand Value = getMemsetValue(Op2, VT, DAG);
4499 SDOperand Store = DAG.getStore(getRoot(), Value,
4500 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
4501 I.getOperand(1), Offset);
4502 OutChains.push_back(Store);
4509 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4510 Size->getValue(), Align, TLI)) {
4511 unsigned NumMemOps = MemOps.size();
4512 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
4513 GlobalAddressSDNode *G = NULL;
4515 bool CopyFromStr = false;
4517 if (Op2.getOpcode() == ISD::GlobalAddress)
4518 G = cast<GlobalAddressSDNode>(Op2);
4519 else if (Op2.getOpcode() == ISD::ADD &&
4520 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4521 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4522 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
4523 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
4526 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
4527 if (GV && GV->isConstant()) {
4528 Str = GV->getStringValue(false);
4536 for (unsigned i = 0; i < NumMemOps; i++) {
4537 MVT::ValueType VT = MemOps[i];
4538 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4539 SDOperand Value, Chain, Store;
4542 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4545 DAG.getStore(Chain, Value,
4546 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4547 I.getOperand(1), DstOff);
4549 Value = DAG.getLoad(VT, getRoot(),
4550 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
4551 I.getOperand(2), SrcOff, false, Align);
4552 Chain = Value.getValue(1);
4554 DAG.getStore(Chain, Value,
4555 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4556 I.getOperand(1), DstOff, false, Align);
4558 OutChains.push_back(Store);
4567 if (!OutChains.empty()) {
4568 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4569 &OutChains[0], OutChains.size()));
4574 SDOperand AlwaysInline = DAG.getConstant(0, MVT::i1);
4578 assert(0 && "Unknown Op");
4580 Node = DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Op4, AlwaysInline);
4583 Node = DAG.getMemmove(getRoot(), Op1, Op2, Op3, Op4, AlwaysInline);
4586 Node = DAG.getMemset(getRoot(), Op1, Op2, Op3, Op4, AlwaysInline);
4592 //===----------------------------------------------------------------------===//
4593 // SelectionDAGISel code
4594 //===----------------------------------------------------------------------===//
4596 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4597 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4600 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4601 AU.addRequired<AliasAnalysis>();
4602 AU.addRequired<CollectorModuleMetadata>();
4603 AU.setPreservesAll();
4608 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4609 // Get alias analysis for load/store combining.
4610 AA = &getAnalysis<AliasAnalysis>();
4612 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4613 if (MF.getFunction()->hasCollector())
4614 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4617 RegInfo = &MF.getRegInfo();
4618 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4620 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4622 if (FuncInfo.needsExceptionHandling)
4623 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4624 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4625 // Mark landing pad.
4626 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4628 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4629 SelectBasicBlock(I, MF, FuncInfo);
4631 // Add function live-ins to entry block live-in set.
4632 BasicBlock *EntryBB = &Fn.getEntryBlock();
4633 BB = FuncInfo.MBBMap[EntryBB];
4634 if (!RegInfo->livein_empty())
4635 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4636 E = RegInfo->livein_end(); I != E; ++I)
4637 BB->addLiveIn(I->first);
4640 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4641 "Not all catch info was assigned to a landing pad!");
4647 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4649 SDOperand Op = getValue(V);
4650 assert((Op.getOpcode() != ISD::CopyFromReg ||
4651 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4652 "Copy from a reg to the same reg!");
4653 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4655 MVT::ValueType SrcVT = Op.getValueType();
4656 MVT::ValueType RegisterVT = TLI.getRegisterType(SrcVT);
4657 unsigned NumRegs = TLI.getNumRegisters(SrcVT);
4658 SmallVector<SDOperand, 8> Regs(NumRegs);
4659 SmallVector<SDOperand, 8> Chains(NumRegs);
4661 // Copy the value by legal parts into sequential virtual registers.
4662 getCopyToParts(DAG, Op, &Regs[0], NumRegs, RegisterVT);
4663 for (unsigned i = 0; i != NumRegs; ++i)
4664 Chains[i] = DAG.getCopyToReg(DAG.getEntryNode(), Reg + i, Regs[i]);
4665 SDOperand Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4666 PendingExports.push_back(Ch);
4669 void SelectionDAGISel::
4670 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4671 // If this is the entry block, emit arguments.
4672 Function &F = *LLVMBB->getParent();
4673 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4674 SDOperand OldRoot = SDL.DAG.getRoot();
4675 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4678 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4680 if (!AI->use_empty()) {
4681 SDL.setValue(AI, Args[a]);
4683 // If this argument is live outside of the entry block, insert a copy from
4684 // whereever we got it to the vreg that other BB's will reference it as.
4685 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4686 if (VMI != FuncInfo.ValueMap.end()) {
4687 SDL.CopyValueToVirtualRegister(AI, VMI->second);
4691 // Finally, if the target has anything special to do, allow it to do so.
4692 // FIXME: this should insert code into the DAG!
4693 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4696 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4697 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4698 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4699 if (isSelector(I)) {
4700 // Apply the catch info to DestBB.
4701 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4703 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4704 FLI.CatchInfoFound.insert(I);
4709 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
4710 /// DAG and fixes their tailcall attribute operand.
4711 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4712 TargetLowering& TLI) {
4713 SDNode * Ret = NULL;
4714 SDOperand Terminator = DAG.getRoot();
4717 if (Terminator.getOpcode() == ISD::RET) {
4718 Ret = Terminator.Val;
4721 // Fix tail call attribute of CALL nodes.
4722 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4723 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4724 if (BI->getOpcode() == ISD::CALL) {
4725 SDOperand OpRet(Ret, 0);
4726 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4727 bool isMarkedTailCall =
4728 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4729 // If CALL node has tail call attribute set to true and the call is not
4730 // eligible (no RET or the target rejects) the attribute is fixed to
4731 // false. The TargetLowering::IsEligibleForTailCallOptimization function
4732 // must correctly identify tail call optimizable calls.
4733 if (isMarkedTailCall &&
4735 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) {
4736 SmallVector<SDOperand, 32> Ops;
4738 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4739 E=OpCall.Val->op_end(); I!=E; I++, idx++) {
4743 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4745 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4751 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4752 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4753 FunctionLoweringInfo &FuncInfo) {
4754 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
4756 // Lower any arguments needed in this block if this is the entry block.
4757 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4758 LowerArguments(LLVMBB, SDL);
4760 BB = FuncInfo.MBBMap[LLVMBB];
4761 SDL.setCurrentBasicBlock(BB);
4763 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4765 if (FuncInfo.needsExceptionHandling && MMI && BB->isLandingPad()) {
4766 // Add a label to mark the beginning of the landing pad. Deletion of the
4767 // landing pad can thus be detected via the MachineModuleInfo.
4768 unsigned LabelID = MMI->addLandingPad(BB);
4769 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4770 DAG.getConstant(LabelID, MVT::i32),
4771 DAG.getConstant(1, MVT::i32)));
4773 // Mark exception register as live in.
4774 unsigned Reg = TLI.getExceptionAddressRegister();
4775 if (Reg) BB->addLiveIn(Reg);
4777 // Mark exception selector register as live in.
4778 Reg = TLI.getExceptionSelectorRegister();
4779 if (Reg) BB->addLiveIn(Reg);
4781 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4782 // function and list of typeids logically belong to the invoke (or, if you
4783 // like, the basic block containing the invoke), and need to be associated
4784 // with it in the dwarf exception handling tables. Currently however the
4785 // information is provided by an intrinsic (eh.selector) that can be moved
4786 // to unexpected places by the optimizers: if the unwind edge is critical,
4787 // then breaking it can result in the intrinsics being in the successor of
4788 // the landing pad, not the landing pad itself. This results in exceptions
4789 // not being caught because no typeids are associated with the invoke.
4790 // This may not be the only way things can go wrong, but it is the only way
4791 // we try to work around for the moment.
4792 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4794 if (Br && Br->isUnconditional()) { // Critical edge?
4795 BasicBlock::iterator I, E;
4796 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4801 // No catch info found - try to extract some from the successor.
4802 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
4806 // Lower all of the non-terminator instructions.
4807 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4811 // Ensure that all instructions which are used outside of their defining
4812 // blocks are available as virtual registers. Invoke is handled elsewhere.
4813 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4814 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
4815 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4816 if (VMI != FuncInfo.ValueMap.end())
4817 SDL.CopyValueToVirtualRegister(I, VMI->second);
4820 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4821 // ensure constants are generated when needed. Remember the virtual registers
4822 // that need to be added to the Machine PHI nodes as input. We cannot just
4823 // directly add them, because expansion might result in multiple MBB's for one
4824 // BB. As such, the start of the BB might correspond to a different MBB than
4827 TerminatorInst *TI = LLVMBB->getTerminator();
4829 // Emit constants only once even if used by multiple PHI nodes.
4830 std::map<Constant*, unsigned> ConstantsOut;
4832 // Vector bool would be better, but vector<bool> is really slow.
4833 std::vector<unsigned char> SuccsHandled;
4834 if (TI->getNumSuccessors())
4835 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4837 // Check successor nodes' PHI nodes that expect a constant to be available
4839 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4840 BasicBlock *SuccBB = TI->getSuccessor(succ);
4841 if (!isa<PHINode>(SuccBB->begin())) continue;
4842 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4844 // If this terminator has multiple identical successors (common for
4845 // switches), only handle each succ once.
4846 unsigned SuccMBBNo = SuccMBB->getNumber();
4847 if (SuccsHandled[SuccMBBNo]) continue;
4848 SuccsHandled[SuccMBBNo] = true;
4850 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4853 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4854 // nodes and Machine PHI nodes, but the incoming operands have not been
4856 for (BasicBlock::iterator I = SuccBB->begin();
4857 (PN = dyn_cast<PHINode>(I)); ++I) {
4858 // Ignore dead phi's.
4859 if (PN->use_empty()) continue;
4862 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4864 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4865 unsigned &RegOut = ConstantsOut[C];
4867 RegOut = FuncInfo.CreateRegForValue(C);
4868 SDL.CopyValueToVirtualRegister(C, RegOut);
4872 Reg = FuncInfo.ValueMap[PHIOp];
4874 assert(isa<AllocaInst>(PHIOp) &&
4875 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4876 "Didn't codegen value into a register!??");
4877 Reg = FuncInfo.CreateRegForValue(PHIOp);
4878 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
4882 // Remember that this register needs to added to the machine PHI node as
4883 // the input for this MBB.
4884 MVT::ValueType VT = TLI.getValueType(PN->getType());
4885 unsigned NumRegisters = TLI.getNumRegisters(VT);
4886 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4887 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4890 ConstantsOut.clear();
4892 // Lower the terminator after the copies are emitted.
4893 SDL.visit(*LLVMBB->getTerminator());
4895 // Copy over any CaseBlock records that may now exist due to SwitchInst
4896 // lowering, as well as any jump table information.
4897 SwitchCases.clear();
4898 SwitchCases = SDL.SwitchCases;
4900 JTCases = SDL.JTCases;
4901 BitTestCases.clear();
4902 BitTestCases = SDL.BitTestCases;
4904 // Make sure the root of the DAG is up-to-date.
4905 DAG.setRoot(SDL.getControlRoot());
4907 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4908 // with correct tailcall attribute so that the target can rely on the tailcall
4909 // attribute indicating whether the call is really eligible for tail call
4911 CheckDAGForTailCallsAndFixThem(DAG, TLI);
4914 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4915 DOUT << "Lowered selection DAG:\n";
4918 // Run the DAG combiner in pre-legalize mode.
4919 DAG.Combine(false, *AA);
4921 DOUT << "Optimized lowered selection DAG:\n";
4924 // Second step, hack on the DAG until it only uses operations and types that
4925 // the target supports.
4926 #if 0 // Enable this some day.
4927 DAG.LegalizeTypes();
4928 // Someday even later, enable a dag combine pass here.
4932 DOUT << "Legalized selection DAG:\n";
4935 // Run the DAG combiner in post-legalize mode.
4936 DAG.Combine(true, *AA);
4938 DOUT << "Optimized legalized selection DAG:\n";
4941 if (ViewISelDAGs) DAG.viewGraph();
4943 // Third, instruction select all of the operations to machine code, adding the
4944 // code to the MachineBasicBlock.
4945 InstructionSelectBasicBlock(DAG);
4947 DOUT << "Selected machine code:\n";
4951 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4952 FunctionLoweringInfo &FuncInfo) {
4953 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4955 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4958 // First step, lower LLVM code to some DAG. This DAG may use operations and
4959 // types that are not supported by the target.
4960 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4962 // Second step, emit the lowered DAG as machine code.
4963 CodeGenAndEmitDAG(DAG);
4966 DOUT << "Total amount of phi nodes to update: "
4967 << PHINodesToUpdate.size() << "\n";
4968 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4969 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4970 << ", " << PHINodesToUpdate[i].second << ")\n";);
4972 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4973 // PHI nodes in successors.
4974 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4975 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4976 MachineInstr *PHI = PHINodesToUpdate[i].first;
4977 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4978 "This is not a machine PHI node that we are updating!");
4979 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4981 PHI->addOperand(MachineOperand::CreateMBB(BB));
4986 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4987 // Lower header first, if it wasn't already lowered
4988 if (!BitTestCases[i].Emitted) {
4989 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4991 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
4992 // Set the current basic block to the mbb we wish to insert the code into
4993 BB = BitTestCases[i].Parent;
4994 HSDL.setCurrentBasicBlock(BB);
4996 HSDL.visitBitTestHeader(BitTestCases[i]);
4997 HSDAG.setRoot(HSDL.getRoot());
4998 CodeGenAndEmitDAG(HSDAG);
5001 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5002 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5004 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
5005 // Set the current basic block to the mbb we wish to insert the code into
5006 BB = BitTestCases[i].Cases[j].ThisBB;
5007 BSDL.setCurrentBasicBlock(BB);
5010 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5011 BitTestCases[i].Reg,
5012 BitTestCases[i].Cases[j]);
5014 BSDL.visitBitTestCase(BitTestCases[i].Default,
5015 BitTestCases[i].Reg,
5016 BitTestCases[i].Cases[j]);
5019 BSDAG.setRoot(BSDL.getRoot());
5020 CodeGenAndEmitDAG(BSDAG);
5024 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5025 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5026 MachineBasicBlock *PHIBB = PHI->getParent();
5027 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5028 "This is not a machine PHI node that we are updating!");
5029 // This is "default" BB. We have two jumps to it. From "header" BB and
5030 // from last "case" BB.
5031 if (PHIBB == BitTestCases[i].Default) {
5032 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5034 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5035 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5037 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5040 // One of "cases" BB.
5041 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5042 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5043 if (cBB->succ_end() !=
5044 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
5045 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5047 PHI->addOperand(MachineOperand::CreateMBB(cBB));
5053 // If the JumpTable record is filled in, then we need to emit a jump table.
5054 // Updating the PHI nodes is tricky in this case, since we need to determine
5055 // whether the PHI is a successor of the range check MBB or the jump table MBB
5056 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5057 // Lower header first, if it wasn't already lowered
5058 if (!JTCases[i].first.Emitted) {
5059 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5061 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5062 // Set the current basic block to the mbb we wish to insert the code into
5063 BB = JTCases[i].first.HeaderBB;
5064 HSDL.setCurrentBasicBlock(BB);
5066 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5067 HSDAG.setRoot(HSDL.getRoot());
5068 CodeGenAndEmitDAG(HSDAG);
5071 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5073 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
5074 // Set the current basic block to the mbb we wish to insert the code into
5075 BB = JTCases[i].second.MBB;
5076 JSDL.setCurrentBasicBlock(BB);
5078 JSDL.visitJumpTable(JTCases[i].second);
5079 JSDAG.setRoot(JSDL.getRoot());
5080 CodeGenAndEmitDAG(JSDAG);
5083 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5084 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5085 MachineBasicBlock *PHIBB = PHI->getParent();
5086 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5087 "This is not a machine PHI node that we are updating!");
5088 // "default" BB. We can go there only from header BB.
5089 if (PHIBB == JTCases[i].second.Default) {
5090 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5092 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
5094 // JT BB. Just iterate over successors here
5095 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
5096 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5098 PHI->addOperand(MachineOperand::CreateMBB(BB));
5103 // If the switch block involved a branch to one of the actual successors, we
5104 // need to update PHI nodes in that block.
5105 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5106 MachineInstr *PHI = PHINodesToUpdate[i].first;
5107 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5108 "This is not a machine PHI node that we are updating!");
5109 if (BB->isSuccessor(PHI->getParent())) {
5110 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5112 PHI->addOperand(MachineOperand::CreateMBB(BB));
5116 // If we generated any switch lowering information, build and codegen any
5117 // additional DAGs necessary.
5118 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
5119 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5121 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
5123 // Set the current basic block to the mbb we wish to insert the code into
5124 BB = SwitchCases[i].ThisBB;
5125 SDL.setCurrentBasicBlock(BB);
5128 SDL.visitSwitchCase(SwitchCases[i]);
5129 SDAG.setRoot(SDL.getRoot());
5130 CodeGenAndEmitDAG(SDAG);
5132 // Handle any PHI nodes in successors of this chunk, as if we were coming
5133 // from the original BB before switch expansion. Note that PHI nodes can
5134 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5135 // handle them the right number of times.
5136 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
5137 for (MachineBasicBlock::iterator Phi = BB->begin();
5138 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5139 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5140 for (unsigned pn = 0; ; ++pn) {
5141 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5142 if (PHINodesToUpdate[pn].first == Phi) {
5143 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5145 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5151 // Don't process RHS if same block as LHS.
5152 if (BB == SwitchCases[i].FalseBB)
5153 SwitchCases[i].FalseBB = 0;
5155 // If we haven't handled the RHS, do so now. Otherwise, we're done.
5156 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5157 SwitchCases[i].FalseBB = 0;
5159 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5164 //===----------------------------------------------------------------------===//
5165 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5166 /// target node in the graph.
5167 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5168 if (ViewSchedDAGs) DAG.viewGraph();
5170 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5174 RegisterScheduler::setDefault(Ctor);
5177 ScheduleDAG *SL = Ctor(this, &DAG, BB);
5180 if (ViewSUnitDAGs) SL->viewGraph();
5186 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5187 return new HazardRecognizer();
5190 //===----------------------------------------------------------------------===//
5191 // Helper functions used by the generated instruction selector.
5192 //===----------------------------------------------------------------------===//
5193 // Calls to these methods are generated by tblgen.
5195 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
5196 /// the dag combiner simplified the 255, we still want to match. RHS is the
5197 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5198 /// specified in the .td file (e.g. 255).
5199 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5200 int64_t DesiredMaskS) const {
5201 const APInt &ActualMask = RHS->getAPIntValue();
5202 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5204 // If the actual mask exactly matches, success!
5205 if (ActualMask == DesiredMask)
5208 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5209 if (ActualMask.intersects(~DesiredMask))
5212 // Otherwise, the DAG Combiner may have proven that the value coming in is
5213 // either already zero or is not demanded. Check for known zero input bits.
5214 APInt NeededMask = DesiredMask & ~ActualMask;
5215 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5218 // TODO: check to see if missing bits are just not demanded.
5220 // Otherwise, this pattern doesn't match.
5224 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
5225 /// the dag combiner simplified the 255, we still want to match. RHS is the
5226 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5227 /// specified in the .td file (e.g. 255).
5228 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5229 int64_t DesiredMaskS) const {
5230 const APInt &ActualMask = RHS->getAPIntValue();
5231 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5233 // If the actual mask exactly matches, success!
5234 if (ActualMask == DesiredMask)
5237 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5238 if (ActualMask.intersects(~DesiredMask))
5241 // Otherwise, the DAG Combiner may have proven that the value coming in is
5242 // either already zero or is not demanded. Check for known zero input bits.
5243 APInt NeededMask = DesiredMask & ~ActualMask;
5245 APInt KnownZero, KnownOne;
5246 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5248 // If all the missing bits in the or are already known to be set, match!
5249 if ((NeededMask & KnownOne) == NeededMask)
5252 // TODO: check to see if missing bits are just not demanded.
5254 // Otherwise, this pattern doesn't match.
5259 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5260 /// by tblgen. Others should not call it.
5261 void SelectionDAGISel::
5262 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5263 std::vector<SDOperand> InOps;
5264 std::swap(InOps, Ops);
5266 Ops.push_back(InOps[0]); // input chain.
5267 Ops.push_back(InOps[1]); // input asm string.
5269 unsigned i = 2, e = InOps.size();
5270 if (InOps[e-1].getValueType() == MVT::Flag)
5271 --e; // Don't process a flag operand if it is here.
5274 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5275 if ((Flags & 7) != 4 /*MEM*/) {
5276 // Just skip over this operand, copying the operands verbatim.
5277 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5278 i += (Flags >> 3) + 1;
5280 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5281 // Otherwise, this is a memory operand. Ask the target to select it.
5282 std::vector<SDOperand> SelOps;
5283 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5284 cerr << "Could not match memory address. Inline asm failure!\n";
5288 // Add this to the output node.
5289 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5290 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5292 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5297 // Add the flag input back if present.
5298 if (e != InOps.size())
5299 Ops.push_back(InOps.back());
5302 char SelectionDAGISel::ID = 0;