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/CodeGen/IntrinsicLowering.h"
26 #include "llvm/CodeGen/MachineDebugInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/SSARegMap.h"
32 #include "llvm/Target/MRegisterInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetFrameInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/Debug.h"
49 ViewISelDAGs("view-isel-dags", cl::Hidden,
50 cl::desc("Pop up a window to show isel dags as they are selected"));
52 ViewSchedDAGs("view-sched-dags", cl::Hidden,
53 cl::desc("Pop up a window to show sched dags as they are processed"));
55 static const bool ViewISelDAGs = 0;
56 static const bool ViewSchedDAGs = 0;
60 cl::opt<SchedHeuristics>
63 cl::desc("Choose scheduling style"),
64 cl::init(defaultScheduling),
66 clEnumValN(defaultScheduling, "default",
67 "Target preferred scheduling style"),
68 clEnumValN(noScheduling, "none",
69 "No scheduling: breadth first sequencing"),
70 clEnumValN(simpleScheduling, "simple",
71 "Simple two pass scheduling: minimize critical path "
72 "and maximize processor utilization"),
73 clEnumValN(simpleNoItinScheduling, "simple-noitin",
74 "Simple two pass scheduling: Same as simple "
75 "except using generic latency"),
76 clEnumValN(listSchedulingBURR, "list-burr",
77 "Bottom up register reduction list scheduling"),
82 /// RegsForValue - This struct represents the physical registers that a
83 /// particular value is assigned and the type information about the value.
84 /// This is needed because values can be promoted into larger registers and
85 /// expanded into multiple smaller registers than the value.
87 /// Regs - This list hold the register (for legal and promoted values)
88 /// or register set (for expanded values) that the value should be assigned
90 std::vector<unsigned> Regs;
92 /// RegVT - The value type of each register.
96 /// ValueVT - The value type of the LLVM value, which may be promoted from
97 /// RegVT or made from merging the two expanded parts.
98 MVT::ValueType ValueVT;
100 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
102 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
103 : RegVT(regvt), ValueVT(valuevt) {
106 RegsForValue(const std::vector<unsigned> ®s,
107 MVT::ValueType regvt, MVT::ValueType valuevt)
108 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
111 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
112 /// this value and returns the result as a ValueVT value. This uses
113 /// Chain/Flag as the input and updates them for the output Chain/Flag.
114 SDOperand getCopyFromRegs(SelectionDAG &DAG,
115 SDOperand &Chain, SDOperand &Flag);
117 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
118 /// specified value into the registers specified by this object. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
121 SDOperand &Chain, SDOperand &Flag);
123 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
124 /// operand list. This adds the code marker and includes the number of
125 /// values added into it.
126 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
127 std::vector<SDOperand> &Ops);
132 //===--------------------------------------------------------------------===//
133 /// FunctionLoweringInfo - This contains information that is global to a
134 /// function that is used when lowering a region of the function.
135 class FunctionLoweringInfo {
142 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
144 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
145 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
147 /// ValueMap - Since we emit code for the function a basic block at a time,
148 /// we must remember which virtual registers hold the values for
149 /// cross-basic-block values.
150 std::map<const Value*, unsigned> ValueMap;
152 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
153 /// the entry block. This allows the allocas to be efficiently referenced
154 /// anywhere in the function.
155 std::map<const AllocaInst*, int> StaticAllocaMap;
157 unsigned MakeReg(MVT::ValueType VT) {
158 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
161 unsigned CreateRegForValue(const Value *V) {
162 MVT::ValueType VT = TLI.getValueType(V->getType());
163 // The common case is that we will only create one register for this
164 // value. If we have that case, create and return the virtual register.
165 unsigned NV = TLI.getNumElements(VT);
167 // If we are promoting this value, pick the next largest supported type.
168 return MakeReg(TLI.getTypeToTransformTo(VT));
171 // If this value is represented with multiple target registers, make sure
172 // to create enough consecutive registers of the right (smaller) type.
173 unsigned NT = VT-1; // Find the type to use.
174 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
177 unsigned R = MakeReg((MVT::ValueType)NT);
178 for (unsigned i = 1; i != NV; ++i)
179 MakeReg((MVT::ValueType)NT);
183 unsigned InitializeRegForValue(const Value *V) {
184 unsigned &R = ValueMap[V];
185 assert(R == 0 && "Already initialized this value register!");
186 return R = CreateRegForValue(V);
191 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
192 /// PHI nodes or outside of the basic block that defines it.
193 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
194 if (isa<PHINode>(I)) return true;
195 BasicBlock *BB = I->getParent();
196 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
197 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
202 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
203 /// entry block, return true.
204 static bool isOnlyUsedInEntryBlock(Argument *A) {
205 BasicBlock *Entry = A->getParent()->begin();
206 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
207 if (cast<Instruction>(*UI)->getParent() != Entry)
208 return false; // Use not in entry block.
212 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
213 Function &fn, MachineFunction &mf)
214 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
216 // Create a vreg for each argument register that is not dead and is used
217 // outside of the entry block for the function.
218 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
220 if (!isOnlyUsedInEntryBlock(AI))
221 InitializeRegForValue(AI);
223 // Initialize the mapping of values to registers. This is only set up for
224 // instruction values that are used outside of the block that defines
226 Function::iterator BB = Fn.begin(), EB = Fn.end();
227 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
228 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
229 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
230 const Type *Ty = AI->getAllocatedType();
231 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
233 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
236 // If the alignment of the value is smaller than the size of the value,
237 // and if the size of the value is particularly small (<= 8 bytes),
238 // round up to the size of the value for potentially better performance.
240 // FIXME: This could be made better with a preferred alignment hook in
241 // TargetData. It serves primarily to 8-byte align doubles for X86.
242 if (Align < TySize && TySize <= 8) Align = TySize;
243 TySize *= CUI->getValue(); // Get total allocated size.
244 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
245 StaticAllocaMap[AI] =
246 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
249 for (; BB != EB; ++BB)
250 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
251 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
252 if (!isa<AllocaInst>(I) ||
253 !StaticAllocaMap.count(cast<AllocaInst>(I)))
254 InitializeRegForValue(I);
256 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
257 // also creates the initial PHI MachineInstrs, though none of the input
258 // operands are populated.
259 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
260 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
262 MF.getBasicBlockList().push_back(MBB);
264 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
267 for (BasicBlock::iterator I = BB->begin();
268 (PN = dyn_cast<PHINode>(I)); ++I)
269 if (!PN->use_empty()) {
270 unsigned NumElements =
271 TLI.getNumElements(TLI.getValueType(PN->getType()));
272 unsigned PHIReg = ValueMap[PN];
273 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
274 for (unsigned i = 0; i != NumElements; ++i)
275 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
282 //===----------------------------------------------------------------------===//
283 /// SelectionDAGLowering - This is the common target-independent lowering
284 /// implementation that is parameterized by a TargetLowering object.
285 /// Also, targets can overload any lowering method.
288 class SelectionDAGLowering {
289 MachineBasicBlock *CurMBB;
291 std::map<const Value*, SDOperand> NodeMap;
293 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
294 /// them up and then emit token factor nodes when possible. This allows us to
295 /// get simple disambiguation between loads without worrying about alias
297 std::vector<SDOperand> PendingLoads;
300 // TLI - This is information that describes the available target features we
301 // need for lowering. This indicates when operations are unavailable,
302 // implemented with a libcall, etc.
305 const TargetData &TD;
307 /// FuncInfo - Information about the function as a whole.
309 FunctionLoweringInfo &FuncInfo;
311 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
312 FunctionLoweringInfo &funcinfo)
313 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
317 /// getRoot - Return the current virtual root of the Selection DAG.
319 SDOperand getRoot() {
320 if (PendingLoads.empty())
321 return DAG.getRoot();
323 if (PendingLoads.size() == 1) {
324 SDOperand Root = PendingLoads[0];
326 PendingLoads.clear();
330 // Otherwise, we have to make a token factor node.
331 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
332 PendingLoads.clear();
337 void visit(Instruction &I) { visit(I.getOpcode(), I); }
339 void visit(unsigned Opcode, User &I) {
341 default: assert(0 && "Unknown instruction type encountered!");
343 // Build the switch statement using the Instruction.def file.
344 #define HANDLE_INST(NUM, OPCODE, CLASS) \
345 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
346 #include "llvm/Instruction.def"
350 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
353 SDOperand getIntPtrConstant(uint64_t Val) {
354 return DAG.getConstant(Val, TLI.getPointerTy());
357 SDOperand getValue(const Value *V) {
358 SDOperand &N = NodeMap[V];
361 const Type *VTy = V->getType();
362 MVT::ValueType VT = TLI.getValueType(VTy);
363 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
365 visit(CE->getOpcode(), *CE);
366 assert(N.Val && "visit didn't populate the ValueMap!");
368 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
369 return N = DAG.getGlobalAddress(GV, VT);
370 } else if (isa<ConstantPointerNull>(C)) {
371 return N = DAG.getConstant(0, TLI.getPointerTy());
372 } else if (isa<UndefValue>(C)) {
373 return N = DAG.getNode(ISD::UNDEF, VT);
374 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
375 return N = DAG.getConstantFP(CFP->getValue(), VT);
376 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
377 unsigned NumElements = PTy->getNumElements();
378 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
379 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
381 // Now that we know the number and type of the elements, push a
382 // Constant or ConstantFP node onto the ops list for each element of
383 // the packed constant.
384 std::vector<SDOperand> Ops;
385 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
386 if (MVT::isFloatingPoint(PVT)) {
387 for (unsigned i = 0; i != NumElements; ++i) {
388 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
389 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
392 for (unsigned i = 0; i != NumElements; ++i) {
393 const ConstantIntegral *El =
394 cast<ConstantIntegral>(CP->getOperand(i));
395 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
399 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
401 if (MVT::isFloatingPoint(PVT))
402 Op = DAG.getConstantFP(0, PVT);
404 Op = DAG.getConstant(0, PVT);
405 Ops.assign(NumElements, Op);
408 // Handle the case where we have a 1-element vector, in which
409 // case we want to immediately turn it into a scalar constant.
410 if (Ops.size() == 1) {
412 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
413 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
415 // If the packed type isn't legal, then create a ConstantVec node with
416 // generic Vector type instead.
417 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
420 // Canonicalize all constant ints to be unsigned.
421 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
424 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
425 std::map<const AllocaInst*, int>::iterator SI =
426 FuncInfo.StaticAllocaMap.find(AI);
427 if (SI != FuncInfo.StaticAllocaMap.end())
428 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
431 std::map<const Value*, unsigned>::const_iterator VMI =
432 FuncInfo.ValueMap.find(V);
433 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
435 unsigned InReg = VMI->second;
437 // If this type is not legal, make it so now.
438 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
440 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
442 // Source must be expanded. This input value is actually coming from the
443 // register pair VMI->second and VMI->second+1.
444 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
445 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
447 if (DestVT > VT) { // Promotion case
448 if (MVT::isFloatingPoint(VT))
449 N = DAG.getNode(ISD::FP_ROUND, VT, N);
451 N = DAG.getNode(ISD::TRUNCATE, VT, N);
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 visitUnreachable(UnreachableInst &I) { /* noop */ }
475 // These all get lowered before this pass.
476 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
477 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
478 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
479 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
480 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();
494 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
496 void visitRem(User &I) {
497 const Type *Ty = I.getType();
498 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
500 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
501 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
502 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
503 void visitShl(User &I) { visitShift(I, ISD::SHL); }
504 void visitShr(User &I) {
505 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
508 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
509 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
510 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
511 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
512 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
513 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
514 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
516 void visitGetElementPtr(User &I);
517 void visitCast(User &I);
518 void visitSelect(User &I);
521 void visitMalloc(MallocInst &I);
522 void visitFree(FreeInst &I);
523 void visitAlloca(AllocaInst &I);
524 void visitLoad(LoadInst &I);
525 void visitStore(StoreInst &I);
526 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
527 void visitCall(CallInst &I);
528 void visitInlineAsm(CallInst &I);
529 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
531 void visitVAStart(CallInst &I);
532 void visitVAArg(VAArgInst &I);
533 void visitVAEnd(CallInst &I);
534 void visitVACopy(CallInst &I);
535 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
537 void visitMemIntrinsic(CallInst &I, unsigned Op);
539 void visitUserOp1(Instruction &I) {
540 assert(0 && "UserOp1 should not exist at instruction selection time!");
543 void visitUserOp2(Instruction &I) {
544 assert(0 && "UserOp2 should not exist at instruction selection time!");
548 } // end namespace llvm
550 void SelectionDAGLowering::visitRet(ReturnInst &I) {
551 if (I.getNumOperands() == 0) {
552 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
555 std::vector<SDOperand> NewValues;
556 NewValues.push_back(getRoot());
557 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
558 SDOperand RetOp = getValue(I.getOperand(i));
560 // If this is an integer return value, we need to promote it ourselves to
561 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
563 if (MVT::isInteger(RetOp.getValueType()) &&
564 RetOp.getValueType() < MVT::i64) {
565 MVT::ValueType TmpVT;
566 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
567 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
571 if (I.getOperand(i)->getType()->isSigned())
572 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
574 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
576 NewValues.push_back(RetOp);
578 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
581 void SelectionDAGLowering::visitBr(BranchInst &I) {
582 // Update machine-CFG edges.
583 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
585 // Figure out which block is immediately after the current one.
586 MachineBasicBlock *NextBlock = 0;
587 MachineFunction::iterator BBI = CurMBB;
588 if (++BBI != CurMBB->getParent()->end())
591 if (I.isUnconditional()) {
592 // If this is not a fall-through branch, emit the branch.
593 if (Succ0MBB != NextBlock)
594 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
595 DAG.getBasicBlock(Succ0MBB)));
597 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
599 SDOperand Cond = getValue(I.getCondition());
600 if (Succ1MBB == NextBlock) {
601 // If the condition is false, fall through. This means we should branch
602 // if the condition is true to Succ #0.
603 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
604 Cond, DAG.getBasicBlock(Succ0MBB)));
605 } else if (Succ0MBB == NextBlock) {
606 // If the condition is true, fall through. This means we should branch if
607 // the condition is false to Succ #1. Invert the condition first.
608 SDOperand True = DAG.getConstant(1, Cond.getValueType());
609 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
610 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
611 Cond, DAG.getBasicBlock(Succ1MBB)));
613 std::vector<SDOperand> Ops;
614 Ops.push_back(getRoot());
615 // If the false case is the current basic block, then this is a self
616 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
617 // adds an extra instruction in the loop. Instead, invert the
618 // condition and emit "Loop: ... br!cond Loop; br Out.
619 if (CurMBB == Succ1MBB) {
620 std::swap(Succ0MBB, Succ1MBB);
621 SDOperand True = DAG.getConstant(1, Cond.getValueType());
622 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
625 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
626 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
627 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
632 void SelectionDAGLowering::visitSub(User &I) {
634 if (I.getType()->isFloatingPoint()) {
635 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
636 if (CFP->isExactlyValue(-0.0)) {
637 SDOperand Op2 = getValue(I.getOperand(1));
638 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
642 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
645 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
647 const Type *Ty = I.getType();
648 SDOperand Op1 = getValue(I.getOperand(0));
649 SDOperand Op2 = getValue(I.getOperand(1));
651 if (Ty->isIntegral()) {
652 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
653 } else if (Ty->isFloatingPoint()) {
654 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
656 const PackedType *PTy = cast<PackedType>(Ty);
657 unsigned NumElements = PTy->getNumElements();
658 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
659 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
661 // Immediately scalarize packed types containing only one element, so that
662 // the Legalize pass does not have to deal with them. Similarly, if the
663 // abstract vector is going to turn into one that the target natively
664 // supports, generate that type now so that Legalize doesn't have to deal
665 // with that either. These steps ensure that Legalize only has to handle
666 // vector types in its Expand case.
667 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
668 if (NumElements == 1) {
669 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
670 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
671 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
673 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
674 SDOperand Typ = DAG.getValueType(PVT);
675 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
680 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
681 SDOperand Op1 = getValue(I.getOperand(0));
682 SDOperand Op2 = getValue(I.getOperand(1));
684 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
686 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
689 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
690 ISD::CondCode UnsignedOpcode) {
691 SDOperand Op1 = getValue(I.getOperand(0));
692 SDOperand Op2 = getValue(I.getOperand(1));
693 ISD::CondCode Opcode = SignedOpcode;
694 if (I.getOperand(0)->getType()->isUnsigned())
695 Opcode = UnsignedOpcode;
696 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
699 void SelectionDAGLowering::visitSelect(User &I) {
700 SDOperand Cond = getValue(I.getOperand(0));
701 SDOperand TrueVal = getValue(I.getOperand(1));
702 SDOperand FalseVal = getValue(I.getOperand(2));
703 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
707 void SelectionDAGLowering::visitCast(User &I) {
708 SDOperand N = getValue(I.getOperand(0));
709 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
710 MVT::ValueType DestTy = TLI.getValueType(I.getType());
712 if (N.getValueType() == DestTy) {
713 setValue(&I, N); // noop cast.
714 } else if (DestTy == MVT::i1) {
715 // Cast to bool is a comparison against zero, not truncation to zero.
716 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
717 DAG.getConstantFP(0.0, N.getValueType());
718 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
719 } else if (isInteger(SrcTy)) {
720 if (isInteger(DestTy)) { // Int -> Int cast
721 if (DestTy < SrcTy) // Truncating cast?
722 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
723 else if (I.getOperand(0)->getType()->isSigned())
724 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
726 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
727 } else { // Int -> FP cast
728 if (I.getOperand(0)->getType()->isSigned())
729 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
731 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
734 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
735 if (isFloatingPoint(DestTy)) { // FP -> FP cast
736 if (DestTy < SrcTy) // Rounding cast?
737 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
739 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
740 } else { // FP -> Int cast.
741 if (I.getType()->isSigned())
742 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
744 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
749 void SelectionDAGLowering::visitGetElementPtr(User &I) {
750 SDOperand N = getValue(I.getOperand(0));
751 const Type *Ty = I.getOperand(0)->getType();
752 const Type *UIntPtrTy = TD.getIntPtrType();
754 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
757 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
758 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
761 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
762 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
763 getIntPtrConstant(Offset));
765 Ty = StTy->getElementType(Field);
767 Ty = cast<SequentialType>(Ty)->getElementType();
769 // If this is a constant subscript, handle it quickly.
770 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
771 if (CI->getRawValue() == 0) continue;
774 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
775 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
777 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
778 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
782 // N = N + Idx * ElementSize;
783 uint64_t ElementSize = TD.getTypeSize(Ty);
784 SDOperand IdxN = getValue(Idx);
786 // If the index is smaller or larger than intptr_t, truncate or extend
788 if (IdxN.getValueType() < N.getValueType()) {
789 if (Idx->getType()->isSigned())
790 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
792 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
793 } else if (IdxN.getValueType() > N.getValueType())
794 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
796 // If this is a multiply by a power of two, turn it into a shl
797 // immediately. This is a very common case.
798 if (isPowerOf2_64(ElementSize)) {
799 unsigned Amt = Log2_64(ElementSize);
800 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
801 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
802 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
806 SDOperand Scale = getIntPtrConstant(ElementSize);
807 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
808 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
814 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
815 // If this is a fixed sized alloca in the entry block of the function,
816 // allocate it statically on the stack.
817 if (FuncInfo.StaticAllocaMap.count(&I))
818 return; // getValue will auto-populate this.
820 const Type *Ty = I.getAllocatedType();
821 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
822 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
825 SDOperand AllocSize = getValue(I.getArraySize());
826 MVT::ValueType IntPtr = TLI.getPointerTy();
827 if (IntPtr < AllocSize.getValueType())
828 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
829 else if (IntPtr > AllocSize.getValueType())
830 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
832 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
833 getIntPtrConstant(TySize));
835 // Handle alignment. If the requested alignment is less than or equal to the
836 // stack alignment, ignore it and round the size of the allocation up to the
837 // stack alignment size. If the size is greater than the stack alignment, we
838 // note this in the DYNAMIC_STACKALLOC node.
839 unsigned StackAlign =
840 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
841 if (Align <= StackAlign) {
843 // Add SA-1 to the size.
844 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
845 getIntPtrConstant(StackAlign-1));
846 // Mask out the low bits for alignment purposes.
847 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
848 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
851 std::vector<MVT::ValueType> VTs;
852 VTs.push_back(AllocSize.getValueType());
853 VTs.push_back(MVT::Other);
854 std::vector<SDOperand> Ops;
855 Ops.push_back(getRoot());
856 Ops.push_back(AllocSize);
857 Ops.push_back(getIntPtrConstant(Align));
858 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
859 DAG.setRoot(setValue(&I, DSA).getValue(1));
861 // Inform the Frame Information that we have just allocated a variable-sized
863 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
866 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
867 /// global into a string value. Return an empty string if we can't do it.
869 static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
870 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
871 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
872 if (Init->isString()) {
873 std::string Result = Init->getAsString();
874 if (Offset < Result.size()) {
875 // If we are pointing INTO The string, erase the beginning...
876 Result.erase(Result.begin(), Result.begin()+Offset);
884 void SelectionDAGLowering::visitLoad(LoadInst &I) {
885 SDOperand Ptr = getValue(I.getOperand(0));
891 // Do not serialize non-volatile loads against each other.
892 Root = DAG.getRoot();
895 const Type *Ty = I.getType();
898 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
899 unsigned NumElements = PTy->getNumElements();
900 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
901 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
903 // Immediately scalarize packed types containing only one element, so that
904 // the Legalize pass does not have to deal with them.
905 if (NumElements == 1) {
906 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
907 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
908 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
910 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
911 DAG.getSrcValue(I.getOperand(0)));
914 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
915 DAG.getSrcValue(I.getOperand(0)));
920 DAG.setRoot(L.getValue(1));
922 PendingLoads.push_back(L.getValue(1));
926 void SelectionDAGLowering::visitStore(StoreInst &I) {
927 Value *SrcV = I.getOperand(0);
928 SDOperand Src = getValue(SrcV);
929 SDOperand Ptr = getValue(I.getOperand(1));
930 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
931 DAG.getSrcValue(I.getOperand(1))));
934 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
935 /// we want to emit this as a call to a named external function, return the name
936 /// otherwise lower it and return null.
938 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
940 case Intrinsic::vastart: visitVAStart(I); return 0;
941 case Intrinsic::vaend: visitVAEnd(I); return 0;
942 case Intrinsic::vacopy: visitVACopy(I); return 0;
943 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
944 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
945 case Intrinsic::setjmp:
946 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
948 case Intrinsic::longjmp:
949 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
951 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
952 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
953 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
955 case Intrinsic::readport:
956 case Intrinsic::readio: {
957 std::vector<MVT::ValueType> VTs;
958 VTs.push_back(TLI.getValueType(I.getType()));
959 VTs.push_back(MVT::Other);
960 std::vector<SDOperand> Ops;
961 Ops.push_back(getRoot());
962 Ops.push_back(getValue(I.getOperand(1)));
963 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
964 ISD::READPORT : ISD::READIO, VTs, Ops);
967 DAG.setRoot(Tmp.getValue(1));
970 case Intrinsic::writeport:
971 case Intrinsic::writeio:
972 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
973 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
974 getRoot(), getValue(I.getOperand(1)),
975 getValue(I.getOperand(2))));
978 case Intrinsic::dbg_stoppoint: {
979 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
980 return "llvm_debugger_stop";
982 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
983 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
984 std::vector<SDOperand> Ops;
987 Ops.push_back(getRoot());
990 Ops.push_back(getValue(I.getOperand(2)));
993 Ops.push_back(getValue(I.getOperand(3)));
995 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
996 assert(DD && "Not a debug information descriptor");
997 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
998 assert(CompileUnit && "Not a compile unit");
999 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1000 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1002 if (Ops.size() == 5) // Found filename/workingdir.
1003 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1006 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1009 case Intrinsic::dbg_region_start:
1010 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1011 return "llvm_dbg_region_start";
1012 if (I.getType() != Type::VoidTy)
1013 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1015 case Intrinsic::dbg_region_end:
1016 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1017 return "llvm_dbg_region_end";
1018 if (I.getType() != Type::VoidTy)
1019 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1021 case Intrinsic::dbg_func_start:
1022 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1023 return "llvm_dbg_subprogram";
1024 if (I.getType() != Type::VoidTy)
1025 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1027 case Intrinsic::dbg_declare:
1028 if (I.getType() != Type::VoidTy)
1029 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1032 case Intrinsic::isunordered_f32:
1033 case Intrinsic::isunordered_f64:
1034 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1035 getValue(I.getOperand(2)), ISD::SETUO));
1038 case Intrinsic::sqrt_f32:
1039 case Intrinsic::sqrt_f64:
1040 setValue(&I, DAG.getNode(ISD::FSQRT,
1041 getValue(I.getOperand(1)).getValueType(),
1042 getValue(I.getOperand(1))));
1044 case Intrinsic::pcmarker: {
1045 SDOperand Tmp = getValue(I.getOperand(1));
1046 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1049 case Intrinsic::readcyclecounter: {
1050 std::vector<MVT::ValueType> VTs;
1051 VTs.push_back(MVT::i64);
1052 VTs.push_back(MVT::Other);
1053 std::vector<SDOperand> Ops;
1054 Ops.push_back(getRoot());
1055 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1057 DAG.setRoot(Tmp.getValue(1));
1060 case Intrinsic::bswap_i16:
1061 case Intrinsic::bswap_i32:
1062 case Intrinsic::bswap_i64:
1063 setValue(&I, DAG.getNode(ISD::BSWAP,
1064 getValue(I.getOperand(1)).getValueType(),
1065 getValue(I.getOperand(1))));
1067 case Intrinsic::cttz_i8:
1068 case Intrinsic::cttz_i16:
1069 case Intrinsic::cttz_i32:
1070 case Intrinsic::cttz_i64:
1071 setValue(&I, DAG.getNode(ISD::CTTZ,
1072 getValue(I.getOperand(1)).getValueType(),
1073 getValue(I.getOperand(1))));
1075 case Intrinsic::ctlz_i8:
1076 case Intrinsic::ctlz_i16:
1077 case Intrinsic::ctlz_i32:
1078 case Intrinsic::ctlz_i64:
1079 setValue(&I, DAG.getNode(ISD::CTLZ,
1080 getValue(I.getOperand(1)).getValueType(),
1081 getValue(I.getOperand(1))));
1083 case Intrinsic::ctpop_i8:
1084 case Intrinsic::ctpop_i16:
1085 case Intrinsic::ctpop_i32:
1086 case Intrinsic::ctpop_i64:
1087 setValue(&I, DAG.getNode(ISD::CTPOP,
1088 getValue(I.getOperand(1)).getValueType(),
1089 getValue(I.getOperand(1))));
1091 case Intrinsic::stacksave: {
1092 std::vector<MVT::ValueType> VTs;
1093 VTs.push_back(TLI.getPointerTy());
1094 VTs.push_back(MVT::Other);
1095 std::vector<SDOperand> Ops;
1096 Ops.push_back(getRoot());
1097 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1099 DAG.setRoot(Tmp.getValue(1));
1102 case Intrinsic::stackrestore: {
1103 SDOperand Tmp = getValue(I.getOperand(1));
1104 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1107 case Intrinsic::prefetch:
1108 // FIXME: Currently discarding prefetches.
1112 assert(0 && "This intrinsic is not implemented yet!");
1118 void SelectionDAGLowering::visitCall(CallInst &I) {
1119 const char *RenameFn = 0;
1120 if (Function *F = I.getCalledFunction()) {
1121 if (F->isExternal())
1122 if (unsigned IID = F->getIntrinsicID()) {
1123 RenameFn = visitIntrinsicCall(I, IID);
1126 } else { // Not an LLVM intrinsic.
1127 const std::string &Name = F->getName();
1128 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1129 if (I.getNumOperands() == 2 && // Basic sanity checks.
1130 I.getOperand(1)->getType()->isFloatingPoint() &&
1131 I.getType() == I.getOperand(1)->getType()) {
1132 SDOperand Tmp = getValue(I.getOperand(1));
1133 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1136 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1137 if (I.getNumOperands() == 2 && // Basic sanity checks.
1138 I.getOperand(1)->getType()->isFloatingPoint() &&
1139 I.getType() == I.getOperand(1)->getType()) {
1140 SDOperand Tmp = getValue(I.getOperand(1));
1141 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1144 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1145 if (I.getNumOperands() == 2 && // Basic sanity checks.
1146 I.getOperand(1)->getType()->isFloatingPoint() &&
1147 I.getType() == I.getOperand(1)->getType()) {
1148 SDOperand Tmp = getValue(I.getOperand(1));
1149 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1154 } else if (isa<InlineAsm>(I.getOperand(0))) {
1161 Callee = getValue(I.getOperand(0));
1163 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1164 std::vector<std::pair<SDOperand, const Type*> > Args;
1165 Args.reserve(I.getNumOperands());
1166 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1167 Value *Arg = I.getOperand(i);
1168 SDOperand ArgNode = getValue(Arg);
1169 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1172 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1173 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1175 std::pair<SDOperand,SDOperand> Result =
1176 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1177 I.isTailCall(), Callee, Args, DAG);
1178 if (I.getType() != Type::VoidTy)
1179 setValue(&I, Result.first);
1180 DAG.setRoot(Result.second);
1183 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1184 SDOperand &Chain, SDOperand &Flag) {
1185 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1186 Chain = Val.getValue(1);
1187 Flag = Val.getValue(2);
1189 // If the result was expanded, copy from the top part.
1190 if (Regs.size() > 1) {
1191 assert(Regs.size() == 2 &&
1192 "Cannot expand to more than 2 elts yet!");
1193 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1194 Chain = Val.getValue(1);
1195 Flag = Val.getValue(2);
1196 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1199 // Otherwise, if the return value was promoted, truncate it to the
1200 // appropriate type.
1201 if (RegVT == ValueVT)
1204 if (MVT::isInteger(RegVT))
1205 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1207 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1210 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1211 /// specified value into the registers specified by this object. This uses
1212 /// Chain/Flag as the input and updates them for the output Chain/Flag.
1213 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1214 SDOperand &Chain, SDOperand &Flag) {
1215 if (Regs.size() == 1) {
1216 // If there is a single register and the types differ, this must be
1218 if (RegVT != ValueVT) {
1219 if (MVT::isInteger(RegVT))
1220 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1222 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1224 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1225 Flag = Chain.getValue(1);
1227 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1228 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1229 DAG.getConstant(i, MVT::i32));
1230 Chain = DAG.getCopyToReg(Chain, Regs[i], Part, Flag);
1231 Flag = Chain.getValue(1);
1236 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
1237 /// operand list. This adds the code marker and includes the number of
1238 /// values added into it.
1239 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1240 std::vector<SDOperand> &Ops) {
1241 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1242 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1243 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1246 /// isAllocatableRegister - If the specified register is safe to allocate,
1247 /// i.e. it isn't a stack pointer or some other special register, return the
1248 /// register class for the register. Otherwise, return null.
1249 static const TargetRegisterClass *
1250 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1251 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1252 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1253 E = MRI->regclass_end(); RCI != E; ++RCI) {
1254 const TargetRegisterClass *RC = *RCI;
1255 // If none of the the value types for this register class are valid, we
1256 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1257 bool isLegal = false;
1258 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1260 if (TLI.isTypeLegal(*I)) {
1266 if (!isLegal) continue;
1268 // NOTE: This isn't ideal. In particular, this might allocate the
1269 // frame pointer in functions that need it (due to them not being taken
1270 // out of allocation, because a variable sized allocation hasn't been seen
1271 // yet). This is a slight code pessimization, but should still work.
1272 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1273 E = RC->allocation_order_end(MF); I != E; ++I)
1280 RegsForValue SelectionDAGLowering::
1281 GetRegistersForValue(const std::string &ConstrCode,
1282 MVT::ValueType VT, bool isOutReg, bool isInReg,
1283 std::set<unsigned> &OutputRegs,
1284 std::set<unsigned> &InputRegs) {
1285 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1286 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1287 std::vector<unsigned> Regs;
1289 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1290 MVT::ValueType RegVT;
1291 MVT::ValueType ValueVT = VT;
1293 if (PhysReg.first) {
1294 if (VT == MVT::Other)
1295 ValueVT = *PhysReg.second->vt_begin();
1298 // This is a explicit reference to a physical register.
1299 Regs.push_back(PhysReg.first);
1301 // If this is an expanded reference, add the rest of the regs to Regs.
1303 RegVT = *PhysReg.second->vt_begin();
1304 TargetRegisterClass::iterator I = PhysReg.second->begin();
1305 TargetRegisterClass::iterator E = PhysReg.second->end();
1306 for (; *I != PhysReg.first; ++I)
1307 assert(I != E && "Didn't find reg!");
1309 // Already added the first reg.
1311 for (; NumRegs; --NumRegs, ++I) {
1312 assert(I != E && "Ran out of registers to allocate!");
1316 return RegsForValue(Regs, RegVT, ValueVT);
1319 // This is a reference to a register class. Allocate NumRegs consecutive,
1320 // available, registers from the class.
1321 std::vector<unsigned> RegClassRegs =
1322 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1324 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1325 MachineFunction &MF = *CurMBB->getParent();
1326 unsigned NumAllocated = 0;
1327 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1328 unsigned Reg = RegClassRegs[i];
1329 // See if this register is available.
1330 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1331 (isInReg && InputRegs.count(Reg))) { // Already used.
1332 // Make sure we find consecutive registers.
1337 // Check to see if this register is allocatable (i.e. don't give out the
1339 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1341 // Make sure we find consecutive registers.
1346 // Okay, this register is good, we can use it.
1349 // If we allocated enough consecutive
1350 if (NumAllocated == NumRegs) {
1351 unsigned RegStart = (i-NumAllocated)+1;
1352 unsigned RegEnd = i+1;
1353 // Mark all of the allocated registers used.
1354 for (unsigned i = RegStart; i != RegEnd; ++i) {
1355 unsigned Reg = RegClassRegs[i];
1356 Regs.push_back(Reg);
1357 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1358 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1361 return RegsForValue(Regs, *RC->vt_begin(), VT);
1365 // Otherwise, we couldn't allocate enough registers for this.
1366 return RegsForValue();
1370 /// visitInlineAsm - Handle a call to an InlineAsm object.
1372 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1373 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1375 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1378 // Note, we treat inline asms both with and without side-effects as the same.
1379 // If an inline asm doesn't have side effects and doesn't access memory, we
1380 // could not choose to not chain it.
1381 bool hasSideEffects = IA->hasSideEffects();
1383 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1384 std::vector<MVT::ValueType> ConstraintVTs;
1386 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1387 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1388 /// if it is a def of that register.
1389 std::vector<SDOperand> AsmNodeOperands;
1390 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1391 AsmNodeOperands.push_back(AsmStr);
1393 SDOperand Chain = getRoot();
1396 // We fully assign registers here at isel time. This is not optimal, but
1397 // should work. For register classes that correspond to LLVM classes, we
1398 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1399 // over the constraints, collecting fixed registers that we know we can't use.
1400 std::set<unsigned> OutputRegs, InputRegs;
1402 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1403 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1404 std::string &ConstraintCode = Constraints[i].Codes[0];
1406 MVT::ValueType OpVT;
1408 // Compute the value type for each operand and add it to ConstraintVTs.
1409 switch (Constraints[i].Type) {
1410 case InlineAsm::isOutput:
1411 if (!Constraints[i].isIndirectOutput) {
1412 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1413 OpVT = TLI.getValueType(I.getType());
1415 Value *CallOperand = I.getOperand(OpNum);
1416 const Type *OpTy = CallOperand->getType();
1417 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1418 OpNum++; // Consumes a call operand.
1421 case InlineAsm::isInput:
1422 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1423 OpNum++; // Consumes a call operand.
1425 case InlineAsm::isClobber:
1430 ConstraintVTs.push_back(OpVT);
1432 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1433 continue; // Not assigned a fixed reg.
1435 // Build a list of regs that this operand uses. This always has a single
1436 // element for promoted/expanded operands.
1437 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1439 OutputRegs, InputRegs);
1441 switch (Constraints[i].Type) {
1442 case InlineAsm::isOutput:
1443 // We can't assign any other output to this register.
1444 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1445 // If this is an early-clobber output, it cannot be assigned to the same
1446 // value as the input reg.
1447 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1448 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1450 case InlineAsm::isInput:
1451 // We can't assign any other input to this register.
1452 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1454 case InlineAsm::isClobber:
1455 // Clobbered regs cannot be used as inputs or outputs.
1456 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1457 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1462 // Loop over all of the inputs, copying the operand values into the
1463 // appropriate registers and processing the output regs.
1464 RegsForValue RetValRegs;
1465 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
1468 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1469 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1470 std::string &ConstraintCode = Constraints[i].Codes[0];
1472 switch (Constraints[i].Type) {
1473 case InlineAsm::isOutput: {
1474 // If this is an early-clobber output, or if there is an input
1475 // constraint that matches this, we need to reserve the input register
1476 // so no other inputs allocate to it.
1477 bool UsesInputRegister = false;
1478 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1479 UsesInputRegister = true;
1481 // Copy the output from the appropriate register. Find a register that
1484 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1485 true, UsesInputRegister,
1486 OutputRegs, InputRegs);
1487 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
1489 if (!Constraints[i].isIndirectOutput) {
1490 assert(RetValRegs.Regs.empty() &&
1491 "Cannot have multiple output constraints yet!");
1492 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1495 Value *CallOperand = I.getOperand(OpNum);
1496 IndirectStoresToEmit.push_back(std::make_pair(Regs, CallOperand));
1497 OpNum++; // Consumes a call operand.
1500 // Add information to the INLINEASM node to know that this register is
1502 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
1505 case InlineAsm::isInput: {
1506 Value *CallOperand = I.getOperand(OpNum);
1507 OpNum++; // Consumes a call operand.
1509 SDOperand InOperandVal = getValue(CallOperand);
1511 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1512 // If this is required to match an output register we have already set,
1513 // just use its register.
1514 unsigned OperandNo = atoi(ConstraintCode.c_str());
1516 // Scan until we find the definition we already emitted of this operand.
1517 // When we find it, create a RegsForValue operand.
1518 unsigned CurOp = 2; // The first operand.
1519 for (; OperandNo; --OperandNo) {
1520 // Advance to the next operand.
1522 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1523 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1524 "Skipped past definitions?");
1525 CurOp += (NumOps>>3)+1;
1529 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1530 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1531 "Skipped past definitions?");
1533 // Add NumOps>>3 registers to MatchedRegs.
1534 RegsForValue MatchedRegs;
1535 MatchedRegs.ValueVT = InOperandVal.getValueType();
1536 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1537 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1538 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1539 MatchedRegs.Regs.push_back(Reg);
1542 // Use the produced MatchedRegs object to
1543 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1544 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
1546 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1547 if (ConstraintCode.size() == 1) // not a physreg name.
1548 CTy = TLI.getConstraintType(ConstraintCode[0]);
1550 if (CTy == TargetLowering::C_Other) {
1551 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1552 assert(0 && "MATCH FAIL!");
1554 // Add information to the INLINEASM node to know about this input.
1555 unsigned ResOpType = 3 /*imm*/ | (1 << 3);
1556 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1557 AsmNodeOperands.push_back(InOperandVal);
1561 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1563 // Copy the input into the appropriate registers.
1564 RegsForValue InRegs =
1565 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1566 false, true, OutputRegs, InputRegs);
1567 // FIXME: should be match fail.
1568 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1570 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1572 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
1577 case InlineAsm::isClobber: {
1578 RegsForValue ClobberedRegs =
1579 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1580 OutputRegs, InputRegs);
1581 // Add the clobbered value to the operand list, so that the register
1582 // allocator is aware that the physreg got clobbered.
1583 if (!ClobberedRegs.Regs.empty())
1584 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
1590 // Finish up input operands.
1591 AsmNodeOperands[0] = Chain;
1592 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1594 std::vector<MVT::ValueType> VTs;
1595 VTs.push_back(MVT::Other);
1596 VTs.push_back(MVT::Flag);
1597 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1598 Flag = Chain.getValue(1);
1600 // If this asm returns a register value, copy the result from that register
1601 // and set it as the value of the call.
1602 if (!RetValRegs.Regs.empty())
1603 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
1605 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1607 // Process indirect outputs, first output all of the flagged copies out of
1609 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
1610 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
1611 Value *Ptr = IndirectStoresToEmit[i].second;
1612 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1613 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
1616 // Emit the non-flagged stores from the physregs.
1617 std::vector<SDOperand> OutChains;
1618 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1619 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1620 StoresToEmit[i].first,
1621 getValue(StoresToEmit[i].second),
1622 DAG.getSrcValue(StoresToEmit[i].second)));
1623 if (!OutChains.empty())
1624 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
1629 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1630 SDOperand Src = getValue(I.getOperand(0));
1632 MVT::ValueType IntPtr = TLI.getPointerTy();
1634 if (IntPtr < Src.getValueType())
1635 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1636 else if (IntPtr > Src.getValueType())
1637 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
1639 // Scale the source by the type size.
1640 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1641 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1642 Src, getIntPtrConstant(ElementSize));
1644 std::vector<std::pair<SDOperand, const Type*> > Args;
1645 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
1647 std::pair<SDOperand,SDOperand> Result =
1648 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
1649 DAG.getExternalSymbol("malloc", IntPtr),
1651 setValue(&I, Result.first); // Pointers always fit in registers
1652 DAG.setRoot(Result.second);
1655 void SelectionDAGLowering::visitFree(FreeInst &I) {
1656 std::vector<std::pair<SDOperand, const Type*> > Args;
1657 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1658 TLI.getTargetData().getIntPtrType()));
1659 MVT::ValueType IntPtr = TLI.getPointerTy();
1660 std::pair<SDOperand,SDOperand> Result =
1661 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
1662 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1663 DAG.setRoot(Result.second);
1666 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
1667 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1668 // instructions are special in various ways, which require special support to
1669 // insert. The specified MachineInstr is created but not inserted into any
1670 // basic blocks, and the scheduler passes ownership of it to this method.
1671 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1672 MachineBasicBlock *MBB) {
1673 std::cerr << "If a target marks an instruction with "
1674 "'usesCustomDAGSchedInserter', it must implement "
1675 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1680 void SelectionDAGLowering::visitVAStart(CallInst &I) {
1681 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1682 getValue(I.getOperand(1)),
1683 DAG.getSrcValue(I.getOperand(1))));
1686 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1687 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1688 getValue(I.getOperand(0)),
1689 DAG.getSrcValue(I.getOperand(0)));
1691 DAG.setRoot(V.getValue(1));
1694 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
1695 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1696 getValue(I.getOperand(1)),
1697 DAG.getSrcValue(I.getOperand(1))));
1700 void SelectionDAGLowering::visitVACopy(CallInst &I) {
1701 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1702 getValue(I.getOperand(1)),
1703 getValue(I.getOperand(2)),
1704 DAG.getSrcValue(I.getOperand(1)),
1705 DAG.getSrcValue(I.getOperand(2))));
1708 // It is always conservatively correct for llvm.returnaddress and
1709 // llvm.frameaddress to return 0.
1710 std::pair<SDOperand, SDOperand>
1711 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1712 unsigned Depth, SelectionDAG &DAG) {
1713 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
1716 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1717 assert(0 && "LowerOperation not implemented for this target!");
1722 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1723 SelectionDAG &DAG) {
1724 assert(0 && "CustomPromoteOperation not implemented for this target!");
1729 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1730 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1731 std::pair<SDOperand,SDOperand> Result =
1732 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
1733 setValue(&I, Result.first);
1734 DAG.setRoot(Result.second);
1737 /// getMemsetValue - Vectorized representation of the memset value
1739 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
1740 SelectionDAG &DAG) {
1741 MVT::ValueType CurVT = VT;
1742 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1743 uint64_t Val = C->getValue() & 255;
1745 while (CurVT != MVT::i8) {
1746 Val = (Val << Shift) | Val;
1748 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
1750 return DAG.getConstant(Val, VT);
1752 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1754 while (CurVT != MVT::i8) {
1756 DAG.getNode(ISD::OR, VT,
1757 DAG.getNode(ISD::SHL, VT, Value,
1758 DAG.getConstant(Shift, MVT::i8)), Value);
1760 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
1767 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1768 /// used when a memcpy is turned into a memset when the source is a constant
1770 static SDOperand getMemsetStringVal(MVT::ValueType VT,
1771 SelectionDAG &DAG, TargetLowering &TLI,
1772 std::string &Str, unsigned Offset) {
1773 MVT::ValueType CurVT = VT;
1775 unsigned MSB = getSizeInBits(VT) / 8;
1776 if (TLI.isLittleEndian())
1777 Offset = Offset + MSB - 1;
1778 for (unsigned i = 0; i != MSB; ++i) {
1779 Val = (Val << 8) | Str[Offset];
1780 Offset += TLI.isLittleEndian() ? -1 : 1;
1782 return DAG.getConstant(Val, VT);
1785 /// getMemBasePlusOffset - Returns base and offset node for the
1786 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1787 SelectionDAG &DAG, TargetLowering &TLI) {
1788 MVT::ValueType VT = Base.getValueType();
1789 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1792 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
1793 /// to replace the memset / memcpy is below the threshold. It also returns the
1794 /// types of the sequence of memory ops to perform memset / memcpy.
1795 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1796 unsigned Limit, uint64_t Size,
1797 unsigned Align, TargetLowering &TLI) {
1800 if (TLI.allowsUnalignedMemoryAccesses()) {
1803 switch (Align & 7) {
1819 MVT::ValueType LVT = MVT::i64;
1820 while (!TLI.isTypeLegal(LVT))
1821 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1822 assert(MVT::isInteger(LVT));
1827 unsigned NumMemOps = 0;
1829 unsigned VTSize = getSizeInBits(VT) / 8;
1830 while (VTSize > Size) {
1831 VT = (MVT::ValueType)((unsigned)VT - 1);
1834 assert(MVT::isInteger(VT));
1836 if (++NumMemOps > Limit)
1838 MemOps.push_back(VT);
1845 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1846 SDOperand Op1 = getValue(I.getOperand(1));
1847 SDOperand Op2 = getValue(I.getOperand(2));
1848 SDOperand Op3 = getValue(I.getOperand(3));
1849 SDOperand Op4 = getValue(I.getOperand(4));
1850 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1851 if (Align == 0) Align = 1;
1853 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1854 std::vector<MVT::ValueType> MemOps;
1856 // Expand memset / memcpy to a series of load / store ops
1857 // if the size operand falls below a certain threshold.
1858 std::vector<SDOperand> OutChains;
1860 default: break; // Do nothing for now.
1862 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1863 Size->getValue(), Align, TLI)) {
1864 unsigned NumMemOps = MemOps.size();
1865 unsigned Offset = 0;
1866 for (unsigned i = 0; i < NumMemOps; i++) {
1867 MVT::ValueType VT = MemOps[i];
1868 unsigned VTSize = getSizeInBits(VT) / 8;
1869 SDOperand Value = getMemsetValue(Op2, VT, DAG);
1870 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1872 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1873 DAG.getSrcValue(I.getOperand(1), Offset));
1874 OutChains.push_back(Store);
1881 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1882 Size->getValue(), Align, TLI)) {
1883 unsigned NumMemOps = MemOps.size();
1884 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
1885 GlobalAddressSDNode *G = NULL;
1887 bool CopyFromStr = false;
1889 if (Op2.getOpcode() == ISD::GlobalAddress)
1890 G = cast<GlobalAddressSDNode>(Op2);
1891 else if (Op2.getOpcode() == ISD::ADD &&
1892 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1893 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1894 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
1895 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
1898 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
1900 Str = getStringValue(GV);
1908 for (unsigned i = 0; i < NumMemOps; i++) {
1909 MVT::ValueType VT = MemOps[i];
1910 unsigned VTSize = getSizeInBits(VT) / 8;
1911 SDOperand Value, Chain, Store;
1914 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1917 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1918 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1919 DAG.getSrcValue(I.getOperand(1), DstOff));
1921 Value = DAG.getLoad(VT, getRoot(),
1922 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1923 DAG.getSrcValue(I.getOperand(2), SrcOff));
1924 Chain = Value.getValue(1);
1926 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1927 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1928 DAG.getSrcValue(I.getOperand(1), DstOff));
1930 OutChains.push_back(Store);
1939 if (!OutChains.empty()) {
1940 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1945 std::vector<SDOperand> Ops;
1946 Ops.push_back(getRoot());
1951 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1954 //===----------------------------------------------------------------------===//
1955 // SelectionDAGISel code
1956 //===----------------------------------------------------------------------===//
1958 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1959 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1962 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1963 // FIXME: we only modify the CFG to split critical edges. This
1964 // updates dom and loop info.
1968 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1969 /// casting to the type of GEPI.
1970 static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1971 Value *Ptr, Value *PtrOffset) {
1972 if (V) return V; // Already computed.
1974 BasicBlock::iterator InsertPt;
1975 if (BB == GEPI->getParent()) {
1976 // If insert into the GEP's block, insert right after the GEP.
1980 // Otherwise, insert at the top of BB, after any PHI nodes
1981 InsertPt = BB->begin();
1982 while (isa<PHINode>(InsertPt)) ++InsertPt;
1985 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1986 // BB so that there is only one value live across basic blocks (the cast
1988 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1989 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1990 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1992 // Add the offset, cast it to the right type.
1993 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1994 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1999 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2000 /// selection, we want to be a bit careful about some things. In particular, if
2001 /// we have a GEP instruction that is used in a different block than it is
2002 /// defined, the addressing expression of the GEP cannot be folded into loads or
2003 /// stores that use it. In this case, decompose the GEP and move constant
2004 /// indices into blocks that use it.
2005 static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2006 const TargetData &TD) {
2007 // If this GEP is only used inside the block it is defined in, there is no
2008 // need to rewrite it.
2009 bool isUsedOutsideDefBB = false;
2010 BasicBlock *DefBB = GEPI->getParent();
2011 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2013 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2014 isUsedOutsideDefBB = true;
2018 if (!isUsedOutsideDefBB) return;
2020 // If this GEP has no non-zero constant indices, there is nothing we can do,
2022 bool hasConstantIndex = false;
2023 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2024 E = GEPI->op_end(); OI != E; ++OI) {
2025 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2026 if (CI->getRawValue()) {
2027 hasConstantIndex = true;
2031 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2032 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
2034 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2035 // constant offset (which we now know is non-zero) and deal with it later.
2036 uint64_t ConstantOffset = 0;
2037 const Type *UIntPtrTy = TD.getIntPtrType();
2038 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2039 const Type *Ty = GEPI->getOperand(0)->getType();
2041 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2042 E = GEPI->op_end(); OI != E; ++OI) {
2044 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2045 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2047 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2048 Ty = StTy->getElementType(Field);
2050 Ty = cast<SequentialType>(Ty)->getElementType();
2052 // Handle constant subscripts.
2053 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2054 if (CI->getRawValue() == 0) continue;
2056 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2057 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2059 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2063 // Ptr = Ptr + Idx * ElementSize;
2065 // Cast Idx to UIntPtrTy if needed.
2066 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2068 uint64_t ElementSize = TD.getTypeSize(Ty);
2069 // Mask off bits that should not be set.
2070 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2071 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2073 // Multiply by the element size and add to the base.
2074 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2075 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2079 // Make sure that the offset fits in uintptr_t.
2080 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2081 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2083 // Okay, we have now emitted all of the variable index parts to the BB that
2084 // the GEP is defined in. Loop over all of the using instructions, inserting
2085 // an "add Ptr, ConstantOffset" into each block that uses it and update the
2086 // instruction to use the newly computed value, making GEPI dead. When the
2087 // user is a load or store instruction address, we emit the add into the user
2088 // block, otherwise we use a canonical version right next to the gep (these
2089 // won't be foldable as addresses, so we might as well share the computation).
2091 std::map<BasicBlock*,Value*> InsertedExprs;
2092 while (!GEPI->use_empty()) {
2093 Instruction *User = cast<Instruction>(GEPI->use_back());
2095 // If this use is not foldable into the addressing mode, use a version
2096 // emitted in the GEP block.
2098 if (!isa<LoadInst>(User) &&
2099 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2100 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2103 // Otherwise, insert the code in the User's block so it can be folded into
2104 // any users in that block.
2105 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
2106 User->getParent(), GEPI,
2109 User->replaceUsesOfWith(GEPI, NewVal);
2112 // Finally, the GEP is dead, remove it.
2113 GEPI->eraseFromParent();
2116 bool SelectionDAGISel::runOnFunction(Function &Fn) {
2117 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2118 RegMap = MF.getSSARegMap();
2119 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2121 // First, split all critical edges for PHI nodes with incoming values that are
2122 // constants, this way the load of the constant into a vreg will not be placed
2123 // into MBBs that are used some other way.
2125 // In this pass we also look for GEP instructions that are used across basic
2126 // blocks and rewrites them to improve basic-block-at-a-time selection.
2128 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2130 BasicBlock::iterator BBI;
2131 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
2132 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2133 if (isa<Constant>(PN->getIncomingValue(i)))
2134 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
2136 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2137 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2138 OptimizeGEPExpression(GEPI, TLI.getTargetData());
2141 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2143 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2144 SelectBasicBlock(I, MF, FuncInfo);
2150 SDOperand SelectionDAGISel::
2151 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
2152 SDOperand Op = SDL.getValue(V);
2153 assert((Op.getOpcode() != ISD::CopyFromReg ||
2154 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
2155 "Copy from a reg to the same reg!");
2157 // If this type is not legal, we must make sure to not create an invalid
2159 MVT::ValueType SrcVT = Op.getValueType();
2160 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2161 SelectionDAG &DAG = SDL.DAG;
2162 if (SrcVT == DestVT) {
2163 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2164 } else if (SrcVT < DestVT) {
2165 // The src value is promoted to the register.
2166 if (MVT::isFloatingPoint(SrcVT))
2167 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2169 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
2170 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2172 // The src value is expanded into multiple registers.
2173 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2174 Op, DAG.getConstant(0, MVT::i32));
2175 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2176 Op, DAG.getConstant(1, MVT::i32));
2177 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2178 return DAG.getCopyToReg(Op, Reg+1, Hi);
2182 void SelectionDAGISel::
2183 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2184 std::vector<SDOperand> &UnorderedChains) {
2185 // If this is the entry block, emit arguments.
2186 Function &F = *BB->getParent();
2187 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
2188 SDOperand OldRoot = SDL.DAG.getRoot();
2189 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
2192 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2194 if (!AI->use_empty()) {
2195 SDL.setValue(AI, Args[a]);
2197 // If this argument is live outside of the entry block, insert a copy from
2198 // whereever we got it to the vreg that other BB's will reference it as.
2199 if (FuncInfo.ValueMap.count(AI)) {
2201 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2202 UnorderedChains.push_back(Copy);
2206 // Next, if the function has live ins that need to be copied into vregs,
2207 // emit the copies now, into the top of the block.
2208 MachineFunction &MF = SDL.DAG.getMachineFunction();
2209 if (MF.livein_begin() != MF.livein_end()) {
2210 SSARegMap *RegMap = MF.getSSARegMap();
2211 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2212 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2213 E = MF.livein_end(); LI != E; ++LI)
2215 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2216 LI->first, RegMap->getRegClass(LI->second));
2219 // Finally, if the target has anything special to do, allow it to do so.
2220 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
2224 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2225 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2226 FunctionLoweringInfo &FuncInfo) {
2227 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
2229 std::vector<SDOperand> UnorderedChains;
2231 // Lower any arguments needed in this block if this is the entry block.
2232 if (LLVMBB == &LLVMBB->getParent()->front())
2233 LowerArguments(LLVMBB, SDL, UnorderedChains);
2235 BB = FuncInfo.MBBMap[LLVMBB];
2236 SDL.setCurrentBasicBlock(BB);
2238 // Lower all of the non-terminator instructions.
2239 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2243 // Ensure that all instructions which are used outside of their defining
2244 // blocks are available as virtual registers.
2245 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
2246 if (!I->use_empty() && !isa<PHINode>(I)) {
2247 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
2248 if (VMI != FuncInfo.ValueMap.end())
2249 UnorderedChains.push_back(
2250 CopyValueToVirtualRegister(SDL, I, VMI->second));
2253 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2254 // ensure constants are generated when needed. Remember the virtual registers
2255 // that need to be added to the Machine PHI nodes as input. We cannot just
2256 // directly add them, because expansion might result in multiple MBB's for one
2257 // BB. As such, the start of the BB might correspond to a different MBB than
2261 // Emit constants only once even if used by multiple PHI nodes.
2262 std::map<Constant*, unsigned> ConstantsOut;
2264 // Check successor nodes PHI nodes that expect a constant to be available from
2266 TerminatorInst *TI = LLVMBB->getTerminator();
2267 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2268 BasicBlock *SuccBB = TI->getSuccessor(succ);
2269 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2272 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2273 // nodes and Machine PHI nodes, but the incoming operands have not been
2275 for (BasicBlock::iterator I = SuccBB->begin();
2276 (PN = dyn_cast<PHINode>(I)); ++I)
2277 if (!PN->use_empty()) {
2279 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2280 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2281 unsigned &RegOut = ConstantsOut[C];
2283 RegOut = FuncInfo.CreateRegForValue(C);
2284 UnorderedChains.push_back(
2285 CopyValueToVirtualRegister(SDL, C, RegOut));
2289 Reg = FuncInfo.ValueMap[PHIOp];
2291 assert(isa<AllocaInst>(PHIOp) &&
2292 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2293 "Didn't codegen value into a register!??");
2294 Reg = FuncInfo.CreateRegForValue(PHIOp);
2295 UnorderedChains.push_back(
2296 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
2300 // Remember that this register needs to added to the machine PHI node as
2301 // the input for this MBB.
2302 unsigned NumElements =
2303 TLI.getNumElements(TLI.getValueType(PN->getType()));
2304 for (unsigned i = 0, e = NumElements; i != e; ++i)
2305 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
2308 ConstantsOut.clear();
2310 // Turn all of the unordered chains into one factored node.
2311 if (!UnorderedChains.empty()) {
2312 SDOperand Root = SDL.getRoot();
2313 if (Root.getOpcode() != ISD::EntryToken) {
2314 unsigned i = 0, e = UnorderedChains.size();
2315 for (; i != e; ++i) {
2316 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2317 if (UnorderedChains[i].Val->getOperand(0) == Root)
2318 break; // Don't add the root if we already indirectly depend on it.
2322 UnorderedChains.push_back(Root);
2324 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2327 // Lower the terminator after the copies are emitted.
2328 SDL.visit(*LLVMBB->getTerminator());
2330 // Make sure the root of the DAG is up-to-date.
2331 DAG.setRoot(SDL.getRoot());
2334 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2335 FunctionLoweringInfo &FuncInfo) {
2336 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2338 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2340 // First step, lower LLVM code to some DAG. This DAG may use operations and
2341 // types that are not supported by the target.
2342 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2344 // Run the DAG combiner in pre-legalize mode.
2347 DEBUG(std::cerr << "Lowered selection DAG:\n");
2350 // Second step, hack on the DAG until it only uses operations and types that
2351 // the target supports.
2354 DEBUG(std::cerr << "Legalized selection DAG:\n");
2357 // Run the DAG combiner in post-legalize mode.
2360 if (ViewISelDAGs) DAG.viewGraph();
2362 // Third, instruction select all of the operations to machine code, adding the
2363 // code to the MachineBasicBlock.
2364 InstructionSelectBasicBlock(DAG);
2366 DEBUG(std::cerr << "Selected machine code:\n");
2369 // Next, now that we know what the last MBB the LLVM BB expanded is, update
2370 // PHI nodes in successors.
2371 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2372 MachineInstr *PHI = PHINodesToUpdate[i].first;
2373 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2374 "This is not a machine PHI node that we are updating!");
2375 PHI->addRegOperand(PHINodesToUpdate[i].second);
2376 PHI->addMachineBasicBlockOperand(BB);
2379 // Finally, add the CFG edges from the last selected MBB to the successor
2381 TerminatorInst *TI = LLVMBB->getTerminator();
2382 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2383 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2384 BB->addSuccessor(Succ0MBB);
2388 //===----------------------------------------------------------------------===//
2389 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2390 /// target node in the graph.
2391 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2392 if (ViewSchedDAGs) DAG.viewGraph();
2393 ScheduleDAG *SL = NULL;
2395 switch (ISHeuristic) {
2396 default: assert(0 && "Unrecognized scheduling heuristic");
2397 case defaultScheduling:
2398 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2399 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2400 else /* TargetLowering::SchedulingForRegPressure */
2401 SL = createBURRListDAGScheduler(DAG, BB);
2404 case simpleScheduling:
2405 case simpleNoItinScheduling:
2406 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2408 case listSchedulingBURR:
2409 SL = createBURRListDAGScheduler(DAG, BB);