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/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SSARegMap.h"
34 #include "llvm/Target/MRegisterInfo.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetFrameInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Debug.h"
52 ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
55 ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
58 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
62 cl::opt<ScheduleDAG::SchedHeuristics>
65 cl::desc("Choose scheduling style"),
66 cl::init(ScheduleDAG::defaultScheduling),
68 clEnumValN(ScheduleDAG::defaultScheduling, "default",
69 "Target preferred scheduling style"),
70 clEnumValN(ScheduleDAG::noScheduling, "none",
71 "No scheduling: breadth first sequencing"),
72 clEnumValN(ScheduleDAG::simpleScheduling, "simple",
73 "Simple two pass scheduling: minimize critical path "
74 "and maximize processor utilization"),
75 clEnumValN(ScheduleDAG::simpleNoItinScheduling, "simple-noitin",
76 "Simple two pass scheduling: Same as simple "
77 "except using generic latency"),
78 clEnumValN(ScheduleDAG::listSchedulingBURR, "list-burr",
79 "Bottom-up register reduction list scheduling"),
80 clEnumValN(ScheduleDAG::listSchedulingTDRR, "list-tdrr",
81 "Top-down register reduction list scheduling"),
82 clEnumValN(ScheduleDAG::listSchedulingTD, "list-td",
83 "Top-down list scheduler"),
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
93 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
96 std::vector<unsigned> Regs;
98 /// RegVT - The value type of each register.
100 MVT::ValueType RegVT;
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
112 RegsForValue(const std::vector<unsigned> ®s,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
121 SDOperand &Chain, SDOperand &Flag) const;
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
127 SDOperand &Chain, SDOperand &Flag) const;
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
133 std::vector<SDOperand> &Ops) const;
138 //===--------------------------------------------------------------------===//
139 /// FunctionLoweringInfo - This contains information that is global to a
140 /// function that is used when lowering a region of the function.
141 class FunctionLoweringInfo {
148 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
150 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
151 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
153 /// ValueMap - Since we emit code for the function a basic block at a time,
154 /// we must remember which virtual registers hold the values for
155 /// cross-basic-block values.
156 std::map<const Value*, unsigned> ValueMap;
158 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
159 /// the entry block. This allows the allocas to be efficiently referenced
160 /// anywhere in the function.
161 std::map<const AllocaInst*, int> StaticAllocaMap;
163 unsigned MakeReg(MVT::ValueType VT) {
164 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
167 unsigned CreateRegForValue(const Value *V);
169 unsigned InitializeRegForValue(const Value *V) {
170 unsigned &R = ValueMap[V];
171 assert(R == 0 && "Already initialized this value register!");
172 return R = CreateRegForValue(V);
177 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
178 /// PHI nodes or outside of the basic block that defines it, or used by a
179 /// switch instruction, which may expand to multiple basic blocks.
180 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
181 if (isa<PHINode>(I)) return true;
182 BasicBlock *BB = I->getParent();
183 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
184 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
185 isa<SwitchInst>(*UI))
190 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
191 /// entry block, return true. This includes arguments used by switches, since
192 /// the switch may expand into multiple basic blocks.
193 static bool isOnlyUsedInEntryBlock(Argument *A) {
194 BasicBlock *Entry = A->getParent()->begin();
195 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
196 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
197 return false; // Use not in entry block.
201 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
202 Function &fn, MachineFunction &mf)
203 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
205 // Create a vreg for each argument register that is not dead and is used
206 // outside of the entry block for the function.
207 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
209 if (!isOnlyUsedInEntryBlock(AI))
210 InitializeRegForValue(AI);
212 // Initialize the mapping of values to registers. This is only set up for
213 // instruction values that are used outside of the block that defines
215 Function::iterator BB = Fn.begin(), EB = Fn.end();
216 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
217 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
218 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
219 const Type *Ty = AI->getAllocatedType();
220 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
222 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
225 // If the alignment of the value is smaller than the size of the value,
226 // and if the size of the value is particularly small (<= 8 bytes),
227 // round up to the size of the value for potentially better performance.
229 // FIXME: This could be made better with a preferred alignment hook in
230 // TargetData. It serves primarily to 8-byte align doubles for X86.
231 if (Align < TySize && TySize <= 8) Align = TySize;
232 TySize *= CUI->getValue(); // Get total allocated size.
233 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
234 StaticAllocaMap[AI] =
235 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
238 for (; BB != EB; ++BB)
239 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
240 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
241 if (!isa<AllocaInst>(I) ||
242 !StaticAllocaMap.count(cast<AllocaInst>(I)))
243 InitializeRegForValue(I);
245 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
246 // also creates the initial PHI MachineInstrs, though none of the input
247 // operands are populated.
248 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
249 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
251 MF.getBasicBlockList().push_back(MBB);
253 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
256 for (BasicBlock::iterator I = BB->begin();
257 (PN = dyn_cast<PHINode>(I)); ++I)
258 if (!PN->use_empty()) {
259 MVT::ValueType VT = TLI.getValueType(PN->getType());
260 unsigned NumElements;
261 if (VT != MVT::Vector)
262 NumElements = TLI.getNumElements(VT);
264 MVT::ValueType VT1,VT2;
266 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
269 unsigned PHIReg = ValueMap[PN];
270 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
271 for (unsigned i = 0; i != NumElements; ++i)
272 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
277 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
278 /// the correctly promoted or expanded types. Assign these registers
279 /// consecutive vreg numbers and return the first assigned number.
280 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
281 MVT::ValueType VT = TLI.getValueType(V->getType());
283 // The number of multiples of registers that we need, to, e.g., split up
284 // a <2 x int64> -> 4 x i32 registers.
285 unsigned NumVectorRegs = 1;
287 // If this is a packed type, figure out what type it will decompose into
288 // and how many of the elements it will use.
289 if (VT == MVT::Vector) {
290 const PackedType *PTy = cast<PackedType>(V->getType());
291 unsigned NumElts = PTy->getNumElements();
292 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
294 // Divide the input until we get to a supported size. This will always
295 // end with a scalar if the target doesn't support vectors.
296 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
303 VT = getVectorType(EltTy, NumElts);
306 // The common case is that we will only create one register for this
307 // value. If we have that case, create and return the virtual register.
308 unsigned NV = TLI.getNumElements(VT);
310 // If we are promoting this value, pick the next largest supported type.
311 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
312 unsigned Reg = MakeReg(PromotedType);
313 // If this is a vector of supported or promoted types (e.g. 4 x i16),
314 // create all of the registers.
315 for (unsigned i = 1; i != NumVectorRegs; ++i)
316 MakeReg(PromotedType);
320 // If this value is represented with multiple target registers, make sure
321 // to create enough consecutive registers of the right (smaller) type.
322 unsigned NT = VT-1; // Find the type to use.
323 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
326 unsigned R = MakeReg((MVT::ValueType)NT);
327 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
328 MakeReg((MVT::ValueType)NT);
332 //===----------------------------------------------------------------------===//
333 /// SelectionDAGLowering - This is the common target-independent lowering
334 /// implementation that is parameterized by a TargetLowering object.
335 /// Also, targets can overload any lowering method.
338 class SelectionDAGLowering {
339 MachineBasicBlock *CurMBB;
341 std::map<const Value*, SDOperand> NodeMap;
343 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
344 /// them up and then emit token factor nodes when possible. This allows us to
345 /// get simple disambiguation between loads without worrying about alias
347 std::vector<SDOperand> PendingLoads;
349 /// Case - A pair of values to record the Value for a switch case, and the
350 /// case's target basic block.
351 typedef std::pair<Constant*, MachineBasicBlock*> Case;
352 typedef std::vector<Case>::iterator CaseItr;
353 typedef std::pair<CaseItr, CaseItr> CaseRange;
355 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
356 /// of conditional branches.
358 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
359 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
361 /// CaseBB - The MBB in which to emit the compare and branch
362 MachineBasicBlock *CaseBB;
363 /// LT, GE - If nonzero, we know the current case value must be less-than or
364 /// greater-than-or-equal-to these Constants.
367 /// Range - A pair of iterators representing the range of case values to be
368 /// processed at this point in the binary search tree.
372 /// The comparison function for sorting Case values.
374 bool operator () (const Case& C1, const Case& C2) {
375 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
376 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
378 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
379 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
384 // TLI - This is information that describes the available target features we
385 // need for lowering. This indicates when operations are unavailable,
386 // implemented with a libcall, etc.
389 const TargetData *TD;
391 /// SwitchCases - Vector of CaseBlock structures used to communicate
392 /// SwitchInst code generation information.
393 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
394 SelectionDAGISel::JumpTable JT;
396 /// FuncInfo - Information about the function as a whole.
398 FunctionLoweringInfo &FuncInfo;
400 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
401 FunctionLoweringInfo &funcinfo)
402 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
403 JT(0,0,0,0), FuncInfo(funcinfo) {
406 /// getRoot - Return the current virtual root of the Selection DAG.
408 SDOperand getRoot() {
409 if (PendingLoads.empty())
410 return DAG.getRoot();
412 if (PendingLoads.size() == 1) {
413 SDOperand Root = PendingLoads[0];
415 PendingLoads.clear();
419 // Otherwise, we have to make a token factor node.
420 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
421 PendingLoads.clear();
426 void visit(Instruction &I) { visit(I.getOpcode(), I); }
428 void visit(unsigned Opcode, User &I) {
430 default: assert(0 && "Unknown instruction type encountered!");
432 // Build the switch statement using the Instruction.def file.
433 #define HANDLE_INST(NUM, OPCODE, CLASS) \
434 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
435 #include "llvm/Instruction.def"
439 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
441 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
442 SDOperand SrcValue, SDOperand Root,
445 SDOperand getIntPtrConstant(uint64_t Val) {
446 return DAG.getConstant(Val, TLI.getPointerTy());
449 SDOperand getValue(const Value *V);
451 const SDOperand &setValue(const Value *V, SDOperand NewN) {
452 SDOperand &N = NodeMap[V];
453 assert(N.Val == 0 && "Already set a value for this node!");
457 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
459 bool OutReg, bool InReg,
460 std::set<unsigned> &OutputRegs,
461 std::set<unsigned> &InputRegs);
463 // Terminator instructions.
464 void visitRet(ReturnInst &I);
465 void visitBr(BranchInst &I);
466 void visitSwitch(SwitchInst &I);
467 void visitUnreachable(UnreachableInst &I) { /* noop */ }
469 // Helper for visitSwitch
470 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
471 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
473 // These all get lowered before this pass.
474 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
475 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
477 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
478 void visitShift(User &I, unsigned Opcode);
479 void visitAdd(User &I) {
480 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
482 void visitSub(User &I);
483 void visitMul(User &I) {
484 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
486 void visitDiv(User &I) {
487 const Type *Ty = I.getType();
489 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
490 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
492 void visitRem(User &I) {
493 const Type *Ty = I.getType();
494 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
496 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
497 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
498 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
499 void visitShl(User &I) { visitShift(I, ISD::SHL); }
500 void visitShr(User &I) {
501 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
504 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
505 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
506 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
507 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
508 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
509 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
510 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
512 void visitExtractElement(User &I);
513 void visitInsertElement(User &I);
514 void visitShuffleVector(User &I);
516 void visitGetElementPtr(User &I);
517 void visitCast(User &I);
518 void visitSelect(User &I);
520 void visitMalloc(MallocInst &I);
521 void visitFree(FreeInst &I);
522 void visitAlloca(AllocaInst &I);
523 void visitLoad(LoadInst &I);
524 void visitStore(StoreInst &I);
525 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
526 void visitCall(CallInst &I);
527 void visitInlineAsm(CallInst &I);
528 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
529 void visitTargetIntrinsic(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 SDOperand SelectionDAGLowering::getValue(const Value *V) {
551 SDOperand &N = NodeMap[V];
554 const Type *VTy = V->getType();
555 MVT::ValueType VT = TLI.getValueType(VTy);
556 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
557 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
558 visit(CE->getOpcode(), *CE);
559 assert(N.Val && "visit didn't populate the ValueMap!");
561 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
562 return N = DAG.getGlobalAddress(GV, VT);
563 } else if (isa<ConstantPointerNull>(C)) {
564 return N = DAG.getConstant(0, TLI.getPointerTy());
565 } else if (isa<UndefValue>(C)) {
566 if (!isa<PackedType>(VTy))
567 return N = DAG.getNode(ISD::UNDEF, VT);
569 // Create a VBUILD_VECTOR of undef nodes.
570 const PackedType *PTy = cast<PackedType>(VTy);
571 unsigned NumElements = PTy->getNumElements();
572 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
574 std::vector<SDOperand> Ops;
575 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
577 // Create a VConstant node with generic Vector type.
578 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
579 Ops.push_back(DAG.getValueType(PVT));
580 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
581 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
582 return N = DAG.getConstantFP(CFP->getValue(), VT);
583 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
584 unsigned NumElements = PTy->getNumElements();
585 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
587 // Now that we know the number and type of the elements, push a
588 // Constant or ConstantFP node onto the ops list for each element of
589 // the packed constant.
590 std::vector<SDOperand> Ops;
591 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
592 for (unsigned i = 0; i != NumElements; ++i)
593 Ops.push_back(getValue(CP->getOperand(i)));
595 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
597 if (MVT::isFloatingPoint(PVT))
598 Op = DAG.getConstantFP(0, PVT);
600 Op = DAG.getConstant(0, PVT);
601 Ops.assign(NumElements, Op);
604 // Create a VBUILD_VECTOR node with generic Vector type.
605 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
606 Ops.push_back(DAG.getValueType(PVT));
607 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
609 // Canonicalize all constant ints to be unsigned.
610 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
614 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
615 std::map<const AllocaInst*, int>::iterator SI =
616 FuncInfo.StaticAllocaMap.find(AI);
617 if (SI != FuncInfo.StaticAllocaMap.end())
618 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
621 std::map<const Value*, unsigned>::const_iterator VMI =
622 FuncInfo.ValueMap.find(V);
623 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
625 unsigned InReg = VMI->second;
627 // If this type is not legal, make it so now.
628 if (VT != MVT::Vector) {
629 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
631 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
633 // Source must be expanded. This input value is actually coming from the
634 // register pair VMI->second and VMI->second+1.
635 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
636 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
637 } else if (DestVT > VT) { // Promotion case
638 if (MVT::isFloatingPoint(VT))
639 N = DAG.getNode(ISD::FP_ROUND, VT, N);
641 N = DAG.getNode(ISD::TRUNCATE, VT, N);
644 // Otherwise, if this is a vector, make it available as a generic vector
646 MVT::ValueType PTyElementVT, PTyLegalElementVT;
647 const PackedType *PTy = cast<PackedType>(VTy);
648 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
651 // Build a VBUILD_VECTOR with the input registers.
652 std::vector<SDOperand> Ops;
653 if (PTyElementVT == PTyLegalElementVT) {
654 // If the value types are legal, just VBUILD the CopyFromReg nodes.
655 for (unsigned i = 0; i != NE; ++i)
656 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
658 } else if (PTyElementVT < PTyLegalElementVT) {
659 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
660 for (unsigned i = 0; i != NE; ++i) {
661 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
663 if (MVT::isFloatingPoint(PTyElementVT))
664 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
666 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
670 // If the register was expanded, use BUILD_PAIR.
671 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
672 for (unsigned i = 0; i != NE/2; ++i) {
673 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
675 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
677 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
681 Ops.push_back(DAG.getConstant(NE, MVT::i32));
682 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
683 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
685 // Finally, use a VBIT_CONVERT to make this available as the appropriate
687 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
688 DAG.getConstant(PTy->getNumElements(),
690 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
697 void SelectionDAGLowering::visitRet(ReturnInst &I) {
698 if (I.getNumOperands() == 0) {
699 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
702 std::vector<SDOperand> NewValues;
703 NewValues.push_back(getRoot());
704 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
705 SDOperand RetOp = getValue(I.getOperand(i));
707 // If this is an integer return value, we need to promote it ourselves to
708 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
710 if (MVT::isInteger(RetOp.getValueType()) &&
711 RetOp.getValueType() < MVT::i64) {
712 MVT::ValueType TmpVT;
713 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
714 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
718 if (I.getOperand(i)->getType()->isSigned())
719 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
721 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
723 NewValues.push_back(RetOp);
725 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
728 void SelectionDAGLowering::visitBr(BranchInst &I) {
729 // Update machine-CFG edges.
730 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
731 CurMBB->addSuccessor(Succ0MBB);
733 // Figure out which block is immediately after the current one.
734 MachineBasicBlock *NextBlock = 0;
735 MachineFunction::iterator BBI = CurMBB;
736 if (++BBI != CurMBB->getParent()->end())
739 if (I.isUnconditional()) {
740 // If this is not a fall-through branch, emit the branch.
741 if (Succ0MBB != NextBlock)
742 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
743 DAG.getBasicBlock(Succ0MBB)));
745 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
746 CurMBB->addSuccessor(Succ1MBB);
748 SDOperand Cond = getValue(I.getCondition());
749 if (Succ1MBB == NextBlock) {
750 // If the condition is false, fall through. This means we should branch
751 // if the condition is true to Succ #0.
752 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
753 Cond, DAG.getBasicBlock(Succ0MBB)));
754 } else if (Succ0MBB == NextBlock) {
755 // If the condition is true, fall through. This means we should branch if
756 // the condition is false to Succ #1. Invert the condition first.
757 SDOperand True = DAG.getConstant(1, Cond.getValueType());
758 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
759 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
760 Cond, DAG.getBasicBlock(Succ1MBB)));
762 std::vector<SDOperand> Ops;
763 Ops.push_back(getRoot());
764 // If the false case is the current basic block, then this is a self
765 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
766 // adds an extra instruction in the loop. Instead, invert the
767 // condition and emit "Loop: ... br!cond Loop; br Out.
768 if (CurMBB == Succ1MBB) {
769 std::swap(Succ0MBB, Succ1MBB);
770 SDOperand True = DAG.getConstant(1, Cond.getValueType());
771 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
773 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
774 DAG.getBasicBlock(Succ0MBB));
775 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
776 DAG.getBasicBlock(Succ1MBB)));
781 /// visitSwitchCase - Emits the necessary code to represent a single node in
782 /// the binary search tree resulting from lowering a switch instruction.
783 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
784 SDOperand SwitchOp = getValue(CB.SwitchV);
785 SDOperand CaseOp = getValue(CB.CaseC);
786 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
788 // Set NextBlock to be the MBB immediately after the current one, if any.
789 // This is used to avoid emitting unnecessary branches to the next block.
790 MachineBasicBlock *NextBlock = 0;
791 MachineFunction::iterator BBI = CurMBB;
792 if (++BBI != CurMBB->getParent()->end())
795 // If the lhs block is the next block, invert the condition so that we can
796 // fall through to the lhs instead of the rhs block.
797 if (CB.LHSBB == NextBlock) {
798 std::swap(CB.LHSBB, CB.RHSBB);
799 SDOperand True = DAG.getConstant(1, Cond.getValueType());
800 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
802 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
803 DAG.getBasicBlock(CB.LHSBB));
804 if (CB.RHSBB == NextBlock)
807 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
808 DAG.getBasicBlock(CB.RHSBB)));
809 // Update successor info
810 CurMBB->addSuccessor(CB.LHSBB);
811 CurMBB->addSuccessor(CB.RHSBB);
814 /// visitSwitchCase - Emits the necessary code to represent a single node in
815 /// the binary search tree resulting from lowering a switch instruction.
816 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
817 // FIXME: Need to emit different code for PIC vs. Non-PIC, specifically,
818 // we need to add the address of the jump table to the value loaded, since
819 // the entries in the jump table will be differences rather than absolute
822 // Emit the code for the jump table
823 MVT::ValueType PTy = TLI.getPointerTy();
824 unsigned PTyBytes = MVT::getSizeInBits(PTy)/8;
825 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
826 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
827 DAG.getConstant(PTyBytes, PTy));
828 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, DAG.getJumpTable(JT.JTI,PTy));
829 SDOperand LD = DAG.getLoad(PTy, Copy.getValue(1), ADD, DAG.getSrcValue(0));
830 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
833 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
834 // Figure out which block is immediately after the current one.
835 MachineBasicBlock *NextBlock = 0;
836 MachineFunction::iterator BBI = CurMBB;
837 if (++BBI != CurMBB->getParent()->end())
840 // If there is only the default destination, branch to it if it is not the
841 // next basic block. Otherwise, just fall through.
842 if (I.getNumOperands() == 2) {
843 // Update machine-CFG edges.
844 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
845 // If this is not a fall-through branch, emit the branch.
846 if (DefaultMBB != NextBlock)
847 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
848 DAG.getBasicBlock(DefaultMBB)));
852 // If there are any non-default case statements, create a vector of Cases
853 // representing each one, and sort the vector so that we can efficiently
854 // create a binary search tree from them.
855 std::vector<Case> Cases;
856 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
857 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
858 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
860 std::sort(Cases.begin(), Cases.end(), CaseCmp());
862 // Get the Value to be switched on and default basic blocks, which will be
863 // inserted into CaseBlock records, representing basic blocks in the binary
865 Value *SV = I.getOperand(0);
866 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
868 // Get the MachineFunction which holds the current MBB. This is used during
869 // emission of jump tables, and when inserting any additional MBBs necessary
870 // to represent the switch.
871 MachineFunction *CurMF = CurMBB->getParent();
872 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
873 Reloc::Model Relocs = TLI.getTargetMachine().getRelocationModel();
875 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
876 // target supports indirect branches, then emit a jump table rather than
877 // lowering the switch to a binary tree of conditional branches.
878 // FIXME: Make this work with PIC code
879 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
880 (Relocs == Reloc::Static || Relocs == Reloc::DynamicNoPIC) &&
882 uint64_t First = cast<ConstantIntegral>(Cases.front().first)->getRawValue();
883 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getRawValue();
884 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
886 if (Density >= 0.3125) {
887 // Create a new basic block to hold the code for loading the address
888 // of the jump table, and jumping to it. Update successor information;
889 // we will either branch to the default case for the switch, or the jump
891 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
892 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
893 CurMBB->addSuccessor(Default);
894 CurMBB->addSuccessor(JumpTableBB);
896 // Subtract the lowest switch case value from the value being switched on
897 // and conditional branch to default mbb if the result is greater than the
898 // difference between smallest and largest cases.
899 SDOperand SwitchOp = getValue(SV);
900 MVT::ValueType VT = SwitchOp.getValueType();
901 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
902 DAG.getConstant(First, VT));
904 // The SDNode we just created, which holds the value being switched on
905 // minus the the smallest case value, needs to be copied to a virtual
906 // register so it can be used as an index into the jump table in a
907 // subsequent basic block. This value may be smaller or larger than the
908 // target's pointer type, and therefore require extension or truncating.
909 if (VT > TLI.getPointerTy())
910 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
912 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
913 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
914 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
916 // Emit the range check for the jump table, and branch to the default
917 // block for the switch statement if the value being switched on exceeds
918 // the largest case in the switch.
919 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
920 DAG.getConstant(Last-First,VT), ISD::SETUGT);
921 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
922 DAG.getBasicBlock(Default)));
924 // Build a vector of destination BBs, corresponding to each target
925 // of the jump table. If the value of the jump table slot corresponds to
926 // a case statement, push the case's BB onto the vector, otherwise, push
928 std::set<MachineBasicBlock*> UniqueBBs;
929 std::vector<MachineBasicBlock*> DestBBs;
930 uint64_t TEI = First;
931 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI) {
932 if (cast<ConstantIntegral>(ii->first)->getRawValue() == TEI) {
933 DestBBs.push_back(ii->second);
934 UniqueBBs.insert(ii->second);
937 DestBBs.push_back(Default);
938 UniqueBBs.insert(Default);
942 // Update successor info
943 for (std::set<MachineBasicBlock*>::iterator ii = UniqueBBs.begin(),
944 ee = UniqueBBs.end(); ii != ee; ++ii)
945 JumpTableBB->addSuccessor(*ii);
947 // Create a jump table index for this jump table, or return an existing
949 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
951 // Set the jump table information so that we can codegen it as a second
953 JT.Reg = JumpTableReg;
955 JT.MBB = JumpTableBB;
956 JT.Default = Default;
961 // Push the initial CaseRec onto the worklist
962 std::vector<CaseRec> CaseVec;
963 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
965 while (!CaseVec.empty()) {
966 // Grab a record representing a case range to process off the worklist
967 CaseRec CR = CaseVec.back();
970 // Size is the number of Cases represented by this range. If Size is 1,
971 // then we are processing a leaf of the binary search tree. Otherwise,
972 // we need to pick a pivot, and push left and right ranges onto the
974 unsigned Size = CR.Range.second - CR.Range.first;
977 // Create a CaseBlock record representing a conditional branch to
978 // the Case's target mbb if the value being switched on SV is equal
979 // to C. Otherwise, branch to default.
980 Constant *C = CR.Range.first->first;
981 MachineBasicBlock *Target = CR.Range.first->second;
982 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
984 // If the MBB representing the leaf node is the current MBB, then just
985 // call visitSwitchCase to emit the code into the current block.
986 // Otherwise, push the CaseBlock onto the vector to be later processed
987 // by SDISel, and insert the node's MBB before the next MBB.
988 if (CR.CaseBB == CurMBB)
991 SwitchCases.push_back(CB);
992 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
995 // split case range at pivot
996 CaseItr Pivot = CR.Range.first + (Size / 2);
997 CaseRange LHSR(CR.Range.first, Pivot);
998 CaseRange RHSR(Pivot, CR.Range.second);
999 Constant *C = Pivot->first;
1000 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
1001 // We know that we branch to the LHS if the Value being switched on is
1002 // less than the Pivot value, C. We use this to optimize our binary
1003 // tree a bit, by recognizing that if SV is greater than or equal to the
1004 // LHS's Case Value, and that Case Value is exactly one less than the
1005 // Pivot's Value, then we can branch directly to the LHS's Target,
1006 // rather than creating a leaf node for it.
1007 if ((LHSR.second - LHSR.first) == 1 &&
1008 LHSR.first->first == CR.GE &&
1009 cast<ConstantIntegral>(C)->getRawValue() ==
1010 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
1011 LHSBB = LHSR.first->second;
1013 LHSBB = new MachineBasicBlock(LLVMBB);
1014 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1016 // Similar to the optimization above, if the Value being switched on is
1017 // known to be less than the Constant CR.LT, and the current Case Value
1018 // is CR.LT - 1, then we can branch directly to the target block for
1019 // the current Case Value, rather than emitting a RHS leaf node for it.
1020 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1021 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
1022 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
1023 RHSBB = RHSR.first->second;
1025 RHSBB = new MachineBasicBlock(LLVMBB);
1026 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1028 // Create a CaseBlock record representing a conditional branch to
1029 // the LHS node if the value being switched on SV is less than C.
1030 // Otherwise, branch to LHS.
1031 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1032 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
1033 if (CR.CaseBB == CurMBB)
1034 visitSwitchCase(CB);
1036 SwitchCases.push_back(CB);
1037 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1043 void SelectionDAGLowering::visitSub(User &I) {
1044 // -0.0 - X --> fneg
1045 if (I.getType()->isFloatingPoint()) {
1046 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1047 if (CFP->isExactlyValue(-0.0)) {
1048 SDOperand Op2 = getValue(I.getOperand(1));
1049 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1053 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
1056 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1058 const Type *Ty = I.getType();
1059 SDOperand Op1 = getValue(I.getOperand(0));
1060 SDOperand Op2 = getValue(I.getOperand(1));
1062 if (Ty->isIntegral()) {
1063 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1064 } else if (Ty->isFloatingPoint()) {
1065 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1067 const PackedType *PTy = cast<PackedType>(Ty);
1068 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1069 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1070 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1074 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1075 SDOperand Op1 = getValue(I.getOperand(0));
1076 SDOperand Op2 = getValue(I.getOperand(1));
1078 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1080 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1083 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
1084 ISD::CondCode UnsignedOpcode) {
1085 SDOperand Op1 = getValue(I.getOperand(0));
1086 SDOperand Op2 = getValue(I.getOperand(1));
1087 ISD::CondCode Opcode = SignedOpcode;
1088 if (I.getOperand(0)->getType()->isUnsigned())
1089 Opcode = UnsignedOpcode;
1090 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1093 void SelectionDAGLowering::visitSelect(User &I) {
1094 SDOperand Cond = getValue(I.getOperand(0));
1095 SDOperand TrueVal = getValue(I.getOperand(1));
1096 SDOperand FalseVal = getValue(I.getOperand(2));
1097 if (!isa<PackedType>(I.getType())) {
1098 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1099 TrueVal, FalseVal));
1101 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1102 *(TrueVal.Val->op_end()-2),
1103 *(TrueVal.Val->op_end()-1)));
1107 void SelectionDAGLowering::visitCast(User &I) {
1108 SDOperand N = getValue(I.getOperand(0));
1109 MVT::ValueType SrcVT = N.getValueType();
1110 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1112 if (DestVT == MVT::Vector) {
1113 // This is a cast to a vector from something else. This is always a bit
1114 // convert. Get information about the input vector.
1115 const PackedType *DestTy = cast<PackedType>(I.getType());
1116 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1117 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1118 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1119 DAG.getValueType(EltVT)));
1120 } else if (SrcVT == DestVT) {
1121 setValue(&I, N); // noop cast.
1122 } else if (DestVT == MVT::i1) {
1123 // Cast to bool is a comparison against zero, not truncation to zero.
1124 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1125 DAG.getConstantFP(0.0, N.getValueType());
1126 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1127 } else if (isInteger(SrcVT)) {
1128 if (isInteger(DestVT)) { // Int -> Int cast
1129 if (DestVT < SrcVT) // Truncating cast?
1130 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1131 else if (I.getOperand(0)->getType()->isSigned())
1132 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1134 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1135 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
1136 if (I.getOperand(0)->getType()->isSigned())
1137 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1139 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1141 assert(0 && "Unknown cast!");
1143 } else if (isFloatingPoint(SrcVT)) {
1144 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1145 if (DestVT < SrcVT) // Rounding cast?
1146 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1148 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1149 } else if (isInteger(DestVT)) { // FP -> Int cast.
1150 if (I.getType()->isSigned())
1151 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1153 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1155 assert(0 && "Unknown cast!");
1158 assert(SrcVT == MVT::Vector && "Unknown cast!");
1159 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1160 // This is a cast from a vector to something else. This is always a bit
1161 // convert. Get information about the input vector.
1162 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1166 void SelectionDAGLowering::visitInsertElement(User &I) {
1167 SDOperand InVec = getValue(I.getOperand(0));
1168 SDOperand InVal = getValue(I.getOperand(1));
1169 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1170 getValue(I.getOperand(2)));
1172 SDOperand Num = *(InVec.Val->op_end()-2);
1173 SDOperand Typ = *(InVec.Val->op_end()-1);
1174 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1175 InVec, InVal, InIdx, Num, Typ));
1178 void SelectionDAGLowering::visitExtractElement(User &I) {
1179 SDOperand InVec = getValue(I.getOperand(0));
1180 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1181 getValue(I.getOperand(1)));
1182 SDOperand Typ = *(InVec.Val->op_end()-1);
1183 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1184 TLI.getValueType(I.getType()), InVec, InIdx));
1187 void SelectionDAGLowering::visitShuffleVector(User &I) {
1188 SDOperand V1 = getValue(I.getOperand(0));
1189 SDOperand V2 = getValue(I.getOperand(1));
1190 SDOperand Mask = getValue(I.getOperand(2));
1192 SDOperand Num = *(V1.Val->op_end()-2);
1193 SDOperand Typ = *(V2.Val->op_end()-1);
1194 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1195 V1, V2, Mask, Num, Typ));
1199 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1200 SDOperand N = getValue(I.getOperand(0));
1201 const Type *Ty = I.getOperand(0)->getType();
1203 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1206 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1207 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1210 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1211 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1212 getIntPtrConstant(Offset));
1214 Ty = StTy->getElementType(Field);
1216 Ty = cast<SequentialType>(Ty)->getElementType();
1218 // If this is a constant subscript, handle it quickly.
1219 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1220 if (CI->getRawValue() == 0) continue;
1223 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1224 Offs = (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
1226 Offs = TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1227 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1231 // N = N + Idx * ElementSize;
1232 uint64_t ElementSize = TD->getTypeSize(Ty);
1233 SDOperand IdxN = getValue(Idx);
1235 // If the index is smaller or larger than intptr_t, truncate or extend
1237 if (IdxN.getValueType() < N.getValueType()) {
1238 if (Idx->getType()->isSigned())
1239 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1241 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1242 } else if (IdxN.getValueType() > N.getValueType())
1243 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1245 // If this is a multiply by a power of two, turn it into a shl
1246 // immediately. This is a very common case.
1247 if (isPowerOf2_64(ElementSize)) {
1248 unsigned Amt = Log2_64(ElementSize);
1249 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1250 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1251 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1255 SDOperand Scale = getIntPtrConstant(ElementSize);
1256 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1257 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1263 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1264 // If this is a fixed sized alloca in the entry block of the function,
1265 // allocate it statically on the stack.
1266 if (FuncInfo.StaticAllocaMap.count(&I))
1267 return; // getValue will auto-populate this.
1269 const Type *Ty = I.getAllocatedType();
1270 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1271 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
1274 SDOperand AllocSize = getValue(I.getArraySize());
1275 MVT::ValueType IntPtr = TLI.getPointerTy();
1276 if (IntPtr < AllocSize.getValueType())
1277 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1278 else if (IntPtr > AllocSize.getValueType())
1279 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1281 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1282 getIntPtrConstant(TySize));
1284 // Handle alignment. If the requested alignment is less than or equal to the
1285 // stack alignment, ignore it and round the size of the allocation up to the
1286 // stack alignment size. If the size is greater than the stack alignment, we
1287 // note this in the DYNAMIC_STACKALLOC node.
1288 unsigned StackAlign =
1289 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1290 if (Align <= StackAlign) {
1292 // Add SA-1 to the size.
1293 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1294 getIntPtrConstant(StackAlign-1));
1295 // Mask out the low bits for alignment purposes.
1296 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1297 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1300 std::vector<MVT::ValueType> VTs;
1301 VTs.push_back(AllocSize.getValueType());
1302 VTs.push_back(MVT::Other);
1303 std::vector<SDOperand> Ops;
1304 Ops.push_back(getRoot());
1305 Ops.push_back(AllocSize);
1306 Ops.push_back(getIntPtrConstant(Align));
1307 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
1308 DAG.setRoot(setValue(&I, DSA).getValue(1));
1310 // Inform the Frame Information that we have just allocated a variable-sized
1312 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1315 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1316 SDOperand Ptr = getValue(I.getOperand(0));
1322 // Do not serialize non-volatile loads against each other.
1323 Root = DAG.getRoot();
1326 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1327 Root, I.isVolatile()));
1330 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1331 SDOperand SrcValue, SDOperand Root,
1334 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1335 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1336 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
1338 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
1342 DAG.setRoot(L.getValue(1));
1344 PendingLoads.push_back(L.getValue(1));
1350 void SelectionDAGLowering::visitStore(StoreInst &I) {
1351 Value *SrcV = I.getOperand(0);
1352 SDOperand Src = getValue(SrcV);
1353 SDOperand Ptr = getValue(I.getOperand(1));
1354 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1355 DAG.getSrcValue(I.getOperand(1))));
1358 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1359 /// access memory and has no other side effects at all.
1360 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1361 #define GET_NO_MEMORY_INTRINSICS
1362 #include "llvm/Intrinsics.gen"
1363 #undef GET_NO_MEMORY_INTRINSICS
1367 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1368 // have any side-effects or if it only reads memory.
1369 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1370 #define GET_SIDE_EFFECT_INFO
1371 #include "llvm/Intrinsics.gen"
1372 #undef GET_SIDE_EFFECT_INFO
1376 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1378 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1379 unsigned Intrinsic) {
1380 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1381 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1383 // Build the operand list.
1384 std::vector<SDOperand> Ops;
1385 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1387 // We don't need to serialize loads against other loads.
1388 Ops.push_back(DAG.getRoot());
1390 Ops.push_back(getRoot());
1394 // Add the intrinsic ID as an integer operand.
1395 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1397 // Add all operands of the call to the operand list.
1398 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1399 SDOperand Op = getValue(I.getOperand(i));
1401 // If this is a vector type, force it to the right packed type.
1402 if (Op.getValueType() == MVT::Vector) {
1403 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1404 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1406 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1407 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1408 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1411 assert(TLI.isTypeLegal(Op.getValueType()) &&
1412 "Intrinsic uses a non-legal type?");
1416 std::vector<MVT::ValueType> VTs;
1417 if (I.getType() != Type::VoidTy) {
1418 MVT::ValueType VT = TLI.getValueType(I.getType());
1419 if (VT == MVT::Vector) {
1420 const PackedType *DestTy = cast<PackedType>(I.getType());
1421 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1423 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1424 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1427 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1431 VTs.push_back(MVT::Other);
1436 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1437 else if (I.getType() != Type::VoidTy)
1438 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1440 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1443 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1445 PendingLoads.push_back(Chain);
1449 if (I.getType() != Type::VoidTy) {
1450 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1451 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1452 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1453 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1454 DAG.getValueType(EVT));
1456 setValue(&I, Result);
1460 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1461 /// we want to emit this as a call to a named external function, return the name
1462 /// otherwise lower it and return null.
1464 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1465 switch (Intrinsic) {
1467 // By default, turn this into a target intrinsic node.
1468 visitTargetIntrinsic(I, Intrinsic);
1470 case Intrinsic::vastart: visitVAStart(I); return 0;
1471 case Intrinsic::vaend: visitVAEnd(I); return 0;
1472 case Intrinsic::vacopy: visitVACopy(I); return 0;
1473 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1474 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1475 case Intrinsic::setjmp:
1476 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1478 case Intrinsic::longjmp:
1479 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1481 case Intrinsic::memcpy_i32:
1482 case Intrinsic::memcpy_i64:
1483 visitMemIntrinsic(I, ISD::MEMCPY);
1485 case Intrinsic::memset_i32:
1486 case Intrinsic::memset_i64:
1487 visitMemIntrinsic(I, ISD::MEMSET);
1489 case Intrinsic::memmove_i32:
1490 case Intrinsic::memmove_i64:
1491 visitMemIntrinsic(I, ISD::MEMMOVE);
1494 case Intrinsic::dbg_stoppoint: {
1495 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1496 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1497 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1498 std::vector<SDOperand> Ops;
1500 Ops.push_back(getRoot());
1501 Ops.push_back(getValue(SPI.getLineValue()));
1502 Ops.push_back(getValue(SPI.getColumnValue()));
1504 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1505 assert(DD && "Not a debug information descriptor");
1506 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1508 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1509 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1511 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1516 case Intrinsic::dbg_region_start: {
1517 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1518 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1519 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1520 std::vector<SDOperand> Ops;
1522 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1524 Ops.push_back(getRoot());
1525 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1527 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1532 case Intrinsic::dbg_region_end: {
1533 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1534 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1535 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1536 std::vector<SDOperand> Ops;
1538 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1540 Ops.push_back(getRoot());
1541 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1543 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1548 case Intrinsic::dbg_func_start: {
1549 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1550 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1551 if (DebugInfo && FSI.getSubprogram() &&
1552 DebugInfo->Verify(FSI.getSubprogram())) {
1553 std::vector<SDOperand> Ops;
1555 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1557 Ops.push_back(getRoot());
1558 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1560 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1565 case Intrinsic::dbg_declare: {
1566 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1567 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1568 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1569 std::vector<SDOperand> Ops;
1571 SDOperand AddressOp = getValue(DI.getAddress());
1572 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
1573 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1580 case Intrinsic::isunordered_f32:
1581 case Intrinsic::isunordered_f64:
1582 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1583 getValue(I.getOperand(2)), ISD::SETUO));
1586 case Intrinsic::sqrt_f32:
1587 case Intrinsic::sqrt_f64:
1588 setValue(&I, DAG.getNode(ISD::FSQRT,
1589 getValue(I.getOperand(1)).getValueType(),
1590 getValue(I.getOperand(1))));
1592 case Intrinsic::pcmarker: {
1593 SDOperand Tmp = getValue(I.getOperand(1));
1594 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1597 case Intrinsic::readcyclecounter: {
1598 std::vector<MVT::ValueType> VTs;
1599 VTs.push_back(MVT::i64);
1600 VTs.push_back(MVT::Other);
1601 std::vector<SDOperand> Ops;
1602 Ops.push_back(getRoot());
1603 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1605 DAG.setRoot(Tmp.getValue(1));
1608 case Intrinsic::bswap_i16:
1609 case Intrinsic::bswap_i32:
1610 case Intrinsic::bswap_i64:
1611 setValue(&I, DAG.getNode(ISD::BSWAP,
1612 getValue(I.getOperand(1)).getValueType(),
1613 getValue(I.getOperand(1))));
1615 case Intrinsic::cttz_i8:
1616 case Intrinsic::cttz_i16:
1617 case Intrinsic::cttz_i32:
1618 case Intrinsic::cttz_i64:
1619 setValue(&I, DAG.getNode(ISD::CTTZ,
1620 getValue(I.getOperand(1)).getValueType(),
1621 getValue(I.getOperand(1))));
1623 case Intrinsic::ctlz_i8:
1624 case Intrinsic::ctlz_i16:
1625 case Intrinsic::ctlz_i32:
1626 case Intrinsic::ctlz_i64:
1627 setValue(&I, DAG.getNode(ISD::CTLZ,
1628 getValue(I.getOperand(1)).getValueType(),
1629 getValue(I.getOperand(1))));
1631 case Intrinsic::ctpop_i8:
1632 case Intrinsic::ctpop_i16:
1633 case Intrinsic::ctpop_i32:
1634 case Intrinsic::ctpop_i64:
1635 setValue(&I, DAG.getNode(ISD::CTPOP,
1636 getValue(I.getOperand(1)).getValueType(),
1637 getValue(I.getOperand(1))));
1639 case Intrinsic::stacksave: {
1640 std::vector<MVT::ValueType> VTs;
1641 VTs.push_back(TLI.getPointerTy());
1642 VTs.push_back(MVT::Other);
1643 std::vector<SDOperand> Ops;
1644 Ops.push_back(getRoot());
1645 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1647 DAG.setRoot(Tmp.getValue(1));
1650 case Intrinsic::stackrestore: {
1651 SDOperand Tmp = getValue(I.getOperand(1));
1652 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1655 case Intrinsic::prefetch:
1656 // FIXME: Currently discarding prefetches.
1662 void SelectionDAGLowering::visitCall(CallInst &I) {
1663 const char *RenameFn = 0;
1664 if (Function *F = I.getCalledFunction()) {
1665 if (F->isExternal())
1666 if (unsigned IID = F->getIntrinsicID()) {
1667 RenameFn = visitIntrinsicCall(I, IID);
1670 } else { // Not an LLVM intrinsic.
1671 const std::string &Name = F->getName();
1672 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1673 if (I.getNumOperands() == 3 && // Basic sanity checks.
1674 I.getOperand(1)->getType()->isFloatingPoint() &&
1675 I.getType() == I.getOperand(1)->getType() &&
1676 I.getType() == I.getOperand(2)->getType()) {
1677 SDOperand LHS = getValue(I.getOperand(1));
1678 SDOperand RHS = getValue(I.getOperand(2));
1679 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1683 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1684 if (I.getNumOperands() == 2 && // Basic sanity checks.
1685 I.getOperand(1)->getType()->isFloatingPoint() &&
1686 I.getType() == I.getOperand(1)->getType()) {
1687 SDOperand Tmp = getValue(I.getOperand(1));
1688 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1691 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1692 if (I.getNumOperands() == 2 && // Basic sanity checks.
1693 I.getOperand(1)->getType()->isFloatingPoint() &&
1694 I.getType() == I.getOperand(1)->getType()) {
1695 SDOperand Tmp = getValue(I.getOperand(1));
1696 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1699 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1700 if (I.getNumOperands() == 2 && // Basic sanity checks.
1701 I.getOperand(1)->getType()->isFloatingPoint() &&
1702 I.getType() == I.getOperand(1)->getType()) {
1703 SDOperand Tmp = getValue(I.getOperand(1));
1704 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1709 } else if (isa<InlineAsm>(I.getOperand(0))) {
1716 Callee = getValue(I.getOperand(0));
1718 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1719 std::vector<std::pair<SDOperand, const Type*> > Args;
1720 Args.reserve(I.getNumOperands());
1721 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1722 Value *Arg = I.getOperand(i);
1723 SDOperand ArgNode = getValue(Arg);
1724 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1727 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1728 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1730 std::pair<SDOperand,SDOperand> Result =
1731 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1732 I.isTailCall(), Callee, Args, DAG);
1733 if (I.getType() != Type::VoidTy)
1734 setValue(&I, Result.first);
1735 DAG.setRoot(Result.second);
1738 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1739 SDOperand &Chain, SDOperand &Flag)const{
1740 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1741 Chain = Val.getValue(1);
1742 Flag = Val.getValue(2);
1744 // If the result was expanded, copy from the top part.
1745 if (Regs.size() > 1) {
1746 assert(Regs.size() == 2 &&
1747 "Cannot expand to more than 2 elts yet!");
1748 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1749 Chain = Val.getValue(1);
1750 Flag = Val.getValue(2);
1751 if (DAG.getTargetLoweringInfo().isLittleEndian())
1752 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1754 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
1757 // Otherwise, if the return value was promoted, truncate it to the
1758 // appropriate type.
1759 if (RegVT == ValueVT)
1762 if (MVT::isInteger(RegVT))
1763 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1765 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1768 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1769 /// specified value into the registers specified by this object. This uses
1770 /// Chain/Flag as the input and updates them for the output Chain/Flag.
1771 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1772 SDOperand &Chain, SDOperand &Flag) const {
1773 if (Regs.size() == 1) {
1774 // If there is a single register and the types differ, this must be
1776 if (RegVT != ValueVT) {
1777 if (MVT::isInteger(RegVT))
1778 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1780 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1782 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1783 Flag = Chain.getValue(1);
1785 std::vector<unsigned> R(Regs);
1786 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1787 std::reverse(R.begin(), R.end());
1789 for (unsigned i = 0, e = R.size(); i != e; ++i) {
1790 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1791 DAG.getConstant(i, MVT::i32));
1792 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
1793 Flag = Chain.getValue(1);
1798 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
1799 /// operand list. This adds the code marker and includes the number of
1800 /// values added into it.
1801 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1802 std::vector<SDOperand> &Ops) const {
1803 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1804 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1805 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1808 /// isAllocatableRegister - If the specified register is safe to allocate,
1809 /// i.e. it isn't a stack pointer or some other special register, return the
1810 /// register class for the register. Otherwise, return null.
1811 static const TargetRegisterClass *
1812 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1813 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1814 MVT::ValueType FoundVT = MVT::Other;
1815 const TargetRegisterClass *FoundRC = 0;
1816 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1817 E = MRI->regclass_end(); RCI != E; ++RCI) {
1818 MVT::ValueType ThisVT = MVT::Other;
1820 const TargetRegisterClass *RC = *RCI;
1821 // If none of the the value types for this register class are valid, we
1822 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1823 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1825 if (TLI.isTypeLegal(*I)) {
1826 // If we have already found this register in a different register class,
1827 // choose the one with the largest VT specified. For example, on
1828 // PowerPC, we favor f64 register classes over f32.
1829 if (FoundVT == MVT::Other ||
1830 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1837 if (ThisVT == MVT::Other) continue;
1839 // NOTE: This isn't ideal. In particular, this might allocate the
1840 // frame pointer in functions that need it (due to them not being taken
1841 // out of allocation, because a variable sized allocation hasn't been seen
1842 // yet). This is a slight code pessimization, but should still work.
1843 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1844 E = RC->allocation_order_end(MF); I != E; ++I)
1846 // We found a matching register class. Keep looking at others in case
1847 // we find one with larger registers that this physreg is also in.
1856 RegsForValue SelectionDAGLowering::
1857 GetRegistersForValue(const std::string &ConstrCode,
1858 MVT::ValueType VT, bool isOutReg, bool isInReg,
1859 std::set<unsigned> &OutputRegs,
1860 std::set<unsigned> &InputRegs) {
1861 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1862 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1863 std::vector<unsigned> Regs;
1865 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1866 MVT::ValueType RegVT;
1867 MVT::ValueType ValueVT = VT;
1869 if (PhysReg.first) {
1870 if (VT == MVT::Other)
1871 ValueVT = *PhysReg.second->vt_begin();
1874 // This is a explicit reference to a physical register.
1875 Regs.push_back(PhysReg.first);
1877 // If this is an expanded reference, add the rest of the regs to Regs.
1879 RegVT = *PhysReg.second->vt_begin();
1880 TargetRegisterClass::iterator I = PhysReg.second->begin();
1881 TargetRegisterClass::iterator E = PhysReg.second->end();
1882 for (; *I != PhysReg.first; ++I)
1883 assert(I != E && "Didn't find reg!");
1885 // Already added the first reg.
1887 for (; NumRegs; --NumRegs, ++I) {
1888 assert(I != E && "Ran out of registers to allocate!");
1892 return RegsForValue(Regs, RegVT, ValueVT);
1895 // This is a reference to a register class. Allocate NumRegs consecutive,
1896 // available, registers from the class.
1897 std::vector<unsigned> RegClassRegs =
1898 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1900 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1901 MachineFunction &MF = *CurMBB->getParent();
1902 unsigned NumAllocated = 0;
1903 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1904 unsigned Reg = RegClassRegs[i];
1905 // See if this register is available.
1906 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1907 (isInReg && InputRegs.count(Reg))) { // Already used.
1908 // Make sure we find consecutive registers.
1913 // Check to see if this register is allocatable (i.e. don't give out the
1915 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1917 // Make sure we find consecutive registers.
1922 // Okay, this register is good, we can use it.
1925 // If we allocated enough consecutive
1926 if (NumAllocated == NumRegs) {
1927 unsigned RegStart = (i-NumAllocated)+1;
1928 unsigned RegEnd = i+1;
1929 // Mark all of the allocated registers used.
1930 for (unsigned i = RegStart; i != RegEnd; ++i) {
1931 unsigned Reg = RegClassRegs[i];
1932 Regs.push_back(Reg);
1933 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1934 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1937 return RegsForValue(Regs, *RC->vt_begin(), VT);
1941 // Otherwise, we couldn't allocate enough registers for this.
1942 return RegsForValue();
1946 /// visitInlineAsm - Handle a call to an InlineAsm object.
1948 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1949 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1951 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1954 // Note, we treat inline asms both with and without side-effects as the same.
1955 // If an inline asm doesn't have side effects and doesn't access memory, we
1956 // could not choose to not chain it.
1957 bool hasSideEffects = IA->hasSideEffects();
1959 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1960 std::vector<MVT::ValueType> ConstraintVTs;
1962 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1963 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1964 /// if it is a def of that register.
1965 std::vector<SDOperand> AsmNodeOperands;
1966 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1967 AsmNodeOperands.push_back(AsmStr);
1969 SDOperand Chain = getRoot();
1972 // We fully assign registers here at isel time. This is not optimal, but
1973 // should work. For register classes that correspond to LLVM classes, we
1974 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1975 // over the constraints, collecting fixed registers that we know we can't use.
1976 std::set<unsigned> OutputRegs, InputRegs;
1978 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1979 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1980 std::string &ConstraintCode = Constraints[i].Codes[0];
1982 MVT::ValueType OpVT;
1984 // Compute the value type for each operand and add it to ConstraintVTs.
1985 switch (Constraints[i].Type) {
1986 case InlineAsm::isOutput:
1987 if (!Constraints[i].isIndirectOutput) {
1988 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1989 OpVT = TLI.getValueType(I.getType());
1991 const Type *OpTy = I.getOperand(OpNum)->getType();
1992 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1993 OpNum++; // Consumes a call operand.
1996 case InlineAsm::isInput:
1997 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1998 OpNum++; // Consumes a call operand.
2000 case InlineAsm::isClobber:
2005 ConstraintVTs.push_back(OpVT);
2007 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2008 continue; // Not assigned a fixed reg.
2010 // Build a list of regs that this operand uses. This always has a single
2011 // element for promoted/expanded operands.
2012 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2014 OutputRegs, InputRegs);
2016 switch (Constraints[i].Type) {
2017 case InlineAsm::isOutput:
2018 // We can't assign any other output to this register.
2019 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2020 // If this is an early-clobber output, it cannot be assigned to the same
2021 // value as the input reg.
2022 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2023 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2025 case InlineAsm::isInput:
2026 // We can't assign any other input to this register.
2027 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2029 case InlineAsm::isClobber:
2030 // Clobbered regs cannot be used as inputs or outputs.
2031 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2032 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2037 // Loop over all of the inputs, copying the operand values into the
2038 // appropriate registers and processing the output regs.
2039 RegsForValue RetValRegs;
2040 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2043 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2044 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2045 std::string &ConstraintCode = Constraints[i].Codes[0];
2047 switch (Constraints[i].Type) {
2048 case InlineAsm::isOutput: {
2049 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2050 if (ConstraintCode.size() == 1) // not a physreg name.
2051 CTy = TLI.getConstraintType(ConstraintCode[0]);
2053 if (CTy == TargetLowering::C_Memory) {
2055 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2057 // Check that the operand (the address to store to) isn't a float.
2058 if (!MVT::isInteger(InOperandVal.getValueType()))
2059 assert(0 && "MATCH FAIL!");
2061 if (!Constraints[i].isIndirectOutput)
2062 assert(0 && "MATCH FAIL!");
2064 OpNum++; // Consumes a call operand.
2066 // Extend/truncate to the right pointer type if needed.
2067 MVT::ValueType PtrType = TLI.getPointerTy();
2068 if (InOperandVal.getValueType() < PtrType)
2069 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2070 else if (InOperandVal.getValueType() > PtrType)
2071 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2073 // Add information to the INLINEASM node to know about this output.
2074 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2075 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2076 AsmNodeOperands.push_back(InOperandVal);
2080 // Otherwise, this is a register output.
2081 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2083 // If this is an early-clobber output, or if there is an input
2084 // constraint that matches this, we need to reserve the input register
2085 // so no other inputs allocate to it.
2086 bool UsesInputRegister = false;
2087 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2088 UsesInputRegister = true;
2090 // Copy the output from the appropriate register. Find a register that
2093 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2094 true, UsesInputRegister,
2095 OutputRegs, InputRegs);
2096 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
2098 if (!Constraints[i].isIndirectOutput) {
2099 assert(RetValRegs.Regs.empty() &&
2100 "Cannot have multiple output constraints yet!");
2101 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2104 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2105 I.getOperand(OpNum)));
2106 OpNum++; // Consumes a call operand.
2109 // Add information to the INLINEASM node to know that this register is
2111 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2114 case InlineAsm::isInput: {
2115 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2116 OpNum++; // Consumes a call operand.
2118 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2119 // If this is required to match an output register we have already set,
2120 // just use its register.
2121 unsigned OperandNo = atoi(ConstraintCode.c_str());
2123 // Scan until we find the definition we already emitted of this operand.
2124 // When we find it, create a RegsForValue operand.
2125 unsigned CurOp = 2; // The first operand.
2126 for (; OperandNo; --OperandNo) {
2127 // Advance to the next operand.
2129 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2130 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2131 "Skipped past definitions?");
2132 CurOp += (NumOps>>3)+1;
2136 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2137 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2138 "Skipped past definitions?");
2140 // Add NumOps>>3 registers to MatchedRegs.
2141 RegsForValue MatchedRegs;
2142 MatchedRegs.ValueVT = InOperandVal.getValueType();
2143 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2144 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2145 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2146 MatchedRegs.Regs.push_back(Reg);
2149 // Use the produced MatchedRegs object to
2150 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2151 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2155 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2156 if (ConstraintCode.size() == 1) // not a physreg name.
2157 CTy = TLI.getConstraintType(ConstraintCode[0]);
2159 if (CTy == TargetLowering::C_Other) {
2160 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2161 assert(0 && "MATCH FAIL!");
2163 // Add information to the INLINEASM node to know about this input.
2164 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2165 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2166 AsmNodeOperands.push_back(InOperandVal);
2168 } else if (CTy == TargetLowering::C_Memory) {
2171 // Check that the operand isn't a float.
2172 if (!MVT::isInteger(InOperandVal.getValueType()))
2173 assert(0 && "MATCH FAIL!");
2175 // Extend/truncate to the right pointer type if needed.
2176 MVT::ValueType PtrType = TLI.getPointerTy();
2177 if (InOperandVal.getValueType() < PtrType)
2178 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2179 else if (InOperandVal.getValueType() > PtrType)
2180 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2182 // Add information to the INLINEASM node to know about this input.
2183 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2184 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2185 AsmNodeOperands.push_back(InOperandVal);
2189 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2191 // Copy the input into the appropriate registers.
2192 RegsForValue InRegs =
2193 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2194 false, true, OutputRegs, InputRegs);
2195 // FIXME: should be match fail.
2196 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2198 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2200 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2203 case InlineAsm::isClobber: {
2204 RegsForValue ClobberedRegs =
2205 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2206 OutputRegs, InputRegs);
2207 // Add the clobbered value to the operand list, so that the register
2208 // allocator is aware that the physreg got clobbered.
2209 if (!ClobberedRegs.Regs.empty())
2210 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2216 // Finish up input operands.
2217 AsmNodeOperands[0] = Chain;
2218 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2220 std::vector<MVT::ValueType> VTs;
2221 VTs.push_back(MVT::Other);
2222 VTs.push_back(MVT::Flag);
2223 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2224 Flag = Chain.getValue(1);
2226 // If this asm returns a register value, copy the result from that register
2227 // and set it as the value of the call.
2228 if (!RetValRegs.Regs.empty())
2229 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2231 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2233 // Process indirect outputs, first output all of the flagged copies out of
2235 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2236 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2237 Value *Ptr = IndirectStoresToEmit[i].second;
2238 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2239 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2242 // Emit the non-flagged stores from the physregs.
2243 std::vector<SDOperand> OutChains;
2244 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2245 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2246 StoresToEmit[i].first,
2247 getValue(StoresToEmit[i].second),
2248 DAG.getSrcValue(StoresToEmit[i].second)));
2249 if (!OutChains.empty())
2250 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2255 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2256 SDOperand Src = getValue(I.getOperand(0));
2258 MVT::ValueType IntPtr = TLI.getPointerTy();
2260 if (IntPtr < Src.getValueType())
2261 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2262 else if (IntPtr > Src.getValueType())
2263 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2265 // Scale the source by the type size.
2266 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2267 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2268 Src, getIntPtrConstant(ElementSize));
2270 std::vector<std::pair<SDOperand, const Type*> > Args;
2271 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
2273 std::pair<SDOperand,SDOperand> Result =
2274 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2275 DAG.getExternalSymbol("malloc", IntPtr),
2277 setValue(&I, Result.first); // Pointers always fit in registers
2278 DAG.setRoot(Result.second);
2281 void SelectionDAGLowering::visitFree(FreeInst &I) {
2282 std::vector<std::pair<SDOperand, const Type*> > Args;
2283 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2284 TLI.getTargetData()->getIntPtrType()));
2285 MVT::ValueType IntPtr = TLI.getPointerTy();
2286 std::pair<SDOperand,SDOperand> Result =
2287 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2288 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2289 DAG.setRoot(Result.second);
2292 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2293 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2294 // instructions are special in various ways, which require special support to
2295 // insert. The specified MachineInstr is created but not inserted into any
2296 // basic blocks, and the scheduler passes ownership of it to this method.
2297 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2298 MachineBasicBlock *MBB) {
2299 std::cerr << "If a target marks an instruction with "
2300 "'usesCustomDAGSchedInserter', it must implement "
2301 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2306 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2307 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2308 getValue(I.getOperand(1)),
2309 DAG.getSrcValue(I.getOperand(1))));
2312 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2313 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2314 getValue(I.getOperand(0)),
2315 DAG.getSrcValue(I.getOperand(0)));
2317 DAG.setRoot(V.getValue(1));
2320 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2321 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2322 getValue(I.getOperand(1)),
2323 DAG.getSrcValue(I.getOperand(1))));
2326 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2327 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2328 getValue(I.getOperand(1)),
2329 getValue(I.getOperand(2)),
2330 DAG.getSrcValue(I.getOperand(1)),
2331 DAG.getSrcValue(I.getOperand(2))));
2334 /// TargetLowering::LowerArguments - This is the default LowerArguments
2335 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
2336 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be removed.
2337 std::vector<SDOperand>
2338 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2339 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2340 std::vector<SDOperand> Ops;
2341 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2342 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2344 // Add one result value for each formal argument.
2345 std::vector<MVT::ValueType> RetVals;
2346 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2347 MVT::ValueType VT = getValueType(I->getType());
2349 switch (getTypeAction(VT)) {
2350 default: assert(0 && "Unknown type action!");
2352 RetVals.push_back(VT);
2355 RetVals.push_back(getTypeToTransformTo(VT));
2358 if (VT != MVT::Vector) {
2359 // If this is a large integer, it needs to be broken up into small
2360 // integers. Figure out what the destination type is and how many small
2361 // integers it turns into.
2362 MVT::ValueType NVT = getTypeToTransformTo(VT);
2363 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2364 for (unsigned i = 0; i != NumVals; ++i)
2365 RetVals.push_back(NVT);
2367 // Otherwise, this is a vector type. We only support legal vectors
2369 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2370 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2372 // Figure out if there is a Packed type corresponding to this Vector
2373 // type. If so, convert to the packed type.
2374 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2375 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2376 RetVals.push_back(TVT);
2378 assert(0 && "Don't support illegal by-val vector arguments yet!");
2385 if (RetVals.size() == 0)
2386 RetVals.push_back(MVT::isVoid);
2389 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, RetVals, Ops).Val;
2391 // Set up the return result vector.
2394 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2395 MVT::ValueType VT = getValueType(I->getType());
2397 switch (getTypeAction(VT)) {
2398 default: assert(0 && "Unknown type action!");
2400 Ops.push_back(SDOperand(Result, i++));
2403 SDOperand Op(Result, i++);
2404 if (MVT::isInteger(VT)) {
2405 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2407 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2408 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2410 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2411 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2417 if (VT != MVT::Vector) {
2418 // If this is a large integer, it needs to be reassembled from small
2419 // integers. Figure out what the source elt type is and how many small
2421 MVT::ValueType NVT = getTypeToTransformTo(VT);
2422 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2424 SDOperand Lo = SDOperand(Result, i++);
2425 SDOperand Hi = SDOperand(Result, i++);
2427 if (!isLittleEndian())
2430 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2432 // Value scalarized into many values. Unimp for now.
2433 assert(0 && "Cannot expand i64 -> i16 yet!");
2436 // Otherwise, this is a vector type. We only support legal vectors
2438 const PackedType *PTy = cast<PackedType>(I->getType());
2439 unsigned NumElems = PTy->getNumElements();
2440 const Type *EltTy = PTy->getElementType();
2442 // Figure out if there is a Packed type corresponding to this Vector
2443 // type. If so, convert to the packed type.
2444 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2445 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2446 SDOperand N = SDOperand(Result, i++);
2447 // Handle copies from generic vectors to registers.
2448 MVT::ValueType PTyElementVT, PTyLegalElementVT;
2449 unsigned NE = getPackedTypeBreakdown(PTy, PTyElementVT,
2451 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2452 // "N x PTyElementVT" MVT::Vector type.
2453 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2454 DAG.getConstant(NE, MVT::i32),
2455 DAG.getValueType(PTyElementVT));
2458 assert(0 && "Don't support illegal by-val vector arguments yet!");
2467 // It is always conservatively correct for llvm.returnaddress and
2468 // llvm.frameaddress to return 0.
2469 std::pair<SDOperand, SDOperand>
2470 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2471 unsigned Depth, SelectionDAG &DAG) {
2472 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
2475 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
2476 assert(0 && "LowerOperation not implemented for this target!");
2481 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2482 SelectionDAG &DAG) {
2483 assert(0 && "CustomPromoteOperation not implemented for this target!");
2488 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2489 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2490 std::pair<SDOperand,SDOperand> Result =
2491 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
2492 setValue(&I, Result.first);
2493 DAG.setRoot(Result.second);
2496 /// getMemsetValue - Vectorized representation of the memset value
2498 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2499 SelectionDAG &DAG) {
2500 MVT::ValueType CurVT = VT;
2501 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2502 uint64_t Val = C->getValue() & 255;
2504 while (CurVT != MVT::i8) {
2505 Val = (Val << Shift) | Val;
2507 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2509 return DAG.getConstant(Val, VT);
2511 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2513 while (CurVT != MVT::i8) {
2515 DAG.getNode(ISD::OR, VT,
2516 DAG.getNode(ISD::SHL, VT, Value,
2517 DAG.getConstant(Shift, MVT::i8)), Value);
2519 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2526 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2527 /// used when a memcpy is turned into a memset when the source is a constant
2529 static SDOperand getMemsetStringVal(MVT::ValueType VT,
2530 SelectionDAG &DAG, TargetLowering &TLI,
2531 std::string &Str, unsigned Offset) {
2532 MVT::ValueType CurVT = VT;
2534 unsigned MSB = getSizeInBits(VT) / 8;
2535 if (TLI.isLittleEndian())
2536 Offset = Offset + MSB - 1;
2537 for (unsigned i = 0; i != MSB; ++i) {
2538 Val = (Val << 8) | Str[Offset];
2539 Offset += TLI.isLittleEndian() ? -1 : 1;
2541 return DAG.getConstant(Val, VT);
2544 /// getMemBasePlusOffset - Returns base and offset node for the
2545 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2546 SelectionDAG &DAG, TargetLowering &TLI) {
2547 MVT::ValueType VT = Base.getValueType();
2548 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2551 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2552 /// to replace the memset / memcpy is below the threshold. It also returns the
2553 /// types of the sequence of memory ops to perform memset / memcpy.
2554 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2555 unsigned Limit, uint64_t Size,
2556 unsigned Align, TargetLowering &TLI) {
2559 if (TLI.allowsUnalignedMemoryAccesses()) {
2562 switch (Align & 7) {
2578 MVT::ValueType LVT = MVT::i64;
2579 while (!TLI.isTypeLegal(LVT))
2580 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2581 assert(MVT::isInteger(LVT));
2586 unsigned NumMemOps = 0;
2588 unsigned VTSize = getSizeInBits(VT) / 8;
2589 while (VTSize > Size) {
2590 VT = (MVT::ValueType)((unsigned)VT - 1);
2593 assert(MVT::isInteger(VT));
2595 if (++NumMemOps > Limit)
2597 MemOps.push_back(VT);
2604 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
2605 SDOperand Op1 = getValue(I.getOperand(1));
2606 SDOperand Op2 = getValue(I.getOperand(2));
2607 SDOperand Op3 = getValue(I.getOperand(3));
2608 SDOperand Op4 = getValue(I.getOperand(4));
2609 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2610 if (Align == 0) Align = 1;
2612 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2613 std::vector<MVT::ValueType> MemOps;
2615 // Expand memset / memcpy to a series of load / store ops
2616 // if the size operand falls below a certain threshold.
2617 std::vector<SDOperand> OutChains;
2619 default: break; // Do nothing for now.
2621 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2622 Size->getValue(), Align, TLI)) {
2623 unsigned NumMemOps = MemOps.size();
2624 unsigned Offset = 0;
2625 for (unsigned i = 0; i < NumMemOps; i++) {
2626 MVT::ValueType VT = MemOps[i];
2627 unsigned VTSize = getSizeInBits(VT) / 8;
2628 SDOperand Value = getMemsetValue(Op2, VT, DAG);
2629 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2631 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2632 DAG.getSrcValue(I.getOperand(1), Offset));
2633 OutChains.push_back(Store);
2640 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2641 Size->getValue(), Align, TLI)) {
2642 unsigned NumMemOps = MemOps.size();
2643 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
2644 GlobalAddressSDNode *G = NULL;
2646 bool CopyFromStr = false;
2648 if (Op2.getOpcode() == ISD::GlobalAddress)
2649 G = cast<GlobalAddressSDNode>(Op2);
2650 else if (Op2.getOpcode() == ISD::ADD &&
2651 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2652 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2653 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
2654 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
2657 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2659 Str = GV->getStringValue(false);
2667 for (unsigned i = 0; i < NumMemOps; i++) {
2668 MVT::ValueType VT = MemOps[i];
2669 unsigned VTSize = getSizeInBits(VT) / 8;
2670 SDOperand Value, Chain, Store;
2673 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2676 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2677 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2678 DAG.getSrcValue(I.getOperand(1), DstOff));
2680 Value = DAG.getLoad(VT, getRoot(),
2681 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2682 DAG.getSrcValue(I.getOperand(2), SrcOff));
2683 Chain = Value.getValue(1);
2685 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2686 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2687 DAG.getSrcValue(I.getOperand(1), DstOff));
2689 OutChains.push_back(Store);
2698 if (!OutChains.empty()) {
2699 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2704 std::vector<SDOperand> Ops;
2705 Ops.push_back(getRoot());
2710 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
2713 //===----------------------------------------------------------------------===//
2714 // SelectionDAGISel code
2715 //===----------------------------------------------------------------------===//
2717 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2718 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2721 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
2722 // FIXME: we only modify the CFG to split critical edges. This
2723 // updates dom and loop info.
2727 /// OptimizeNoopCopyExpression - We have determined that the specified cast
2728 /// instruction is a noop copy (e.g. it's casting from one pointer type to
2729 /// another, int->uint, or int->sbyte on PPC.
2731 /// Return true if any changes are made.
2732 static bool OptimizeNoopCopyExpression(CastInst *CI) {
2733 BasicBlock *DefBB = CI->getParent();
2735 /// InsertedCasts - Only insert a cast in each block once.
2736 std::map<BasicBlock*, CastInst*> InsertedCasts;
2738 bool MadeChange = false;
2739 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
2741 Use &TheUse = UI.getUse();
2742 Instruction *User = cast<Instruction>(*UI);
2744 // Figure out which BB this cast is used in. For PHI's this is the
2745 // appropriate predecessor block.
2746 BasicBlock *UserBB = User->getParent();
2747 if (PHINode *PN = dyn_cast<PHINode>(User)) {
2748 unsigned OpVal = UI.getOperandNo()/2;
2749 UserBB = PN->getIncomingBlock(OpVal);
2752 // Preincrement use iterator so we don't invalidate it.
2755 // If this user is in the same block as the cast, don't change the cast.
2756 if (UserBB == DefBB) continue;
2758 // If we have already inserted a cast into this block, use it.
2759 CastInst *&InsertedCast = InsertedCasts[UserBB];
2761 if (!InsertedCast) {
2762 BasicBlock::iterator InsertPt = UserBB->begin();
2763 while (isa<PHINode>(InsertPt)) ++InsertPt;
2766 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2770 // Replace a use of the cast with a use of the new casat.
2771 TheUse = InsertedCast;
2774 // If we removed all uses, nuke the cast.
2775 if (CI->use_empty())
2776 CI->eraseFromParent();
2781 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2782 /// casting to the type of GEPI.
2783 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
2784 Instruction *GEPI, Value *Ptr,
2786 if (V) return V; // Already computed.
2788 BasicBlock::iterator InsertPt;
2789 if (BB == GEPI->getParent()) {
2790 // If insert into the GEP's block, insert right after the GEP.
2794 // Otherwise, insert at the top of BB, after any PHI nodes
2795 InsertPt = BB->begin();
2796 while (isa<PHINode>(InsertPt)) ++InsertPt;
2799 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2800 // BB so that there is only one value live across basic blocks (the cast
2802 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2803 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2804 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2806 // Add the offset, cast it to the right type.
2807 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2808 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2811 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
2812 /// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
2813 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
2814 /// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
2815 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
2816 /// the constant add into a load or store instruction. Additionally, if a user
2817 /// is a pointer-pointer cast, we look through it to find its users.
2818 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
2819 Constant *PtrOffset, BasicBlock *DefBB,
2820 GetElementPtrInst *GEPI,
2821 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
2822 while (!RepPtr->use_empty()) {
2823 Instruction *User = cast<Instruction>(RepPtr->use_back());
2825 // If the user is a Pointer-Pointer cast, recurse.
2826 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
2827 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
2829 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
2830 // could invalidate an iterator.
2831 User->setOperand(0, UndefValue::get(RepPtr->getType()));
2835 // If this is a load of the pointer, or a store through the pointer, emit
2836 // the increment into the load/store block.
2837 Instruction *NewVal;
2838 if (isa<LoadInst>(User) ||
2839 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
2840 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
2841 User->getParent(), GEPI,
2844 // If this use is not foldable into the addressing mode, use a version
2845 // emitted in the GEP block.
2846 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2850 if (GEPI->getType() != RepPtr->getType()) {
2851 BasicBlock::iterator IP = NewVal;
2853 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
2855 User->replaceUsesOfWith(RepPtr, NewVal);
2860 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2861 /// selection, we want to be a bit careful about some things. In particular, if
2862 /// we have a GEP instruction that is used in a different block than it is
2863 /// defined, the addressing expression of the GEP cannot be folded into loads or
2864 /// stores that use it. In this case, decompose the GEP and move constant
2865 /// indices into blocks that use it.
2866 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
2867 const TargetData *TD) {
2868 // If this GEP is only used inside the block it is defined in, there is no
2869 // need to rewrite it.
2870 bool isUsedOutsideDefBB = false;
2871 BasicBlock *DefBB = GEPI->getParent();
2872 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2874 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2875 isUsedOutsideDefBB = true;
2879 if (!isUsedOutsideDefBB) return false;
2881 // If this GEP has no non-zero constant indices, there is nothing we can do,
2883 bool hasConstantIndex = false;
2884 bool hasVariableIndex = false;
2885 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2886 E = GEPI->op_end(); OI != E; ++OI) {
2887 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
2888 if (CI->getRawValue()) {
2889 hasConstantIndex = true;
2893 hasVariableIndex = true;
2897 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
2898 if (!hasConstantIndex && !hasVariableIndex) {
2899 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
2900 GEPI->getName(), GEPI);
2901 GEPI->replaceAllUsesWith(NC);
2902 GEPI->eraseFromParent();
2906 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2907 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
2910 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2911 // constant offset (which we now know is non-zero) and deal with it later.
2912 uint64_t ConstantOffset = 0;
2913 const Type *UIntPtrTy = TD->getIntPtrType();
2914 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2915 const Type *Ty = GEPI->getOperand(0)->getType();
2917 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2918 E = GEPI->op_end(); OI != E; ++OI) {
2920 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2921 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2923 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
2924 Ty = StTy->getElementType(Field);
2926 Ty = cast<SequentialType>(Ty)->getElementType();
2928 // Handle constant subscripts.
2929 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2930 if (CI->getRawValue() == 0) continue;
2932 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2933 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
2935 ConstantOffset+=TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2939 // Ptr = Ptr + Idx * ElementSize;
2941 // Cast Idx to UIntPtrTy if needed.
2942 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2944 uint64_t ElementSize = TD->getTypeSize(Ty);
2945 // Mask off bits that should not be set.
2946 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2947 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2949 // Multiply by the element size and add to the base.
2950 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2951 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2955 // Make sure that the offset fits in uintptr_t.
2956 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2957 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2959 // Okay, we have now emitted all of the variable index parts to the BB that
2960 // the GEP is defined in. Loop over all of the using instructions, inserting
2961 // an "add Ptr, ConstantOffset" into each block that uses it and update the
2962 // instruction to use the newly computed value, making GEPI dead. When the
2963 // user is a load or store instruction address, we emit the add into the user
2964 // block, otherwise we use a canonical version right next to the gep (these
2965 // won't be foldable as addresses, so we might as well share the computation).
2967 std::map<BasicBlock*,Instruction*> InsertedExprs;
2968 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
2970 // Finally, the GEP is dead, remove it.
2971 GEPI->eraseFromParent();
2976 bool SelectionDAGISel::runOnFunction(Function &Fn) {
2977 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2978 RegMap = MF.getSSARegMap();
2979 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2981 // First, split all critical edges for PHI nodes with incoming values that are
2982 // constants, this way the load of the constant into a vreg will not be placed
2983 // into MBBs that are used some other way.
2985 // In this pass we also look for GEP and cast instructions that are used
2986 // across basic blocks and rewrite them to improve basic-block-at-a-time
2990 bool MadeChange = true;
2991 while (MadeChange) {
2993 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2995 BasicBlock::iterator BBI;
2996 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
2997 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2998 if (isa<Constant>(PN->getIncomingValue(i)))
2999 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3001 for (BasicBlock::iterator E = BB->end(); BBI != E; ) {
3002 Instruction *I = BBI++;
3003 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3004 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3005 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3006 // If this is a noop copy, sink it into user blocks to reduce the number
3007 // of virtual registers that must be created and coallesced.
3008 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3009 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3011 // This is an fp<->int conversion?
3012 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3015 // If this is an extension, it will be a zero or sign extension, which
3017 if (SrcVT < DstVT) continue;
3019 // If these values will be promoted, find out what they will be promoted
3020 // to. This helps us consider truncates on PPC as noop copies when they
3022 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3023 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3024 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3025 DstVT = TLI.getTypeToTransformTo(DstVT);
3027 // If, after promotion, these are the same types, this is a noop copy.
3029 MadeChange |= OptimizeNoopCopyExpression(CI);
3035 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3037 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3038 SelectBasicBlock(I, MF, FuncInfo);
3044 SDOperand SelectionDAGISel::
3045 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
3046 SDOperand Op = SDL.getValue(V);
3047 assert((Op.getOpcode() != ISD::CopyFromReg ||
3048 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3049 "Copy from a reg to the same reg!");
3051 // If this type is not legal, we must make sure to not create an invalid
3053 MVT::ValueType SrcVT = Op.getValueType();
3054 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3055 SelectionDAG &DAG = SDL.DAG;
3056 if (SrcVT == DestVT) {
3057 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3058 } else if (SrcVT == MVT::Vector) {
3059 // Handle copies from generic vectors to registers.
3060 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3061 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3062 PTyElementVT, PTyLegalElementVT);
3064 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3065 // MVT::Vector type.
3066 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3067 DAG.getConstant(NE, MVT::i32),
3068 DAG.getValueType(PTyElementVT));
3070 // Loop over all of the elements of the resultant vector,
3071 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3072 // copying them into output registers.
3073 std::vector<SDOperand> OutChains;
3074 SDOperand Root = SDL.getRoot();
3075 for (unsigned i = 0; i != NE; ++i) {
3076 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3077 Op, DAG.getConstant(i, MVT::i32));
3078 if (PTyElementVT == PTyLegalElementVT) {
3079 // Elements are legal.
3080 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3081 } else if (PTyLegalElementVT > PTyElementVT) {
3082 // Elements are promoted.
3083 if (MVT::isFloatingPoint(PTyLegalElementVT))
3084 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3086 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3087 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3089 // Elements are expanded.
3090 // The src value is expanded into multiple registers.
3091 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3092 Elt, DAG.getConstant(0, MVT::i32));
3093 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3094 Elt, DAG.getConstant(1, MVT::i32));
3095 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3096 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3099 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
3100 } else if (SrcVT < DestVT) {
3101 // The src value is promoted to the register.
3102 if (MVT::isFloatingPoint(SrcVT))
3103 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3105 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3106 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3108 // The src value is expanded into multiple registers.
3109 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3110 Op, DAG.getConstant(0, MVT::i32));
3111 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3112 Op, DAG.getConstant(1, MVT::i32));
3113 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3114 return DAG.getCopyToReg(Op, Reg+1, Hi);
3118 void SelectionDAGISel::
3119 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3120 std::vector<SDOperand> &UnorderedChains) {
3121 // If this is the entry block, emit arguments.
3122 Function &F = *BB->getParent();
3123 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3124 SDOperand OldRoot = SDL.DAG.getRoot();
3125 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3128 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3130 if (!AI->use_empty()) {
3131 SDL.setValue(AI, Args[a]);
3133 // If this argument is live outside of the entry block, insert a copy from
3134 // whereever we got it to the vreg that other BB's will reference it as.
3135 if (FuncInfo.ValueMap.count(AI)) {
3137 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3138 UnorderedChains.push_back(Copy);
3142 // Next, if the function has live ins that need to be copied into vregs,
3143 // emit the copies now, into the top of the block.
3144 MachineFunction &MF = SDL.DAG.getMachineFunction();
3145 if (MF.livein_begin() != MF.livein_end()) {
3146 SSARegMap *RegMap = MF.getSSARegMap();
3147 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
3148 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
3149 E = MF.livein_end(); LI != E; ++LI)
3151 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
3152 LI->first, RegMap->getRegClass(LI->second));
3155 // Finally, if the target has anything special to do, allow it to do so.
3156 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3160 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3161 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3162 FunctionLoweringInfo &FuncInfo) {
3163 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3165 std::vector<SDOperand> UnorderedChains;
3167 // Lower any arguments needed in this block if this is the entry block.
3168 if (LLVMBB == &LLVMBB->getParent()->front())
3169 LowerArguments(LLVMBB, SDL, UnorderedChains);
3171 BB = FuncInfo.MBBMap[LLVMBB];
3172 SDL.setCurrentBasicBlock(BB);
3174 // Lower all of the non-terminator instructions.
3175 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3179 // Ensure that all instructions which are used outside of their defining
3180 // blocks are available as virtual registers.
3181 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3182 if (!I->use_empty() && !isa<PHINode>(I)) {
3183 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3184 if (VMI != FuncInfo.ValueMap.end())
3185 UnorderedChains.push_back(
3186 CopyValueToVirtualRegister(SDL, I, VMI->second));
3189 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3190 // ensure constants are generated when needed. Remember the virtual registers
3191 // that need to be added to the Machine PHI nodes as input. We cannot just
3192 // directly add them, because expansion might result in multiple MBB's for one
3193 // BB. As such, the start of the BB might correspond to a different MBB than
3197 // Emit constants only once even if used by multiple PHI nodes.
3198 std::map<Constant*, unsigned> ConstantsOut;
3200 // Check successor nodes PHI nodes that expect a constant to be available from
3202 TerminatorInst *TI = LLVMBB->getTerminator();
3203 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3204 BasicBlock *SuccBB = TI->getSuccessor(succ);
3205 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3208 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3209 // nodes and Machine PHI nodes, but the incoming operands have not been
3211 for (BasicBlock::iterator I = SuccBB->begin();
3212 (PN = dyn_cast<PHINode>(I)); ++I)
3213 if (!PN->use_empty()) {
3215 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3216 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3217 unsigned &RegOut = ConstantsOut[C];
3219 RegOut = FuncInfo.CreateRegForValue(C);
3220 UnorderedChains.push_back(
3221 CopyValueToVirtualRegister(SDL, C, RegOut));
3225 Reg = FuncInfo.ValueMap[PHIOp];
3227 assert(isa<AllocaInst>(PHIOp) &&
3228 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3229 "Didn't codegen value into a register!??");
3230 Reg = FuncInfo.CreateRegForValue(PHIOp);
3231 UnorderedChains.push_back(
3232 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
3236 // Remember that this register needs to added to the machine PHI node as
3237 // the input for this MBB.
3238 MVT::ValueType VT = TLI.getValueType(PN->getType());
3239 unsigned NumElements;
3240 if (VT != MVT::Vector)
3241 NumElements = TLI.getNumElements(VT);
3243 MVT::ValueType VT1,VT2;
3245 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3248 for (unsigned i = 0, e = NumElements; i != e; ++i)
3249 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3252 ConstantsOut.clear();
3254 // Turn all of the unordered chains into one factored node.
3255 if (!UnorderedChains.empty()) {
3256 SDOperand Root = SDL.getRoot();
3257 if (Root.getOpcode() != ISD::EntryToken) {
3258 unsigned i = 0, e = UnorderedChains.size();
3259 for (; i != e; ++i) {
3260 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3261 if (UnorderedChains[i].Val->getOperand(0) == Root)
3262 break; // Don't add the root if we already indirectly depend on it.
3266 UnorderedChains.push_back(Root);
3268 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
3271 // Lower the terminator after the copies are emitted.
3272 SDL.visit(*LLVMBB->getTerminator());
3274 // Copy over any CaseBlock records that may now exist due to SwitchInst
3275 // lowering, as well as any jump table information.
3276 SwitchCases.clear();
3277 SwitchCases = SDL.SwitchCases;
3280 // Make sure the root of the DAG is up-to-date.
3281 DAG.setRoot(SDL.getRoot());
3284 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
3285 // Run the DAG combiner in pre-legalize mode.
3288 DEBUG(std::cerr << "Lowered selection DAG:\n");
3291 // Second step, hack on the DAG until it only uses operations and types that
3292 // the target supports.
3295 DEBUG(std::cerr << "Legalized selection DAG:\n");
3298 // Run the DAG combiner in post-legalize mode.
3301 if (ViewISelDAGs) DAG.viewGraph();
3303 // Third, instruction select all of the operations to machine code, adding the
3304 // code to the MachineBasicBlock.
3305 InstructionSelectBasicBlock(DAG);
3307 DEBUG(std::cerr << "Selected machine code:\n");
3311 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3312 FunctionLoweringInfo &FuncInfo) {
3313 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3315 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3318 // First step, lower LLVM code to some DAG. This DAG may use operations and
3319 // types that are not supported by the target.
3320 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3322 // Second step, emit the lowered DAG as machine code.
3323 CodeGenAndEmitDAG(DAG);
3326 // Next, now that we know what the last MBB the LLVM BB expanded is, update
3327 // PHI nodes in successors.
3328 if (SwitchCases.empty() && JT.Reg == 0) {
3329 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3330 MachineInstr *PHI = PHINodesToUpdate[i].first;
3331 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3332 "This is not a machine PHI node that we are updating!");
3333 PHI->addRegOperand(PHINodesToUpdate[i].second);
3334 PHI->addMachineBasicBlockOperand(BB);
3339 // If the JumpTable record is filled in, then we need to emit a jump table.
3340 // Updating the PHI nodes is tricky in this case, since we need to determine
3341 // whether the PHI is a successor of the range check MBB or the jump table MBB
3343 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3344 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3346 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3347 MachineBasicBlock *RangeBB = BB;
3348 // Set the current basic block to the mbb we wish to insert the code into
3350 SDL.setCurrentBasicBlock(BB);
3352 SDL.visitJumpTable(JT);
3353 SDAG.setRoot(SDL.getRoot());
3354 CodeGenAndEmitDAG(SDAG);
3356 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3357 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3358 MachineBasicBlock *PHIBB = PHI->getParent();
3359 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3360 "This is not a machine PHI node that we are updating!");
3361 if (PHIBB == JT.Default) {
3362 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3363 PHI->addMachineBasicBlockOperand(RangeBB);
3365 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
3366 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3367 PHI->addMachineBasicBlockOperand(BB);
3373 // If we generated any switch lowering information, build and codegen any
3374 // additional DAGs necessary.
3375 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
3376 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3378 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3379 // Set the current basic block to the mbb we wish to insert the code into
3380 BB = SwitchCases[i].ThisBB;
3381 SDL.setCurrentBasicBlock(BB);
3383 SDL.visitSwitchCase(SwitchCases[i]);
3384 SDAG.setRoot(SDL.getRoot());
3385 CodeGenAndEmitDAG(SDAG);
3386 // Iterate over the phi nodes, if there is a phi node in a successor of this
3387 // block (for instance, the default block), then add a pair of operands to
3388 // the phi node for this block, as if we were coming from the original
3389 // BB before switch expansion.
3390 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3391 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3392 MachineBasicBlock *PHIBB = PHI->getParent();
3393 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3394 "This is not a machine PHI node that we are updating!");
3395 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
3396 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3397 PHI->addMachineBasicBlockOperand(BB);
3403 //===----------------------------------------------------------------------===//
3404 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3405 /// target node in the graph.
3406 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3407 if (ViewSchedDAGs) DAG.viewGraph();
3408 ScheduleDAG *SL = NULL;
3410 switch (ISHeuristic) {
3411 default: assert(0 && "Unrecognized scheduling heuristic");
3412 case ScheduleDAG::defaultScheduling:
3413 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
3414 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3416 assert(TLI.getSchedulingPreference() ==
3417 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
3418 SL = createBURRListDAGScheduler(DAG, BB);
3421 case ScheduleDAG::noScheduling:
3422 SL = createBFS_DAGScheduler(DAG, BB);
3424 case ScheduleDAG::simpleScheduling:
3425 SL = createSimpleDAGScheduler(false, DAG, BB);
3427 case ScheduleDAG::simpleNoItinScheduling:
3428 SL = createSimpleDAGScheduler(true, DAG, BB);
3430 case ScheduleDAG::listSchedulingBURR:
3431 SL = createBURRListDAGScheduler(DAG, BB);
3433 case ScheduleDAG::listSchedulingTDRR:
3434 SL = createTDRRListDAGScheduler(DAG, BB);
3436 case ScheduleDAG::listSchedulingTD:
3437 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3444 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3445 return new HazardRecognizer();
3448 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3449 /// by tblgen. Others should not call it.
3450 void SelectionDAGISel::
3451 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3452 std::vector<SDOperand> InOps;
3453 std::swap(InOps, Ops);
3455 Ops.push_back(InOps[0]); // input chain.
3456 Ops.push_back(InOps[1]); // input asm string.
3458 unsigned i = 2, e = InOps.size();
3459 if (InOps[e-1].getValueType() == MVT::Flag)
3460 --e; // Don't process a flag operand if it is here.
3463 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3464 if ((Flags & 7) != 4 /*MEM*/) {
3465 // Just skip over this operand, copying the operands verbatim.
3466 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3467 i += (Flags >> 3) + 1;
3469 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3470 // Otherwise, this is a memory operand. Ask the target to select it.
3471 std::vector<SDOperand> SelOps;
3472 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3473 std::cerr << "Could not match memory address. Inline asm failure!\n";
3477 // Add this to the output node.
3478 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3479 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3484 // Add the flag input back if present.
3485 if (e != InOps.size())
3486 Ops.push_back(InOps.back());