1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineDebugInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/SelectionDAG.h"
32 #include "llvm/CodeGen/SSARegMap.h"
33 #include "llvm/Target/MRegisterInfo.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetFrameInfo.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Debug.h"
51 ViewISelDAGs("view-isel-dags", cl::Hidden,
52 cl::desc("Pop up a window to show isel dags as they are selected"));
54 ViewSchedDAGs("view-sched-dags", cl::Hidden,
55 cl::desc("Pop up a window to show sched dags as they are processed"));
57 static const bool ViewISelDAGs = 0;
58 static const bool ViewSchedDAGs = 0;
61 // Scheduling heuristics
62 enum SchedHeuristics {
63 defaultScheduling, // Let the target specify its preference.
64 noScheduling, // No scheduling, emit breadth first sequence.
65 simpleScheduling, // Two pass, min. critical path, max. utilization.
66 simpleNoItinScheduling, // Same as above exact using generic latency.
67 listSchedulingBURR, // Bottom up reg reduction list scheduling.
68 listSchedulingTD // Top-down list scheduler.
72 cl::opt<SchedHeuristics>
75 cl::desc("Choose scheduling style"),
76 cl::init(defaultScheduling),
78 clEnumValN(defaultScheduling, "default",
79 "Target preferred scheduling style"),
80 clEnumValN(noScheduling, "none",
81 "No scheduling: breadth first sequencing"),
82 clEnumValN(simpleScheduling, "simple",
83 "Simple two pass scheduling: minimize critical path "
84 "and maximize processor utilization"),
85 clEnumValN(simpleNoItinScheduling, "simple-noitin",
86 "Simple two pass scheduling: Same as simple "
87 "except using generic latency"),
88 clEnumValN(listSchedulingBURR, "list-burr",
89 "Bottom up register reduction list scheduling"),
90 clEnumValN(listSchedulingTD, "list-td",
91 "Top-down list scheduler"),
96 /// RegsForValue - This struct represents the physical registers that a
97 /// particular value is assigned and the type information about the value.
98 /// This is needed because values can be promoted into larger registers and
99 /// expanded into multiple smaller registers than the value.
100 struct RegsForValue {
101 /// Regs - This list hold the register (for legal and promoted values)
102 /// or register set (for expanded values) that the value should be assigned
104 std::vector<unsigned> Regs;
106 /// RegVT - The value type of each register.
108 MVT::ValueType RegVT;
110 /// ValueVT - The value type of the LLVM value, which may be promoted from
111 /// RegVT or made from merging the two expanded parts.
112 MVT::ValueType ValueVT;
114 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
116 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
117 : RegVT(regvt), ValueVT(valuevt) {
120 RegsForValue(const std::vector<unsigned> ®s,
121 MVT::ValueType regvt, MVT::ValueType valuevt)
122 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
125 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
126 /// this value and returns the result as a ValueVT value. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 SDOperand getCopyFromRegs(SelectionDAG &DAG,
129 SDOperand &Chain, SDOperand &Flag) const;
131 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
132 /// specified value into the registers specified by this object. This uses
133 /// Chain/Flag as the input and updates them for the output Chain/Flag.
134 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
135 SDOperand &Chain, SDOperand &Flag) const;
137 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
138 /// operand list. This adds the code marker and includes the number of
139 /// values added into it.
140 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
141 std::vector<SDOperand> &Ops) const;
146 //===--------------------------------------------------------------------===//
147 /// FunctionLoweringInfo - This contains information that is global to a
148 /// function that is used when lowering a region of the function.
149 class FunctionLoweringInfo {
156 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
158 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
159 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
161 /// ValueMap - Since we emit code for the function a basic block at a time,
162 /// we must remember which virtual registers hold the values for
163 /// cross-basic-block values.
164 std::map<const Value*, unsigned> ValueMap;
166 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
167 /// the entry block. This allows the allocas to be efficiently referenced
168 /// anywhere in the function.
169 std::map<const AllocaInst*, int> StaticAllocaMap;
171 unsigned MakeReg(MVT::ValueType VT) {
172 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
175 unsigned CreateRegForValue(const Value *V);
177 unsigned InitializeRegForValue(const Value *V) {
178 unsigned &R = ValueMap[V];
179 assert(R == 0 && "Already initialized this value register!");
180 return R = CreateRegForValue(V);
185 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
186 /// PHI nodes or outside of the basic block that defines it, or used by a
187 /// switch instruction, which may expand to multiple basic blocks.
188 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
189 if (isa<PHINode>(I)) return true;
190 BasicBlock *BB = I->getParent();
191 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
192 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
193 isa<SwitchInst>(*UI))
198 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
199 /// entry block, return true. This includes arguments used by switches, since
200 /// the switch may expand into multiple basic blocks.
201 static bool isOnlyUsedInEntryBlock(Argument *A) {
202 BasicBlock *Entry = A->getParent()->begin();
203 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
204 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
205 return false; // Use not in entry block.
209 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
210 Function &fn, MachineFunction &mf)
211 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
213 // Create a vreg for each argument register that is not dead and is used
214 // outside of the entry block for the function.
215 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
217 if (!isOnlyUsedInEntryBlock(AI))
218 InitializeRegForValue(AI);
220 // Initialize the mapping of values to registers. This is only set up for
221 // instruction values that are used outside of the block that defines
223 Function::iterator BB = Fn.begin(), EB = Fn.end();
224 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
225 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
226 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
227 const Type *Ty = AI->getAllocatedType();
228 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
230 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
233 // If the alignment of the value is smaller than the size of the value,
234 // and if the size of the value is particularly small (<= 8 bytes),
235 // round up to the size of the value for potentially better performance.
237 // FIXME: This could be made better with a preferred alignment hook in
238 // TargetData. It serves primarily to 8-byte align doubles for X86.
239 if (Align < TySize && TySize <= 8) Align = TySize;
240 TySize *= CUI->getValue(); // Get total allocated size.
241 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
242 StaticAllocaMap[AI] =
243 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
246 for (; BB != EB; ++BB)
247 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
248 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
249 if (!isa<AllocaInst>(I) ||
250 !StaticAllocaMap.count(cast<AllocaInst>(I)))
251 InitializeRegForValue(I);
253 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
254 // also creates the initial PHI MachineInstrs, though none of the input
255 // operands are populated.
256 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
257 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
259 MF.getBasicBlockList().push_back(MBB);
261 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
264 for (BasicBlock::iterator I = BB->begin();
265 (PN = dyn_cast<PHINode>(I)); ++I)
266 if (!PN->use_empty()) {
267 MVT::ValueType VT = TLI.getValueType(PN->getType());
268 unsigned NumElements;
269 if (VT != MVT::Vector)
270 NumElements = TLI.getNumElements(VT);
272 MVT::ValueType VT1,VT2;
274 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
277 unsigned PHIReg = ValueMap[PN];
278 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
279 for (unsigned i = 0; i != NumElements; ++i)
280 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
285 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
286 /// the correctly promoted or expanded types. Assign these registers
287 /// consecutive vreg numbers and return the first assigned number.
288 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
289 MVT::ValueType VT = TLI.getValueType(V->getType());
291 // The number of multiples of registers that we need, to, e.g., split up
292 // a <2 x int64> -> 4 x i32 registers.
293 unsigned NumVectorRegs = 1;
295 // If this is a packed type, figure out what type it will decompose into
296 // and how many of the elements it will use.
297 if (VT == MVT::Vector) {
298 const PackedType *PTy = cast<PackedType>(V->getType());
299 unsigned NumElts = PTy->getNumElements();
300 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
302 // Divide the input until we get to a supported size. This will always
303 // end with a scalar if the target doesn't support vectors.
304 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
311 VT = getVectorType(EltTy, NumElts);
314 // The common case is that we will only create one register for this
315 // value. If we have that case, create and return the virtual register.
316 unsigned NV = TLI.getNumElements(VT);
318 // If we are promoting this value, pick the next largest supported type.
319 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
320 unsigned Reg = MakeReg(PromotedType);
321 // If this is a vector of supported or promoted types (e.g. 4 x i16),
322 // create all of the registers.
323 for (unsigned i = 1; i != NumVectorRegs; ++i)
324 MakeReg(PromotedType);
328 // If this value is represented with multiple target registers, make sure
329 // to create enough consecutive registers of the right (smaller) type.
330 unsigned NT = VT-1; // Find the type to use.
331 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
334 unsigned R = MakeReg((MVT::ValueType)NT);
335 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
336 MakeReg((MVT::ValueType)NT);
340 //===----------------------------------------------------------------------===//
341 /// SelectionDAGLowering - This is the common target-independent lowering
342 /// implementation that is parameterized by a TargetLowering object.
343 /// Also, targets can overload any lowering method.
346 class SelectionDAGLowering {
347 MachineBasicBlock *CurMBB;
349 std::map<const Value*, SDOperand> NodeMap;
351 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
352 /// them up and then emit token factor nodes when possible. This allows us to
353 /// get simple disambiguation between loads without worrying about alias
355 std::vector<SDOperand> PendingLoads;
357 /// Case - A pair of values to record the Value for a switch case, and the
358 /// case's target basic block.
359 typedef std::pair<Constant*, MachineBasicBlock*> Case;
360 typedef std::vector<Case>::iterator CaseItr;
361 typedef std::pair<CaseItr, CaseItr> CaseRange;
363 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
364 /// of conditional branches.
366 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
367 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
369 /// CaseBB - The MBB in which to emit the compare and branch
370 MachineBasicBlock *CaseBB;
371 /// LT, GE - If nonzero, we know the current case value must be less-than or
372 /// greater-than-or-equal-to these Constants.
375 /// Range - A pair of iterators representing the range of case values to be
376 /// processed at this point in the binary search tree.
380 /// The comparison function for sorting Case values.
382 bool operator () (const Case& C1, const Case& C2) {
383 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
384 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
386 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
387 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
392 // TLI - This is information that describes the available target features we
393 // need for lowering. This indicates when operations are unavailable,
394 // implemented with a libcall, etc.
397 const TargetData &TD;
399 /// SwitchCases - Vector of CaseBlock structures used to communicate
400 /// SwitchInst code generation information.
401 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
403 /// FuncInfo - Information about the function as a whole.
405 FunctionLoweringInfo &FuncInfo;
407 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
408 FunctionLoweringInfo &funcinfo)
409 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
413 /// getRoot - Return the current virtual root of the Selection DAG.
415 SDOperand getRoot() {
416 if (PendingLoads.empty())
417 return DAG.getRoot();
419 if (PendingLoads.size() == 1) {
420 SDOperand Root = PendingLoads[0];
422 PendingLoads.clear();
426 // Otherwise, we have to make a token factor node.
427 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
428 PendingLoads.clear();
433 void visit(Instruction &I) { visit(I.getOpcode(), I); }
435 void visit(unsigned Opcode, User &I) {
437 default: assert(0 && "Unknown instruction type encountered!");
439 // Build the switch statement using the Instruction.def file.
440 #define HANDLE_INST(NUM, OPCODE, CLASS) \
441 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
442 #include "llvm/Instruction.def"
446 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
448 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
449 SDOperand SrcValue, SDOperand Root,
452 SDOperand getIntPtrConstant(uint64_t Val) {
453 return DAG.getConstant(Val, TLI.getPointerTy());
456 SDOperand getValue(const Value *V);
458 const SDOperand &setValue(const Value *V, SDOperand NewN) {
459 SDOperand &N = NodeMap[V];
460 assert(N.Val == 0 && "Already set a value for this node!");
464 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
466 bool OutReg, bool InReg,
467 std::set<unsigned> &OutputRegs,
468 std::set<unsigned> &InputRegs);
470 // Terminator instructions.
471 void visitRet(ReturnInst &I);
472 void visitBr(BranchInst &I);
473 void visitSwitch(SwitchInst &I);
474 void visitUnreachable(UnreachableInst &I) { /* noop */ }
476 // Helper for visitSwitch
477 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
479 // These all get lowered before this pass.
480 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
481 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
483 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
484 void visitShift(User &I, unsigned Opcode);
485 void visitAdd(User &I) {
486 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
488 void visitSub(User &I);
489 void visitMul(User &I) {
490 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
492 void visitDiv(User &I) {
493 const Type *Ty = I.getType();
495 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
496 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
498 void visitRem(User &I) {
499 const Type *Ty = I.getType();
500 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
502 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
503 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
504 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
505 void visitShl(User &I) { visitShift(I, ISD::SHL); }
506 void visitShr(User &I) {
507 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
510 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
511 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
512 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
513 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
514 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
515 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
516 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
518 void visitExtractElement(User &I);
519 void visitInsertElement(User &I);
521 void visitGetElementPtr(User &I);
522 void visitCast(User &I);
523 void visitSelect(User &I);
525 void visitMalloc(MallocInst &I);
526 void visitFree(FreeInst &I);
527 void visitAlloca(AllocaInst &I);
528 void visitLoad(LoadInst &I);
529 void visitStore(StoreInst &I);
530 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
531 void visitCall(CallInst &I);
532 void visitInlineAsm(CallInst &I);
533 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
534 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
536 void visitVAStart(CallInst &I);
537 void visitVAArg(VAArgInst &I);
538 void visitVAEnd(CallInst &I);
539 void visitVACopy(CallInst &I);
540 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
542 void visitMemIntrinsic(CallInst &I, unsigned Op);
544 void visitUserOp1(Instruction &I) {
545 assert(0 && "UserOp1 should not exist at instruction selection time!");
548 void visitUserOp2(Instruction &I) {
549 assert(0 && "UserOp2 should not exist at instruction selection time!");
553 } // end namespace llvm
555 SDOperand SelectionDAGLowering::getValue(const Value *V) {
556 SDOperand &N = NodeMap[V];
559 const Type *VTy = V->getType();
560 MVT::ValueType VT = TLI.getValueType(VTy);
561 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
562 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
563 visit(CE->getOpcode(), *CE);
564 assert(N.Val && "visit didn't populate the ValueMap!");
566 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
567 return N = DAG.getGlobalAddress(GV, VT);
568 } else if (isa<ConstantPointerNull>(C)) {
569 return N = DAG.getConstant(0, TLI.getPointerTy());
570 } else if (isa<UndefValue>(C)) {
571 if (!isa<PackedType>(VTy))
572 return N = DAG.getNode(ISD::UNDEF, VT);
574 // Create a VBUILD_VECTOR of undef nodes.
575 const PackedType *PTy = cast<PackedType>(VTy);
576 unsigned NumElements = PTy->getNumElements();
577 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
579 std::vector<SDOperand> Ops;
580 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
582 // Create a VConstant node with generic Vector type.
583 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
584 Ops.push_back(DAG.getValueType(PVT));
585 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
586 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
587 return N = DAG.getConstantFP(CFP->getValue(), VT);
588 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
589 unsigned NumElements = PTy->getNumElements();
590 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
592 // Now that we know the number and type of the elements, push a
593 // Constant or ConstantFP node onto the ops list for each element of
594 // the packed constant.
595 std::vector<SDOperand> Ops;
596 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
597 for (unsigned i = 0; i != NumElements; ++i)
598 Ops.push_back(getValue(CP->getOperand(i)));
600 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
602 if (MVT::isFloatingPoint(PVT))
603 Op = DAG.getConstantFP(0, PVT);
605 Op = DAG.getConstant(0, PVT);
606 Ops.assign(NumElements, Op);
609 // Create a VBUILD_VECTOR node with generic Vector type.
610 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
611 Ops.push_back(DAG.getValueType(PVT));
612 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
614 // Canonicalize all constant ints to be unsigned.
615 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
619 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
620 std::map<const AllocaInst*, int>::iterator SI =
621 FuncInfo.StaticAllocaMap.find(AI);
622 if (SI != FuncInfo.StaticAllocaMap.end())
623 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
626 std::map<const Value*, unsigned>::const_iterator VMI =
627 FuncInfo.ValueMap.find(V);
628 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
630 unsigned InReg = VMI->second;
632 // If this type is not legal, make it so now.
633 if (VT != MVT::Vector) {
634 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
636 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
638 // Source must be expanded. This input value is actually coming from the
639 // register pair VMI->second and VMI->second+1.
640 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
641 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
642 } else if (DestVT > VT) { // Promotion case
643 if (MVT::isFloatingPoint(VT))
644 N = DAG.getNode(ISD::FP_ROUND, VT, N);
646 N = DAG.getNode(ISD::TRUNCATE, VT, N);
649 // Otherwise, if this is a vector, make it available as a generic vector
651 MVT::ValueType PTyElementVT, PTyLegalElementVT;
652 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(VTy),PTyElementVT,
655 // Build a VBUILD_VECTOR with the input registers.
656 std::vector<SDOperand> Ops;
657 if (PTyElementVT == PTyLegalElementVT) {
658 // If the value types are legal, just VBUILD the CopyFromReg nodes.
659 for (unsigned i = 0; i != NE; ++i)
660 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
662 } else if (PTyElementVT < PTyLegalElementVT) {
663 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
664 for (unsigned i = 0; i != NE; ++i) {
665 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
667 if (MVT::isFloatingPoint(PTyElementVT))
668 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
670 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
674 // If the register was expanded, use BUILD_PAIR.
675 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
676 for (unsigned i = 0; i != NE/2; ++i) {
677 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
679 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
681 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
685 Ops.push_back(DAG.getConstant(NE, MVT::i32));
686 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
687 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
694 void SelectionDAGLowering::visitRet(ReturnInst &I) {
695 if (I.getNumOperands() == 0) {
696 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
699 std::vector<SDOperand> NewValues;
700 NewValues.push_back(getRoot());
701 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
702 SDOperand RetOp = getValue(I.getOperand(i));
704 // If this is an integer return value, we need to promote it ourselves to
705 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
707 if (MVT::isInteger(RetOp.getValueType()) &&
708 RetOp.getValueType() < MVT::i64) {
709 MVT::ValueType TmpVT;
710 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
711 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
715 if (I.getOperand(i)->getType()->isSigned())
716 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
718 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
720 NewValues.push_back(RetOp);
722 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
725 void SelectionDAGLowering::visitBr(BranchInst &I) {
726 // Update machine-CFG edges.
727 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
728 CurMBB->addSuccessor(Succ0MBB);
730 // Figure out which block is immediately after the current one.
731 MachineBasicBlock *NextBlock = 0;
732 MachineFunction::iterator BBI = CurMBB;
733 if (++BBI != CurMBB->getParent()->end())
736 if (I.isUnconditional()) {
737 // If this is not a fall-through branch, emit the branch.
738 if (Succ0MBB != NextBlock)
739 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
740 DAG.getBasicBlock(Succ0MBB)));
742 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
743 CurMBB->addSuccessor(Succ1MBB);
745 SDOperand Cond = getValue(I.getCondition());
746 if (Succ1MBB == NextBlock) {
747 // If the condition is false, fall through. This means we should branch
748 // if the condition is true to Succ #0.
749 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
750 Cond, DAG.getBasicBlock(Succ0MBB)));
751 } else if (Succ0MBB == NextBlock) {
752 // If the condition is true, fall through. This means we should branch if
753 // the condition is false to Succ #1. Invert the condition first.
754 SDOperand True = DAG.getConstant(1, Cond.getValueType());
755 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
756 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
757 Cond, DAG.getBasicBlock(Succ1MBB)));
759 std::vector<SDOperand> Ops;
760 Ops.push_back(getRoot());
761 // If the false case is the current basic block, then this is a self
762 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
763 // adds an extra instruction in the loop. Instead, invert the
764 // condition and emit "Loop: ... br!cond Loop; br Out.
765 if (CurMBB == Succ1MBB) {
766 std::swap(Succ0MBB, Succ1MBB);
767 SDOperand True = DAG.getConstant(1, Cond.getValueType());
768 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
770 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
771 DAG.getBasicBlock(Succ0MBB));
772 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
773 DAG.getBasicBlock(Succ1MBB)));
778 /// visitSwitchCase - Emits the necessary code to represent a single node in
779 /// the binary search tree resulting from lowering a switch instruction.
780 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
781 SDOperand SwitchOp = getValue(CB.SwitchV);
782 SDOperand CaseOp = getValue(CB.CaseC);
783 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
785 // Set NextBlock to be the MBB immediately after the current one, if any.
786 // This is used to avoid emitting unnecessary branches to the next block.
787 MachineBasicBlock *NextBlock = 0;
788 MachineFunction::iterator BBI = CurMBB;
789 if (++BBI != CurMBB->getParent()->end())
792 // If the lhs block is the next block, invert the condition so that we can
793 // fall through to the lhs instead of the rhs block.
794 if (CB.LHSBB == NextBlock) {
795 std::swap(CB.LHSBB, CB.RHSBB);
796 SDOperand True = DAG.getConstant(1, Cond.getValueType());
797 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
799 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
800 DAG.getBasicBlock(CB.LHSBB));
801 if (CB.RHSBB == NextBlock)
804 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
805 DAG.getBasicBlock(CB.RHSBB)));
806 // Update successor info
807 CurMBB->addSuccessor(CB.LHSBB);
808 CurMBB->addSuccessor(CB.RHSBB);
811 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
812 // Figure out which block is immediately after the current one.
813 MachineBasicBlock *NextBlock = 0;
814 MachineFunction::iterator BBI = CurMBB;
815 if (++BBI != CurMBB->getParent()->end())
818 // If there is only the default destination, branch to it if it is not the
819 // next basic block. Otherwise, just fall through.
820 if (I.getNumOperands() == 2) {
821 // Update machine-CFG edges.
822 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
823 // If this is not a fall-through branch, emit the branch.
824 if (DefaultMBB != NextBlock)
825 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
826 DAG.getBasicBlock(DefaultMBB)));
830 // If there are any non-default case statements, create a vector of Cases
831 // representing each one, and sort the vector so that we can efficiently
832 // create a binary search tree from them.
833 std::vector<Case> Cases;
834 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
835 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
836 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
838 std::sort(Cases.begin(), Cases.end(), CaseCmp());
840 // Get the Value to be switched on and default basic blocks, which will be
841 // inserted into CaseBlock records, representing basic blocks in the binary
843 Value *SV = I.getOperand(0);
844 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
846 // Get the current MachineFunction and LLVM basic block, for use in creating
847 // and inserting new MBBs during the creation of the binary search tree.
848 MachineFunction *CurMF = CurMBB->getParent();
849 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
851 // Push the initial CaseRec onto the worklist
852 std::vector<CaseRec> CaseVec;
853 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
855 while (!CaseVec.empty()) {
856 // Grab a record representing a case range to process off the worklist
857 CaseRec CR = CaseVec.back();
860 // Size is the number of Cases represented by this range. If Size is 1,
861 // then we are processing a leaf of the binary search tree. Otherwise,
862 // we need to pick a pivot, and push left and right ranges onto the
864 unsigned Size = CR.Range.second - CR.Range.first;
867 // Create a CaseBlock record representing a conditional branch to
868 // the Case's target mbb if the value being switched on SV is equal
869 // to C. Otherwise, branch to default.
870 Constant *C = CR.Range.first->first;
871 MachineBasicBlock *Target = CR.Range.first->second;
872 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
874 // If the MBB representing the leaf node is the current MBB, then just
875 // call visitSwitchCase to emit the code into the current block.
876 // Otherwise, push the CaseBlock onto the vector to be later processed
877 // by SDISel, and insert the node's MBB before the next MBB.
878 if (CR.CaseBB == CurMBB)
881 SwitchCases.push_back(CB);
882 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
885 // split case range at pivot
886 CaseItr Pivot = CR.Range.first + (Size / 2);
887 CaseRange LHSR(CR.Range.first, Pivot);
888 CaseRange RHSR(Pivot, CR.Range.second);
889 Constant *C = Pivot->first;
890 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
891 // We know that we branch to the LHS if the Value being switched on is
892 // less than the Pivot value, C. We use this to optimize our binary
893 // tree a bit, by recognizing that if SV is greater than or equal to the
894 // LHS's Case Value, and that Case Value is exactly one less than the
895 // Pivot's Value, then we can branch directly to the LHS's Target,
896 // rather than creating a leaf node for it.
897 if ((LHSR.second - LHSR.first) == 1 &&
898 LHSR.first->first == CR.GE &&
899 cast<ConstantIntegral>(C)->getRawValue() ==
900 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
901 LHSBB = LHSR.first->second;
903 LHSBB = new MachineBasicBlock(LLVMBB);
904 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
906 // Similar to the optimization above, if the Value being switched on is
907 // known to be less than the Constant CR.LT, and the current Case Value
908 // is CR.LT - 1, then we can branch directly to the target block for
909 // the current Case Value, rather than emitting a RHS leaf node for it.
910 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
911 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
912 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
913 RHSBB = RHSR.first->second;
915 RHSBB = new MachineBasicBlock(LLVMBB);
916 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
918 // Create a CaseBlock record representing a conditional branch to
919 // the LHS node if the value being switched on SV is less than C.
920 // Otherwise, branch to LHS.
921 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
922 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
923 if (CR.CaseBB == CurMBB)
926 SwitchCases.push_back(CB);
927 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
933 void SelectionDAGLowering::visitSub(User &I) {
935 if (I.getType()->isFloatingPoint()) {
936 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
937 if (CFP->isExactlyValue(-0.0)) {
938 SDOperand Op2 = getValue(I.getOperand(1));
939 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
943 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
946 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
948 const Type *Ty = I.getType();
949 SDOperand Op1 = getValue(I.getOperand(0));
950 SDOperand Op2 = getValue(I.getOperand(1));
952 if (Ty->isIntegral()) {
953 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
954 } else if (Ty->isFloatingPoint()) {
955 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
957 const PackedType *PTy = cast<PackedType>(Ty);
958 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
959 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
960 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
964 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
965 SDOperand Op1 = getValue(I.getOperand(0));
966 SDOperand Op2 = getValue(I.getOperand(1));
968 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
970 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
973 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
974 ISD::CondCode UnsignedOpcode) {
975 SDOperand Op1 = getValue(I.getOperand(0));
976 SDOperand Op2 = getValue(I.getOperand(1));
977 ISD::CondCode Opcode = SignedOpcode;
978 if (I.getOperand(0)->getType()->isUnsigned())
979 Opcode = UnsignedOpcode;
980 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
983 void SelectionDAGLowering::visitSelect(User &I) {
984 SDOperand Cond = getValue(I.getOperand(0));
985 SDOperand TrueVal = getValue(I.getOperand(1));
986 SDOperand FalseVal = getValue(I.getOperand(2));
987 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
991 void SelectionDAGLowering::visitCast(User &I) {
992 SDOperand N = getValue(I.getOperand(0));
993 MVT::ValueType SrcVT = N.getValueType();
994 MVT::ValueType DestVT = TLI.getValueType(I.getType());
996 if (DestVT == MVT::Vector) {
997 // This is a cast to a vector from something else. This is always a bit
998 // convert. Get information about the input vector.
999 const PackedType *DestTy = cast<PackedType>(I.getType());
1000 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1001 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1002 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1003 DAG.getValueType(EltVT)));
1004 } else if (SrcVT == DestVT) {
1005 setValue(&I, N); // noop cast.
1006 } else if (DestVT == MVT::i1) {
1007 // Cast to bool is a comparison against zero, not truncation to zero.
1008 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1009 DAG.getConstantFP(0.0, N.getValueType());
1010 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1011 } else if (isInteger(SrcVT)) {
1012 if (isInteger(DestVT)) { // Int -> Int cast
1013 if (DestVT < SrcVT) // Truncating cast?
1014 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1015 else if (I.getOperand(0)->getType()->isSigned())
1016 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1018 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1019 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
1020 if (I.getOperand(0)->getType()->isSigned())
1021 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1023 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1025 assert(0 && "Unknown cast!");
1027 } else if (isFloatingPoint(SrcVT)) {
1028 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1029 if (DestVT < SrcVT) // Rounding cast?
1030 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1032 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1033 } else if (isInteger(DestVT)) { // FP -> Int cast.
1034 if (I.getType()->isSigned())
1035 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1037 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1039 assert(0 && "Unknown cast!");
1042 assert(SrcVT == MVT::Vector && "Unknown cast!");
1043 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1044 // This is a cast from a vector to something else. This is always a bit
1045 // convert. Get information about the input vector.
1046 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1050 void SelectionDAGLowering::visitInsertElement(User &I) {
1051 SDOperand InVec = getValue(I.getOperand(0));
1052 SDOperand InVal = getValue(I.getOperand(1));
1053 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1054 getValue(I.getOperand(2)));
1056 SDOperand Num = *(InVec.Val->op_end()-2);
1057 SDOperand Typ = *(InVec.Val->op_end()-1);
1058 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1059 InVec, InVal, InIdx, Num, Typ));
1062 void SelectionDAGLowering::visitExtractElement(User &I) {
1063 SDOperand InVec = getValue(I.getOperand(0));
1064 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1065 getValue(I.getOperand(1)));
1066 SDOperand Typ = *(InVec.Val->op_end()-1);
1067 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1068 TLI.getValueType(I.getType()), InVec, InIdx));
1071 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1072 SDOperand N = getValue(I.getOperand(0));
1073 const Type *Ty = I.getOperand(0)->getType();
1074 const Type *UIntPtrTy = TD.getIntPtrType();
1076 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1079 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1080 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1083 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
1084 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1085 getIntPtrConstant(Offset));
1087 Ty = StTy->getElementType(Field);
1089 Ty = cast<SequentialType>(Ty)->getElementType();
1091 // If this is a constant subscript, handle it quickly.
1092 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1093 if (CI->getRawValue() == 0) continue;
1096 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1097 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1099 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1100 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1104 // N = N + Idx * ElementSize;
1105 uint64_t ElementSize = TD.getTypeSize(Ty);
1106 SDOperand IdxN = getValue(Idx);
1108 // If the index is smaller or larger than intptr_t, truncate or extend
1110 if (IdxN.getValueType() < N.getValueType()) {
1111 if (Idx->getType()->isSigned())
1112 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1114 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1115 } else if (IdxN.getValueType() > N.getValueType())
1116 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1118 // If this is a multiply by a power of two, turn it into a shl
1119 // immediately. This is a very common case.
1120 if (isPowerOf2_64(ElementSize)) {
1121 unsigned Amt = Log2_64(ElementSize);
1122 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1123 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1124 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1128 SDOperand Scale = getIntPtrConstant(ElementSize);
1129 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1130 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1136 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1137 // If this is a fixed sized alloca in the entry block of the function,
1138 // allocate it statically on the stack.
1139 if (FuncInfo.StaticAllocaMap.count(&I))
1140 return; // getValue will auto-populate this.
1142 const Type *Ty = I.getAllocatedType();
1143 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1144 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
1147 SDOperand AllocSize = getValue(I.getArraySize());
1148 MVT::ValueType IntPtr = TLI.getPointerTy();
1149 if (IntPtr < AllocSize.getValueType())
1150 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1151 else if (IntPtr > AllocSize.getValueType())
1152 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1154 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1155 getIntPtrConstant(TySize));
1157 // Handle alignment. If the requested alignment is less than or equal to the
1158 // stack alignment, ignore it and round the size of the allocation up to the
1159 // stack alignment size. If the size is greater than the stack alignment, we
1160 // note this in the DYNAMIC_STACKALLOC node.
1161 unsigned StackAlign =
1162 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1163 if (Align <= StackAlign) {
1165 // Add SA-1 to the size.
1166 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1167 getIntPtrConstant(StackAlign-1));
1168 // Mask out the low bits for alignment purposes.
1169 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1170 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1173 std::vector<MVT::ValueType> VTs;
1174 VTs.push_back(AllocSize.getValueType());
1175 VTs.push_back(MVT::Other);
1176 std::vector<SDOperand> Ops;
1177 Ops.push_back(getRoot());
1178 Ops.push_back(AllocSize);
1179 Ops.push_back(getIntPtrConstant(Align));
1180 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
1181 DAG.setRoot(setValue(&I, DSA).getValue(1));
1183 // Inform the Frame Information that we have just allocated a variable-sized
1185 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1188 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1189 SDOperand Ptr = getValue(I.getOperand(0));
1195 // Do not serialize non-volatile loads against each other.
1196 Root = DAG.getRoot();
1199 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1200 Root, I.isVolatile()));
1203 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1204 SDOperand SrcValue, SDOperand Root,
1207 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1208 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1209 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
1211 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
1215 DAG.setRoot(L.getValue(1));
1217 PendingLoads.push_back(L.getValue(1));
1223 void SelectionDAGLowering::visitStore(StoreInst &I) {
1224 Value *SrcV = I.getOperand(0);
1225 SDOperand Src = getValue(SrcV);
1226 SDOperand Ptr = getValue(I.getOperand(1));
1227 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1228 DAG.getSrcValue(I.getOperand(1))));
1231 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1232 /// access memory and has no other side effects at all.
1233 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1234 #define GET_NO_MEMORY_INTRINSICS
1235 #include "llvm/Intrinsics.gen"
1236 #undef GET_NO_MEMORY_INTRINSICS
1240 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1242 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1243 unsigned Intrinsic) {
1244 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1246 // Build the operand list.
1247 std::vector<SDOperand> Ops;
1248 if (HasChain) // If this intrinsic has side-effects, chainify it.
1249 Ops.push_back(getRoot());
1251 // Add the intrinsic ID as an integer operand.
1252 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1254 // Add all operands of the call to the operand list.
1255 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1256 SDOperand Op = getValue(I.getOperand(i));
1258 // If this is a vector type, force it to the right packed type.
1259 if (Op.getValueType() == MVT::Vector) {
1260 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1261 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1263 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1264 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1265 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1268 assert(TLI.isTypeLegal(Op.getValueType()) &&
1269 "Intrinsic uses a non-legal type?");
1273 std::vector<MVT::ValueType> VTs;
1274 if (I.getType() != Type::VoidTy) {
1275 MVT::ValueType VT = TLI.getValueType(I.getType());
1276 if (VT == MVT::Vector) {
1277 const PackedType *DestTy = cast<PackedType>(I.getType());
1278 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1280 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1281 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1284 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1288 VTs.push_back(MVT::Other);
1293 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1294 else if (I.getType() != Type::VoidTy)
1295 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1297 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1300 DAG.setRoot(Result.getValue(Result.Val->getNumValues()-1));
1301 if (I.getType() != Type::VoidTy) {
1302 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1303 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1304 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1305 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1306 DAG.getValueType(EVT));
1308 setValue(&I, Result);
1312 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1313 /// we want to emit this as a call to a named external function, return the name
1314 /// otherwise lower it and return null.
1316 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1317 switch (Intrinsic) {
1319 // By default, turn this into a target intrinsic node.
1320 visitTargetIntrinsic(I, Intrinsic);
1322 case Intrinsic::vastart: visitVAStart(I); return 0;
1323 case Intrinsic::vaend: visitVAEnd(I); return 0;
1324 case Intrinsic::vacopy: visitVACopy(I); return 0;
1325 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1326 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1327 case Intrinsic::setjmp:
1328 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1330 case Intrinsic::longjmp:
1331 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1333 case Intrinsic::memcpy_i32:
1334 case Intrinsic::memcpy_i64:
1335 visitMemIntrinsic(I, ISD::MEMCPY);
1337 case Intrinsic::memset_i32:
1338 case Intrinsic::memset_i64:
1339 visitMemIntrinsic(I, ISD::MEMSET);
1341 case Intrinsic::memmove_i32:
1342 case Intrinsic::memmove_i64:
1343 visitMemIntrinsic(I, ISD::MEMMOVE);
1346 case Intrinsic::dbg_stoppoint: {
1347 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1348 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1349 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1350 std::vector<SDOperand> Ops;
1352 Ops.push_back(getRoot());
1353 Ops.push_back(getValue(SPI.getLineValue()));
1354 Ops.push_back(getValue(SPI.getColumnValue()));
1356 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1357 assert(DD && "Not a debug information descriptor");
1358 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1360 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1361 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1363 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1368 case Intrinsic::dbg_region_start: {
1369 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1370 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1371 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1372 std::vector<SDOperand> Ops;
1374 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1376 Ops.push_back(getRoot());
1377 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1379 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1384 case Intrinsic::dbg_region_end: {
1385 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1386 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1387 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1388 std::vector<SDOperand> Ops;
1390 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1392 Ops.push_back(getRoot());
1393 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1395 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1400 case Intrinsic::dbg_func_start: {
1401 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1402 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1403 if (DebugInfo && FSI.getSubprogram() &&
1404 DebugInfo->Verify(FSI.getSubprogram())) {
1405 std::vector<SDOperand> Ops;
1407 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1409 Ops.push_back(getRoot());
1410 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1412 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1417 case Intrinsic::dbg_declare: {
1418 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1419 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1420 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1421 std::vector<SDOperand> Ops;
1423 SDOperand AddressOp = getValue(DI.getAddress());
1424 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
1425 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1432 case Intrinsic::isunordered_f32:
1433 case Intrinsic::isunordered_f64:
1434 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1435 getValue(I.getOperand(2)), ISD::SETUO));
1438 case Intrinsic::sqrt_f32:
1439 case Intrinsic::sqrt_f64:
1440 setValue(&I, DAG.getNode(ISD::FSQRT,
1441 getValue(I.getOperand(1)).getValueType(),
1442 getValue(I.getOperand(1))));
1444 case Intrinsic::pcmarker: {
1445 SDOperand Tmp = getValue(I.getOperand(1));
1446 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1449 case Intrinsic::readcyclecounter: {
1450 std::vector<MVT::ValueType> VTs;
1451 VTs.push_back(MVT::i64);
1452 VTs.push_back(MVT::Other);
1453 std::vector<SDOperand> Ops;
1454 Ops.push_back(getRoot());
1455 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1457 DAG.setRoot(Tmp.getValue(1));
1460 case Intrinsic::bswap_i16:
1461 case Intrinsic::bswap_i32:
1462 case Intrinsic::bswap_i64:
1463 setValue(&I, DAG.getNode(ISD::BSWAP,
1464 getValue(I.getOperand(1)).getValueType(),
1465 getValue(I.getOperand(1))));
1467 case Intrinsic::cttz_i8:
1468 case Intrinsic::cttz_i16:
1469 case Intrinsic::cttz_i32:
1470 case Intrinsic::cttz_i64:
1471 setValue(&I, DAG.getNode(ISD::CTTZ,
1472 getValue(I.getOperand(1)).getValueType(),
1473 getValue(I.getOperand(1))));
1475 case Intrinsic::ctlz_i8:
1476 case Intrinsic::ctlz_i16:
1477 case Intrinsic::ctlz_i32:
1478 case Intrinsic::ctlz_i64:
1479 setValue(&I, DAG.getNode(ISD::CTLZ,
1480 getValue(I.getOperand(1)).getValueType(),
1481 getValue(I.getOperand(1))));
1483 case Intrinsic::ctpop_i8:
1484 case Intrinsic::ctpop_i16:
1485 case Intrinsic::ctpop_i32:
1486 case Intrinsic::ctpop_i64:
1487 setValue(&I, DAG.getNode(ISD::CTPOP,
1488 getValue(I.getOperand(1)).getValueType(),
1489 getValue(I.getOperand(1))));
1491 case Intrinsic::stacksave: {
1492 std::vector<MVT::ValueType> VTs;
1493 VTs.push_back(TLI.getPointerTy());
1494 VTs.push_back(MVT::Other);
1495 std::vector<SDOperand> Ops;
1496 Ops.push_back(getRoot());
1497 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1499 DAG.setRoot(Tmp.getValue(1));
1502 case Intrinsic::stackrestore: {
1503 SDOperand Tmp = getValue(I.getOperand(1));
1504 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1507 case Intrinsic::prefetch:
1508 // FIXME: Currently discarding prefetches.
1514 void SelectionDAGLowering::visitCall(CallInst &I) {
1515 const char *RenameFn = 0;
1516 if (Function *F = I.getCalledFunction()) {
1517 if (F->isExternal())
1518 if (unsigned IID = F->getIntrinsicID()) {
1519 RenameFn = visitIntrinsicCall(I, IID);
1522 } else { // Not an LLVM intrinsic.
1523 const std::string &Name = F->getName();
1524 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1525 if (I.getNumOperands() == 3 && // Basic sanity checks.
1526 I.getOperand(1)->getType()->isFloatingPoint() &&
1527 I.getType() == I.getOperand(1)->getType() &&
1528 I.getType() == I.getOperand(2)->getType()) {
1529 SDOperand LHS = getValue(I.getOperand(1));
1530 SDOperand RHS = getValue(I.getOperand(2));
1531 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1535 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1536 if (I.getNumOperands() == 2 && // Basic sanity checks.
1537 I.getOperand(1)->getType()->isFloatingPoint() &&
1538 I.getType() == I.getOperand(1)->getType()) {
1539 SDOperand Tmp = getValue(I.getOperand(1));
1540 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1543 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1544 if (I.getNumOperands() == 2 && // Basic sanity checks.
1545 I.getOperand(1)->getType()->isFloatingPoint() &&
1546 I.getType() == I.getOperand(1)->getType()) {
1547 SDOperand Tmp = getValue(I.getOperand(1));
1548 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1551 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1552 if (I.getNumOperands() == 2 && // Basic sanity checks.
1553 I.getOperand(1)->getType()->isFloatingPoint() &&
1554 I.getType() == I.getOperand(1)->getType()) {
1555 SDOperand Tmp = getValue(I.getOperand(1));
1556 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1561 } else if (isa<InlineAsm>(I.getOperand(0))) {
1568 Callee = getValue(I.getOperand(0));
1570 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1571 std::vector<std::pair<SDOperand, const Type*> > Args;
1572 Args.reserve(I.getNumOperands());
1573 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1574 Value *Arg = I.getOperand(i);
1575 SDOperand ArgNode = getValue(Arg);
1576 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1579 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1580 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1582 std::pair<SDOperand,SDOperand> Result =
1583 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1584 I.isTailCall(), Callee, Args, DAG);
1585 if (I.getType() != Type::VoidTy)
1586 setValue(&I, Result.first);
1587 DAG.setRoot(Result.second);
1590 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1591 SDOperand &Chain, SDOperand &Flag)const{
1592 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1593 Chain = Val.getValue(1);
1594 Flag = Val.getValue(2);
1596 // If the result was expanded, copy from the top part.
1597 if (Regs.size() > 1) {
1598 assert(Regs.size() == 2 &&
1599 "Cannot expand to more than 2 elts yet!");
1600 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1601 Chain = Val.getValue(1);
1602 Flag = Val.getValue(2);
1603 if (DAG.getTargetLoweringInfo().isLittleEndian())
1604 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1606 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
1609 // Otherwise, if the return value was promoted, truncate it to the
1610 // appropriate type.
1611 if (RegVT == ValueVT)
1614 if (MVT::isInteger(RegVT))
1615 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1617 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1620 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1621 /// specified value into the registers specified by this object. This uses
1622 /// Chain/Flag as the input and updates them for the output Chain/Flag.
1623 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1624 SDOperand &Chain, SDOperand &Flag) const {
1625 if (Regs.size() == 1) {
1626 // If there is a single register and the types differ, this must be
1628 if (RegVT != ValueVT) {
1629 if (MVT::isInteger(RegVT))
1630 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1632 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1634 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1635 Flag = Chain.getValue(1);
1637 std::vector<unsigned> R(Regs);
1638 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1639 std::reverse(R.begin(), R.end());
1641 for (unsigned i = 0, e = R.size(); i != e; ++i) {
1642 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1643 DAG.getConstant(i, MVT::i32));
1644 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
1645 Flag = Chain.getValue(1);
1650 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
1651 /// operand list. This adds the code marker and includes the number of
1652 /// values added into it.
1653 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1654 std::vector<SDOperand> &Ops) const {
1655 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1656 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1657 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1660 /// isAllocatableRegister - If the specified register is safe to allocate,
1661 /// i.e. it isn't a stack pointer or some other special register, return the
1662 /// register class for the register. Otherwise, return null.
1663 static const TargetRegisterClass *
1664 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1665 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1666 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1667 E = MRI->regclass_end(); RCI != E; ++RCI) {
1668 const TargetRegisterClass *RC = *RCI;
1669 // If none of the the value types for this register class are valid, we
1670 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1671 bool isLegal = false;
1672 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1674 if (TLI.isTypeLegal(*I)) {
1680 if (!isLegal) continue;
1682 // NOTE: This isn't ideal. In particular, this might allocate the
1683 // frame pointer in functions that need it (due to them not being taken
1684 // out of allocation, because a variable sized allocation hasn't been seen
1685 // yet). This is a slight code pessimization, but should still work.
1686 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1687 E = RC->allocation_order_end(MF); I != E; ++I)
1694 RegsForValue SelectionDAGLowering::
1695 GetRegistersForValue(const std::string &ConstrCode,
1696 MVT::ValueType VT, bool isOutReg, bool isInReg,
1697 std::set<unsigned> &OutputRegs,
1698 std::set<unsigned> &InputRegs) {
1699 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1700 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1701 std::vector<unsigned> Regs;
1703 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1704 MVT::ValueType RegVT;
1705 MVT::ValueType ValueVT = VT;
1707 if (PhysReg.first) {
1708 if (VT == MVT::Other)
1709 ValueVT = *PhysReg.second->vt_begin();
1712 // This is a explicit reference to a physical register.
1713 Regs.push_back(PhysReg.first);
1715 // If this is an expanded reference, add the rest of the regs to Regs.
1717 RegVT = *PhysReg.second->vt_begin();
1718 TargetRegisterClass::iterator I = PhysReg.second->begin();
1719 TargetRegisterClass::iterator E = PhysReg.second->end();
1720 for (; *I != PhysReg.first; ++I)
1721 assert(I != E && "Didn't find reg!");
1723 // Already added the first reg.
1725 for (; NumRegs; --NumRegs, ++I) {
1726 assert(I != E && "Ran out of registers to allocate!");
1730 return RegsForValue(Regs, RegVT, ValueVT);
1733 // This is a reference to a register class. Allocate NumRegs consecutive,
1734 // available, registers from the class.
1735 std::vector<unsigned> RegClassRegs =
1736 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1738 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1739 MachineFunction &MF = *CurMBB->getParent();
1740 unsigned NumAllocated = 0;
1741 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1742 unsigned Reg = RegClassRegs[i];
1743 // See if this register is available.
1744 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1745 (isInReg && InputRegs.count(Reg))) { // Already used.
1746 // Make sure we find consecutive registers.
1751 // Check to see if this register is allocatable (i.e. don't give out the
1753 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1755 // Make sure we find consecutive registers.
1760 // Okay, this register is good, we can use it.
1763 // If we allocated enough consecutive
1764 if (NumAllocated == NumRegs) {
1765 unsigned RegStart = (i-NumAllocated)+1;
1766 unsigned RegEnd = i+1;
1767 // Mark all of the allocated registers used.
1768 for (unsigned i = RegStart; i != RegEnd; ++i) {
1769 unsigned Reg = RegClassRegs[i];
1770 Regs.push_back(Reg);
1771 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1772 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1775 return RegsForValue(Regs, *RC->vt_begin(), VT);
1779 // Otherwise, we couldn't allocate enough registers for this.
1780 return RegsForValue();
1784 /// visitInlineAsm - Handle a call to an InlineAsm object.
1786 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1787 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1789 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1792 // Note, we treat inline asms both with and without side-effects as the same.
1793 // If an inline asm doesn't have side effects and doesn't access memory, we
1794 // could not choose to not chain it.
1795 bool hasSideEffects = IA->hasSideEffects();
1797 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1798 std::vector<MVT::ValueType> ConstraintVTs;
1800 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1801 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1802 /// if it is a def of that register.
1803 std::vector<SDOperand> AsmNodeOperands;
1804 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1805 AsmNodeOperands.push_back(AsmStr);
1807 SDOperand Chain = getRoot();
1810 // We fully assign registers here at isel time. This is not optimal, but
1811 // should work. For register classes that correspond to LLVM classes, we
1812 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1813 // over the constraints, collecting fixed registers that we know we can't use.
1814 std::set<unsigned> OutputRegs, InputRegs;
1816 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1817 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1818 std::string &ConstraintCode = Constraints[i].Codes[0];
1820 MVT::ValueType OpVT;
1822 // Compute the value type for each operand and add it to ConstraintVTs.
1823 switch (Constraints[i].Type) {
1824 case InlineAsm::isOutput:
1825 if (!Constraints[i].isIndirectOutput) {
1826 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1827 OpVT = TLI.getValueType(I.getType());
1829 const Type *OpTy = I.getOperand(OpNum)->getType();
1830 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1831 OpNum++; // Consumes a call operand.
1834 case InlineAsm::isInput:
1835 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1836 OpNum++; // Consumes a call operand.
1838 case InlineAsm::isClobber:
1843 ConstraintVTs.push_back(OpVT);
1845 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1846 continue; // Not assigned a fixed reg.
1848 // Build a list of regs that this operand uses. This always has a single
1849 // element for promoted/expanded operands.
1850 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1852 OutputRegs, InputRegs);
1854 switch (Constraints[i].Type) {
1855 case InlineAsm::isOutput:
1856 // We can't assign any other output to this register.
1857 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1858 // If this is an early-clobber output, it cannot be assigned to the same
1859 // value as the input reg.
1860 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1861 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1863 case InlineAsm::isInput:
1864 // We can't assign any other input to this register.
1865 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1867 case InlineAsm::isClobber:
1868 // Clobbered regs cannot be used as inputs or outputs.
1869 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1870 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1875 // Loop over all of the inputs, copying the operand values into the
1876 // appropriate registers and processing the output regs.
1877 RegsForValue RetValRegs;
1878 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
1881 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1882 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1883 std::string &ConstraintCode = Constraints[i].Codes[0];
1885 switch (Constraints[i].Type) {
1886 case InlineAsm::isOutput: {
1887 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1888 if (ConstraintCode.size() == 1) // not a physreg name.
1889 CTy = TLI.getConstraintType(ConstraintCode[0]);
1891 if (CTy == TargetLowering::C_Memory) {
1893 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1895 // Check that the operand (the address to store to) isn't a float.
1896 if (!MVT::isInteger(InOperandVal.getValueType()))
1897 assert(0 && "MATCH FAIL!");
1899 if (!Constraints[i].isIndirectOutput)
1900 assert(0 && "MATCH FAIL!");
1902 OpNum++; // Consumes a call operand.
1904 // Extend/truncate to the right pointer type if needed.
1905 MVT::ValueType PtrType = TLI.getPointerTy();
1906 if (InOperandVal.getValueType() < PtrType)
1907 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1908 else if (InOperandVal.getValueType() > PtrType)
1909 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1911 // Add information to the INLINEASM node to know about this output.
1912 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1913 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1914 AsmNodeOperands.push_back(InOperandVal);
1918 // Otherwise, this is a register output.
1919 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1921 // If this is an early-clobber output, or if there is an input
1922 // constraint that matches this, we need to reserve the input register
1923 // so no other inputs allocate to it.
1924 bool UsesInputRegister = false;
1925 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1926 UsesInputRegister = true;
1928 // Copy the output from the appropriate register. Find a register that
1931 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1932 true, UsesInputRegister,
1933 OutputRegs, InputRegs);
1934 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
1936 if (!Constraints[i].isIndirectOutput) {
1937 assert(RetValRegs.Regs.empty() &&
1938 "Cannot have multiple output constraints yet!");
1939 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1942 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1943 I.getOperand(OpNum)));
1944 OpNum++; // Consumes a call operand.
1947 // Add information to the INLINEASM node to know that this register is
1949 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
1952 case InlineAsm::isInput: {
1953 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1954 OpNum++; // Consumes a call operand.
1956 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1957 // If this is required to match an output register we have already set,
1958 // just use its register.
1959 unsigned OperandNo = atoi(ConstraintCode.c_str());
1961 // Scan until we find the definition we already emitted of this operand.
1962 // When we find it, create a RegsForValue operand.
1963 unsigned CurOp = 2; // The first operand.
1964 for (; OperandNo; --OperandNo) {
1965 // Advance to the next operand.
1967 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1968 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1969 "Skipped past definitions?");
1970 CurOp += (NumOps>>3)+1;
1974 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1975 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1976 "Skipped past definitions?");
1978 // Add NumOps>>3 registers to MatchedRegs.
1979 RegsForValue MatchedRegs;
1980 MatchedRegs.ValueVT = InOperandVal.getValueType();
1981 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1982 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1983 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1984 MatchedRegs.Regs.push_back(Reg);
1987 // Use the produced MatchedRegs object to
1988 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1989 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
1993 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1994 if (ConstraintCode.size() == 1) // not a physreg name.
1995 CTy = TLI.getConstraintType(ConstraintCode[0]);
1997 if (CTy == TargetLowering::C_Other) {
1998 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1999 assert(0 && "MATCH FAIL!");
2001 // Add information to the INLINEASM node to know about this input.
2002 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2003 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2004 AsmNodeOperands.push_back(InOperandVal);
2006 } else if (CTy == TargetLowering::C_Memory) {
2009 // Check that the operand isn't a float.
2010 if (!MVT::isInteger(InOperandVal.getValueType()))
2011 assert(0 && "MATCH FAIL!");
2013 // Extend/truncate to the right pointer type if needed.
2014 MVT::ValueType PtrType = TLI.getPointerTy();
2015 if (InOperandVal.getValueType() < PtrType)
2016 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2017 else if (InOperandVal.getValueType() > PtrType)
2018 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2020 // Add information to the INLINEASM node to know about this input.
2021 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2022 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2023 AsmNodeOperands.push_back(InOperandVal);
2027 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2029 // Copy the input into the appropriate registers.
2030 RegsForValue InRegs =
2031 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2032 false, true, OutputRegs, InputRegs);
2033 // FIXME: should be match fail.
2034 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2036 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2038 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2041 case InlineAsm::isClobber: {
2042 RegsForValue ClobberedRegs =
2043 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2044 OutputRegs, InputRegs);
2045 // Add the clobbered value to the operand list, so that the register
2046 // allocator is aware that the physreg got clobbered.
2047 if (!ClobberedRegs.Regs.empty())
2048 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2054 // Finish up input operands.
2055 AsmNodeOperands[0] = Chain;
2056 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2058 std::vector<MVT::ValueType> VTs;
2059 VTs.push_back(MVT::Other);
2060 VTs.push_back(MVT::Flag);
2061 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2062 Flag = Chain.getValue(1);
2064 // If this asm returns a register value, copy the result from that register
2065 // and set it as the value of the call.
2066 if (!RetValRegs.Regs.empty())
2067 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2069 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2071 // Process indirect outputs, first output all of the flagged copies out of
2073 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2074 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2075 Value *Ptr = IndirectStoresToEmit[i].second;
2076 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2077 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2080 // Emit the non-flagged stores from the physregs.
2081 std::vector<SDOperand> OutChains;
2082 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2083 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2084 StoresToEmit[i].first,
2085 getValue(StoresToEmit[i].second),
2086 DAG.getSrcValue(StoresToEmit[i].second)));
2087 if (!OutChains.empty())
2088 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2093 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2094 SDOperand Src = getValue(I.getOperand(0));
2096 MVT::ValueType IntPtr = TLI.getPointerTy();
2098 if (IntPtr < Src.getValueType())
2099 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2100 else if (IntPtr > Src.getValueType())
2101 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2103 // Scale the source by the type size.
2104 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
2105 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2106 Src, getIntPtrConstant(ElementSize));
2108 std::vector<std::pair<SDOperand, const Type*> > Args;
2109 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
2111 std::pair<SDOperand,SDOperand> Result =
2112 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2113 DAG.getExternalSymbol("malloc", IntPtr),
2115 setValue(&I, Result.first); // Pointers always fit in registers
2116 DAG.setRoot(Result.second);
2119 void SelectionDAGLowering::visitFree(FreeInst &I) {
2120 std::vector<std::pair<SDOperand, const Type*> > Args;
2121 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2122 TLI.getTargetData().getIntPtrType()));
2123 MVT::ValueType IntPtr = TLI.getPointerTy();
2124 std::pair<SDOperand,SDOperand> Result =
2125 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2126 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2127 DAG.setRoot(Result.second);
2130 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2131 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2132 // instructions are special in various ways, which require special support to
2133 // insert. The specified MachineInstr is created but not inserted into any
2134 // basic blocks, and the scheduler passes ownership of it to this method.
2135 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2136 MachineBasicBlock *MBB) {
2137 std::cerr << "If a target marks an instruction with "
2138 "'usesCustomDAGSchedInserter', it must implement "
2139 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2144 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2145 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2146 getValue(I.getOperand(1)),
2147 DAG.getSrcValue(I.getOperand(1))));
2150 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2151 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2152 getValue(I.getOperand(0)),
2153 DAG.getSrcValue(I.getOperand(0)));
2155 DAG.setRoot(V.getValue(1));
2158 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2159 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2160 getValue(I.getOperand(1)),
2161 DAG.getSrcValue(I.getOperand(1))));
2164 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2165 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2166 getValue(I.getOperand(1)),
2167 getValue(I.getOperand(2)),
2168 DAG.getSrcValue(I.getOperand(1)),
2169 DAG.getSrcValue(I.getOperand(2))));
2172 // It is always conservatively correct for llvm.returnaddress and
2173 // llvm.frameaddress to return 0.
2174 std::pair<SDOperand, SDOperand>
2175 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2176 unsigned Depth, SelectionDAG &DAG) {
2177 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
2180 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
2181 assert(0 && "LowerOperation not implemented for this target!");
2186 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2187 SelectionDAG &DAG) {
2188 assert(0 && "CustomPromoteOperation not implemented for this target!");
2193 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2194 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2195 std::pair<SDOperand,SDOperand> Result =
2196 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
2197 setValue(&I, Result.first);
2198 DAG.setRoot(Result.second);
2201 /// getMemsetValue - Vectorized representation of the memset value
2203 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2204 SelectionDAG &DAG) {
2205 MVT::ValueType CurVT = VT;
2206 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2207 uint64_t Val = C->getValue() & 255;
2209 while (CurVT != MVT::i8) {
2210 Val = (Val << Shift) | Val;
2212 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2214 return DAG.getConstant(Val, VT);
2216 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2218 while (CurVT != MVT::i8) {
2220 DAG.getNode(ISD::OR, VT,
2221 DAG.getNode(ISD::SHL, VT, Value,
2222 DAG.getConstant(Shift, MVT::i8)), Value);
2224 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2231 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2232 /// used when a memcpy is turned into a memset when the source is a constant
2234 static SDOperand getMemsetStringVal(MVT::ValueType VT,
2235 SelectionDAG &DAG, TargetLowering &TLI,
2236 std::string &Str, unsigned Offset) {
2237 MVT::ValueType CurVT = VT;
2239 unsigned MSB = getSizeInBits(VT) / 8;
2240 if (TLI.isLittleEndian())
2241 Offset = Offset + MSB - 1;
2242 for (unsigned i = 0; i != MSB; ++i) {
2243 Val = (Val << 8) | Str[Offset];
2244 Offset += TLI.isLittleEndian() ? -1 : 1;
2246 return DAG.getConstant(Val, VT);
2249 /// getMemBasePlusOffset - Returns base and offset node for the
2250 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2251 SelectionDAG &DAG, TargetLowering &TLI) {
2252 MVT::ValueType VT = Base.getValueType();
2253 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2256 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2257 /// to replace the memset / memcpy is below the threshold. It also returns the
2258 /// types of the sequence of memory ops to perform memset / memcpy.
2259 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2260 unsigned Limit, uint64_t Size,
2261 unsigned Align, TargetLowering &TLI) {
2264 if (TLI.allowsUnalignedMemoryAccesses()) {
2267 switch (Align & 7) {
2283 MVT::ValueType LVT = MVT::i64;
2284 while (!TLI.isTypeLegal(LVT))
2285 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2286 assert(MVT::isInteger(LVT));
2291 unsigned NumMemOps = 0;
2293 unsigned VTSize = getSizeInBits(VT) / 8;
2294 while (VTSize > Size) {
2295 VT = (MVT::ValueType)((unsigned)VT - 1);
2298 assert(MVT::isInteger(VT));
2300 if (++NumMemOps > Limit)
2302 MemOps.push_back(VT);
2309 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
2310 SDOperand Op1 = getValue(I.getOperand(1));
2311 SDOperand Op2 = getValue(I.getOperand(2));
2312 SDOperand Op3 = getValue(I.getOperand(3));
2313 SDOperand Op4 = getValue(I.getOperand(4));
2314 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2315 if (Align == 0) Align = 1;
2317 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2318 std::vector<MVT::ValueType> MemOps;
2320 // Expand memset / memcpy to a series of load / store ops
2321 // if the size operand falls below a certain threshold.
2322 std::vector<SDOperand> OutChains;
2324 default: break; // Do nothing for now.
2326 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2327 Size->getValue(), Align, TLI)) {
2328 unsigned NumMemOps = MemOps.size();
2329 unsigned Offset = 0;
2330 for (unsigned i = 0; i < NumMemOps; i++) {
2331 MVT::ValueType VT = MemOps[i];
2332 unsigned VTSize = getSizeInBits(VT) / 8;
2333 SDOperand Value = getMemsetValue(Op2, VT, DAG);
2334 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2336 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2337 DAG.getSrcValue(I.getOperand(1), Offset));
2338 OutChains.push_back(Store);
2345 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2346 Size->getValue(), Align, TLI)) {
2347 unsigned NumMemOps = MemOps.size();
2348 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
2349 GlobalAddressSDNode *G = NULL;
2351 bool CopyFromStr = false;
2353 if (Op2.getOpcode() == ISD::GlobalAddress)
2354 G = cast<GlobalAddressSDNode>(Op2);
2355 else if (Op2.getOpcode() == ISD::ADD &&
2356 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2357 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2358 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
2359 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
2362 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2364 Str = GV->getStringValue(false);
2372 for (unsigned i = 0; i < NumMemOps; i++) {
2373 MVT::ValueType VT = MemOps[i];
2374 unsigned VTSize = getSizeInBits(VT) / 8;
2375 SDOperand Value, Chain, Store;
2378 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2381 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2382 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2383 DAG.getSrcValue(I.getOperand(1), DstOff));
2385 Value = DAG.getLoad(VT, getRoot(),
2386 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2387 DAG.getSrcValue(I.getOperand(2), SrcOff));
2388 Chain = Value.getValue(1);
2390 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2391 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2392 DAG.getSrcValue(I.getOperand(1), DstOff));
2394 OutChains.push_back(Store);
2403 if (!OutChains.empty()) {
2404 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2409 std::vector<SDOperand> Ops;
2410 Ops.push_back(getRoot());
2415 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
2418 //===----------------------------------------------------------------------===//
2419 // SelectionDAGISel code
2420 //===----------------------------------------------------------------------===//
2422 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2423 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2426 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
2427 // FIXME: we only modify the CFG to split critical edges. This
2428 // updates dom and loop info.
2432 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2433 /// casting to the type of GEPI.
2434 static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2435 Value *Ptr, Value *PtrOffset) {
2436 if (V) return V; // Already computed.
2438 BasicBlock::iterator InsertPt;
2439 if (BB == GEPI->getParent()) {
2440 // If insert into the GEP's block, insert right after the GEP.
2444 // Otherwise, insert at the top of BB, after any PHI nodes
2445 InsertPt = BB->begin();
2446 while (isa<PHINode>(InsertPt)) ++InsertPt;
2449 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2450 // BB so that there is only one value live across basic blocks (the cast
2452 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2453 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2454 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2456 // Add the offset, cast it to the right type.
2457 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2458 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2463 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2464 /// selection, we want to be a bit careful about some things. In particular, if
2465 /// we have a GEP instruction that is used in a different block than it is
2466 /// defined, the addressing expression of the GEP cannot be folded into loads or
2467 /// stores that use it. In this case, decompose the GEP and move constant
2468 /// indices into blocks that use it.
2469 static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2470 const TargetData &TD) {
2471 // If this GEP is only used inside the block it is defined in, there is no
2472 // need to rewrite it.
2473 bool isUsedOutsideDefBB = false;
2474 BasicBlock *DefBB = GEPI->getParent();
2475 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2477 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2478 isUsedOutsideDefBB = true;
2482 if (!isUsedOutsideDefBB) return;
2484 // If this GEP has no non-zero constant indices, there is nothing we can do,
2486 bool hasConstantIndex = false;
2487 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2488 E = GEPI->op_end(); OI != E; ++OI) {
2489 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2490 if (CI->getRawValue()) {
2491 hasConstantIndex = true;
2495 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2496 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
2498 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2499 // constant offset (which we now know is non-zero) and deal with it later.
2500 uint64_t ConstantOffset = 0;
2501 const Type *UIntPtrTy = TD.getIntPtrType();
2502 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2503 const Type *Ty = GEPI->getOperand(0)->getType();
2505 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2506 E = GEPI->op_end(); OI != E; ++OI) {
2508 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2509 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2511 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2512 Ty = StTy->getElementType(Field);
2514 Ty = cast<SequentialType>(Ty)->getElementType();
2516 // Handle constant subscripts.
2517 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2518 if (CI->getRawValue() == 0) continue;
2520 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2521 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2523 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2527 // Ptr = Ptr + Idx * ElementSize;
2529 // Cast Idx to UIntPtrTy if needed.
2530 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2532 uint64_t ElementSize = TD.getTypeSize(Ty);
2533 // Mask off bits that should not be set.
2534 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2535 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2537 // Multiply by the element size and add to the base.
2538 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2539 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2543 // Make sure that the offset fits in uintptr_t.
2544 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2545 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2547 // Okay, we have now emitted all of the variable index parts to the BB that
2548 // the GEP is defined in. Loop over all of the using instructions, inserting
2549 // an "add Ptr, ConstantOffset" into each block that uses it and update the
2550 // instruction to use the newly computed value, making GEPI dead. When the
2551 // user is a load or store instruction address, we emit the add into the user
2552 // block, otherwise we use a canonical version right next to the gep (these
2553 // won't be foldable as addresses, so we might as well share the computation).
2555 std::map<BasicBlock*,Value*> InsertedExprs;
2556 while (!GEPI->use_empty()) {
2557 Instruction *User = cast<Instruction>(GEPI->use_back());
2559 // If this use is not foldable into the addressing mode, use a version
2560 // emitted in the GEP block.
2562 if (!isa<LoadInst>(User) &&
2563 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2564 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2567 // Otherwise, insert the code in the User's block so it can be folded into
2568 // any users in that block.
2569 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
2570 User->getParent(), GEPI,
2573 User->replaceUsesOfWith(GEPI, NewVal);
2576 // Finally, the GEP is dead, remove it.
2577 GEPI->eraseFromParent();
2580 bool SelectionDAGISel::runOnFunction(Function &Fn) {
2581 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2582 RegMap = MF.getSSARegMap();
2583 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2585 // First, split all critical edges for PHI nodes with incoming values that are
2586 // constants, this way the load of the constant into a vreg will not be placed
2587 // into MBBs that are used some other way.
2589 // In this pass we also look for GEP instructions that are used across basic
2590 // blocks and rewrites them to improve basic-block-at-a-time selection.
2592 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2594 BasicBlock::iterator BBI;
2595 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
2596 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2597 if (isa<Constant>(PN->getIncomingValue(i)))
2598 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
2600 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2601 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2602 OptimizeGEPExpression(GEPI, TLI.getTargetData());
2605 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2607 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2608 SelectBasicBlock(I, MF, FuncInfo);
2614 SDOperand SelectionDAGISel::
2615 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
2616 SDOperand Op = SDL.getValue(V);
2617 assert((Op.getOpcode() != ISD::CopyFromReg ||
2618 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
2619 "Copy from a reg to the same reg!");
2621 // If this type is not legal, we must make sure to not create an invalid
2623 MVT::ValueType SrcVT = Op.getValueType();
2624 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2625 SelectionDAG &DAG = SDL.DAG;
2626 if (SrcVT == DestVT) {
2627 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2628 } else if (SrcVT == MVT::Vector) {
2629 // Handle copies from generic vectors to registers.
2630 MVT::ValueType PTyElementVT, PTyLegalElementVT;
2631 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
2632 PTyElementVT, PTyLegalElementVT);
2634 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
2635 // MVT::Vector type.
2636 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
2637 DAG.getConstant(NE, MVT::i32),
2638 DAG.getValueType(PTyElementVT));
2640 // Loop over all of the elements of the resultant vector,
2641 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
2642 // copying them into output registers.
2643 std::vector<SDOperand> OutChains;
2644 SDOperand Root = SDL.getRoot();
2645 for (unsigned i = 0; i != NE; ++i) {
2646 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
2647 Op, DAG.getConstant(i, MVT::i32));
2648 if (PTyElementVT == PTyLegalElementVT) {
2649 // Elements are legal.
2650 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2651 } else if (PTyLegalElementVT > PTyElementVT) {
2652 // Elements are promoted.
2653 if (MVT::isFloatingPoint(PTyLegalElementVT))
2654 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
2656 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
2657 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2659 // Elements are expanded.
2660 // The src value is expanded into multiple registers.
2661 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2662 Elt, DAG.getConstant(0, MVT::i32));
2663 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2664 Elt, DAG.getConstant(1, MVT::i32));
2665 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
2666 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
2669 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2670 } else if (SrcVT < DestVT) {
2671 // The src value is promoted to the register.
2672 if (MVT::isFloatingPoint(SrcVT))
2673 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2675 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
2676 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2678 // The src value is expanded into multiple registers.
2679 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2680 Op, DAG.getConstant(0, MVT::i32));
2681 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2682 Op, DAG.getConstant(1, MVT::i32));
2683 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2684 return DAG.getCopyToReg(Op, Reg+1, Hi);
2688 void SelectionDAGISel::
2689 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2690 std::vector<SDOperand> &UnorderedChains) {
2691 // If this is the entry block, emit arguments.
2692 Function &F = *BB->getParent();
2693 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
2694 SDOperand OldRoot = SDL.DAG.getRoot();
2695 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
2698 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2700 if (!AI->use_empty()) {
2701 SDL.setValue(AI, Args[a]);
2703 // If this argument is live outside of the entry block, insert a copy from
2704 // whereever we got it to the vreg that other BB's will reference it as.
2705 if (FuncInfo.ValueMap.count(AI)) {
2707 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2708 UnorderedChains.push_back(Copy);
2712 // Next, if the function has live ins that need to be copied into vregs,
2713 // emit the copies now, into the top of the block.
2714 MachineFunction &MF = SDL.DAG.getMachineFunction();
2715 if (MF.livein_begin() != MF.livein_end()) {
2716 SSARegMap *RegMap = MF.getSSARegMap();
2717 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2718 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2719 E = MF.livein_end(); LI != E; ++LI)
2721 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2722 LI->first, RegMap->getRegClass(LI->second));
2725 // Finally, if the target has anything special to do, allow it to do so.
2726 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
2730 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2731 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2732 FunctionLoweringInfo &FuncInfo) {
2733 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
2735 std::vector<SDOperand> UnorderedChains;
2737 // Lower any arguments needed in this block if this is the entry block.
2738 if (LLVMBB == &LLVMBB->getParent()->front())
2739 LowerArguments(LLVMBB, SDL, UnorderedChains);
2741 BB = FuncInfo.MBBMap[LLVMBB];
2742 SDL.setCurrentBasicBlock(BB);
2744 // Lower all of the non-terminator instructions.
2745 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2749 // Ensure that all instructions which are used outside of their defining
2750 // blocks are available as virtual registers.
2751 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
2752 if (!I->use_empty() && !isa<PHINode>(I)) {
2753 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
2754 if (VMI != FuncInfo.ValueMap.end())
2755 UnorderedChains.push_back(
2756 CopyValueToVirtualRegister(SDL, I, VMI->second));
2759 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2760 // ensure constants are generated when needed. Remember the virtual registers
2761 // that need to be added to the Machine PHI nodes as input. We cannot just
2762 // directly add them, because expansion might result in multiple MBB's for one
2763 // BB. As such, the start of the BB might correspond to a different MBB than
2767 // Emit constants only once even if used by multiple PHI nodes.
2768 std::map<Constant*, unsigned> ConstantsOut;
2770 // Check successor nodes PHI nodes that expect a constant to be available from
2772 TerminatorInst *TI = LLVMBB->getTerminator();
2773 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2774 BasicBlock *SuccBB = TI->getSuccessor(succ);
2775 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2778 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2779 // nodes and Machine PHI nodes, but the incoming operands have not been
2781 for (BasicBlock::iterator I = SuccBB->begin();
2782 (PN = dyn_cast<PHINode>(I)); ++I)
2783 if (!PN->use_empty()) {
2785 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2786 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2787 unsigned &RegOut = ConstantsOut[C];
2789 RegOut = FuncInfo.CreateRegForValue(C);
2790 UnorderedChains.push_back(
2791 CopyValueToVirtualRegister(SDL, C, RegOut));
2795 Reg = FuncInfo.ValueMap[PHIOp];
2797 assert(isa<AllocaInst>(PHIOp) &&
2798 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2799 "Didn't codegen value into a register!??");
2800 Reg = FuncInfo.CreateRegForValue(PHIOp);
2801 UnorderedChains.push_back(
2802 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
2806 // Remember that this register needs to added to the machine PHI node as
2807 // the input for this MBB.
2808 unsigned NumElements =
2809 TLI.getNumElements(TLI.getValueType(PN->getType()));
2810 for (unsigned i = 0, e = NumElements; i != e; ++i)
2811 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
2814 ConstantsOut.clear();
2816 // Turn all of the unordered chains into one factored node.
2817 if (!UnorderedChains.empty()) {
2818 SDOperand Root = SDL.getRoot();
2819 if (Root.getOpcode() != ISD::EntryToken) {
2820 unsigned i = 0, e = UnorderedChains.size();
2821 for (; i != e; ++i) {
2822 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2823 if (UnorderedChains[i].Val->getOperand(0) == Root)
2824 break; // Don't add the root if we already indirectly depend on it.
2828 UnorderedChains.push_back(Root);
2830 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2833 // Lower the terminator after the copies are emitted.
2834 SDL.visit(*LLVMBB->getTerminator());
2836 // Copy over any CaseBlock records that may now exist due to SwitchInst
2838 SwitchCases.clear();
2839 SwitchCases = SDL.SwitchCases;
2841 // Make sure the root of the DAG is up-to-date.
2842 DAG.setRoot(SDL.getRoot());
2845 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
2846 // Run the DAG combiner in pre-legalize mode.
2849 DEBUG(std::cerr << "Lowered selection DAG:\n");
2852 // Second step, hack on the DAG until it only uses operations and types that
2853 // the target supports.
2856 DEBUG(std::cerr << "Legalized selection DAG:\n");
2859 // Run the DAG combiner in post-legalize mode.
2862 if (ViewISelDAGs) DAG.viewGraph();
2864 // Third, instruction select all of the operations to machine code, adding the
2865 // code to the MachineBasicBlock.
2866 InstructionSelectBasicBlock(DAG);
2868 DEBUG(std::cerr << "Selected machine code:\n");
2872 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2873 FunctionLoweringInfo &FuncInfo) {
2874 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2876 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2879 // First step, lower LLVM code to some DAG. This DAG may use operations and
2880 // types that are not supported by the target.
2881 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2883 // Second step, emit the lowered DAG as machine code.
2884 CodeGenAndEmitDAG(DAG);
2887 // Next, now that we know what the last MBB the LLVM BB expanded is, update
2888 // PHI nodes in successors.
2889 if (SwitchCases.empty()) {
2890 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2891 MachineInstr *PHI = PHINodesToUpdate[i].first;
2892 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2893 "This is not a machine PHI node that we are updating!");
2894 PHI->addRegOperand(PHINodesToUpdate[i].second);
2895 PHI->addMachineBasicBlockOperand(BB);
2900 // If we generated any switch lowering information, build and codegen any
2901 // additional DAGs necessary.
2902 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
2903 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2905 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
2906 // Set the current basic block to the mbb we wish to insert the code into
2907 BB = SwitchCases[i].ThisBB;
2908 SDL.setCurrentBasicBlock(BB);
2910 SDL.visitSwitchCase(SwitchCases[i]);
2911 SDAG.setRoot(SDL.getRoot());
2912 CodeGenAndEmitDAG(SDAG);
2913 // Iterate over the phi nodes, if there is a phi node in a successor of this
2914 // block (for instance, the default block), then add a pair of operands to
2915 // the phi node for this block, as if we were coming from the original
2916 // BB before switch expansion.
2917 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
2918 MachineInstr *PHI = PHINodesToUpdate[pi].first;
2919 MachineBasicBlock *PHIBB = PHI->getParent();
2920 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2921 "This is not a machine PHI node that we are updating!");
2922 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
2923 PHI->addRegOperand(PHINodesToUpdate[pi].second);
2924 PHI->addMachineBasicBlockOperand(BB);
2930 //===----------------------------------------------------------------------===//
2931 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2932 /// target node in the graph.
2933 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2934 if (ViewSchedDAGs) DAG.viewGraph();
2935 ScheduleDAG *SL = NULL;
2937 switch (ISHeuristic) {
2938 default: assert(0 && "Unrecognized scheduling heuristic");
2939 case defaultScheduling:
2940 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2941 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2942 else /* TargetLowering::SchedulingForRegPressure */
2943 SL = createBURRListDAGScheduler(DAG, BB);
2946 SL = createBFS_DAGScheduler(DAG, BB);
2948 case simpleScheduling:
2949 SL = createSimpleDAGScheduler(false, DAG, BB);
2951 case simpleNoItinScheduling:
2952 SL = createSimpleDAGScheduler(true, DAG, BB);
2954 case listSchedulingBURR:
2955 SL = createBURRListDAGScheduler(DAG, BB);
2957 case listSchedulingTD:
2958 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
2965 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2966 return new HazardRecognizer();
2969 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2970 /// by tblgen. Others should not call it.
2971 void SelectionDAGISel::
2972 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2973 std::vector<SDOperand> InOps;
2974 std::swap(InOps, Ops);
2976 Ops.push_back(InOps[0]); // input chain.
2977 Ops.push_back(InOps[1]); // input asm string.
2979 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2980 unsigned i = 2, e = InOps.size();
2981 if (InOps[e-1].getValueType() == MVT::Flag)
2982 --e; // Don't process a flag operand if it is here.
2985 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2986 if ((Flags & 7) != 4 /*MEM*/) {
2987 // Just skip over this operand, copying the operands verbatim.
2988 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2989 i += (Flags >> 3) + 1;
2991 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2992 // Otherwise, this is a memory operand. Ask the target to select it.
2993 std::vector<SDOperand> SelOps;
2994 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2995 std::cerr << "Could not match memory address. Inline asm failure!\n";
2999 // Add this to the output node.
3000 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3001 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3006 // Add the flag input back if present.
3007 if (e != InOps.size())
3008 Ops.push_back(InOps.back());