1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineDebugInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/SelectionDAG.h"
32 #include "llvm/CodeGen/SSARegMap.h"
33 #include "llvm/Target/MRegisterInfo.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetFrameInfo.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Debug.h"
51 ViewISelDAGs("view-isel-dags", cl::Hidden,
52 cl::desc("Pop up a window to show isel dags as they are selected"));
54 ViewSchedDAGs("view-sched-dags", cl::Hidden,
55 cl::desc("Pop up a window to show sched dags as they are processed"));
57 static const bool ViewISelDAGs = 0;
58 static const bool ViewSchedDAGs = 0;
61 // Scheduling heuristics
62 enum SchedHeuristics {
63 defaultScheduling, // Let the target specify its preference.
64 noScheduling, // No scheduling, emit breadth first sequence.
65 simpleScheduling, // Two pass, min. critical path, max. utilization.
66 simpleNoItinScheduling, // Same as above exact using generic latency.
67 listSchedulingBURR, // Bottom up reg reduction list scheduling.
68 listSchedulingTD // Top-down list scheduler.
72 cl::opt<SchedHeuristics>
75 cl::desc("Choose scheduling style"),
76 cl::init(defaultScheduling),
78 clEnumValN(defaultScheduling, "default",
79 "Target preferred scheduling style"),
80 clEnumValN(noScheduling, "none",
81 "No scheduling: breadth first sequencing"),
82 clEnumValN(simpleScheduling, "simple",
83 "Simple two pass scheduling: minimize critical path "
84 "and maximize processor utilization"),
85 clEnumValN(simpleNoItinScheduling, "simple-noitin",
86 "Simple two pass scheduling: Same as simple "
87 "except using generic latency"),
88 clEnumValN(listSchedulingBURR, "list-burr",
89 "Bottom up register reduction list scheduling"),
90 clEnumValN(listSchedulingTD, "list-td",
91 "Top-down list scheduler"),
96 /// RegsForValue - This struct represents the physical registers that a
97 /// particular value is assigned and the type information about the value.
98 /// This is needed because values can be promoted into larger registers and
99 /// expanded into multiple smaller registers than the value.
100 struct RegsForValue {
101 /// Regs - This list hold the register (for legal and promoted values)
102 /// or register set (for expanded values) that the value should be assigned
104 std::vector<unsigned> Regs;
106 /// RegVT - The value type of each register.
108 MVT::ValueType RegVT;
110 /// ValueVT - The value type of the LLVM value, which may be promoted from
111 /// RegVT or made from merging the two expanded parts.
112 MVT::ValueType ValueVT;
114 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
116 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
117 : RegVT(regvt), ValueVT(valuevt) {
120 RegsForValue(const std::vector<unsigned> ®s,
121 MVT::ValueType regvt, MVT::ValueType valuevt)
122 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
125 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
126 /// this value and returns the result as a ValueVT value. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 SDOperand getCopyFromRegs(SelectionDAG &DAG,
129 SDOperand &Chain, SDOperand &Flag) const;
131 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
132 /// specified value into the registers specified by this object. This uses
133 /// Chain/Flag as the input and updates them for the output Chain/Flag.
134 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
135 SDOperand &Chain, SDOperand &Flag) const;
137 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
138 /// operand list. This adds the code marker and includes the number of
139 /// values added into it.
140 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
141 std::vector<SDOperand> &Ops) const;
146 //===--------------------------------------------------------------------===//
147 /// FunctionLoweringInfo - This contains information that is global to a
148 /// function that is used when lowering a region of the function.
149 class FunctionLoweringInfo {
156 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
158 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
159 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
161 /// ValueMap - Since we emit code for the function a basic block at a time,
162 /// we must remember which virtual registers hold the values for
163 /// cross-basic-block values.
164 std::map<const Value*, unsigned> ValueMap;
166 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
167 /// the entry block. This allows the allocas to be efficiently referenced
168 /// anywhere in the function.
169 std::map<const AllocaInst*, int> StaticAllocaMap;
171 unsigned MakeReg(MVT::ValueType VT) {
172 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
175 unsigned CreateRegForValue(const Value *V);
177 unsigned InitializeRegForValue(const Value *V) {
178 unsigned &R = ValueMap[V];
179 assert(R == 0 && "Already initialized this value register!");
180 return R = CreateRegForValue(V);
185 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
186 /// PHI nodes or outside of the basic block that defines it, or used by a
187 /// switch instruction, which may expand to multiple basic blocks.
188 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
189 if (isa<PHINode>(I)) return true;
190 BasicBlock *BB = I->getParent();
191 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
192 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
193 isa<SwitchInst>(*UI))
198 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
199 /// entry block, return true. This includes arguments used by switches, since
200 /// the switch may expand into multiple basic blocks.
201 static bool isOnlyUsedInEntryBlock(Argument *A) {
202 BasicBlock *Entry = A->getParent()->begin();
203 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
204 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
205 return false; // Use not in entry block.
209 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
210 Function &fn, MachineFunction &mf)
211 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
213 // Create a vreg for each argument register that is not dead and is used
214 // outside of the entry block for the function.
215 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
217 if (!isOnlyUsedInEntryBlock(AI))
218 InitializeRegForValue(AI);
220 // Initialize the mapping of values to registers. This is only set up for
221 // instruction values that are used outside of the block that defines
223 Function::iterator BB = Fn.begin(), EB = Fn.end();
224 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
225 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
226 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
227 const Type *Ty = AI->getAllocatedType();
228 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
230 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
233 // If the alignment of the value is smaller than the size of the value,
234 // and if the size of the value is particularly small (<= 8 bytes),
235 // round up to the size of the value for potentially better performance.
237 // FIXME: This could be made better with a preferred alignment hook in
238 // TargetData. It serves primarily to 8-byte align doubles for X86.
239 if (Align < TySize && TySize <= 8) Align = TySize;
240 TySize *= CUI->getValue(); // Get total allocated size.
241 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
242 StaticAllocaMap[AI] =
243 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
246 for (; BB != EB; ++BB)
247 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
248 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
249 if (!isa<AllocaInst>(I) ||
250 !StaticAllocaMap.count(cast<AllocaInst>(I)))
251 InitializeRegForValue(I);
253 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
254 // also creates the initial PHI MachineInstrs, though none of the input
255 // operands are populated.
256 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
257 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
259 MF.getBasicBlockList().push_back(MBB);
261 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
264 for (BasicBlock::iterator I = BB->begin();
265 (PN = dyn_cast<PHINode>(I)); ++I)
266 if (!PN->use_empty()) {
267 unsigned NumElements =
268 TLI.getNumElements(TLI.getValueType(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;
395 /// FuncInfo - Information about the function as a whole.
397 FunctionLoweringInfo &FuncInfo;
399 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
400 FunctionLoweringInfo &funcinfo)
401 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
405 /// getRoot - Return the current virtual root of the Selection DAG.
407 SDOperand getRoot() {
408 if (PendingLoads.empty())
409 return DAG.getRoot();
411 if (PendingLoads.size() == 1) {
412 SDOperand Root = PendingLoads[0];
414 PendingLoads.clear();
418 // Otherwise, we have to make a token factor node.
419 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
420 PendingLoads.clear();
425 void visit(Instruction &I) { visit(I.getOpcode(), I); }
427 void visit(unsigned Opcode, User &I) {
429 default: assert(0 && "Unknown instruction type encountered!");
431 // Build the switch statement using the Instruction.def file.
432 #define HANDLE_INST(NUM, OPCODE, CLASS) \
433 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
434 #include "llvm/Instruction.def"
438 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
440 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
441 SDOperand SrcValue, SDOperand Root,
444 SDOperand getIntPtrConstant(uint64_t Val) {
445 return DAG.getConstant(Val, TLI.getPointerTy());
448 SDOperand getValue(const Value *V);
450 const SDOperand &setValue(const Value *V, SDOperand NewN) {
451 SDOperand &N = NodeMap[V];
452 assert(N.Val == 0 && "Already set a value for this node!");
456 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
458 bool OutReg, bool InReg,
459 std::set<unsigned> &OutputRegs,
460 std::set<unsigned> &InputRegs);
462 // Terminator instructions.
463 void visitRet(ReturnInst &I);
464 void visitBr(BranchInst &I);
465 void visitSwitch(SwitchInst &I);
466 void visitUnreachable(UnreachableInst &I) { /* noop */ }
468 // Helper for visitSwitch
469 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
471 // These all get lowered before this pass.
472 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
473 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
475 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
476 void visitShift(User &I, unsigned Opcode);
477 void visitAdd(User &I) {
478 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
480 void visitSub(User &I);
481 void visitMul(User &I) {
482 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
484 void visitDiv(User &I) {
485 const Type *Ty = I.getType();
487 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
488 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
490 void visitRem(User &I) {
491 const Type *Ty = I.getType();
492 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
494 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
495 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
496 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
497 void visitShl(User &I) { visitShift(I, ISD::SHL); }
498 void visitShr(User &I) {
499 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
502 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
503 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
504 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
505 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
506 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
507 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
508 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
510 void visitExtractElement(ExtractElementInst &I);
511 void visitInsertElement(InsertElementInst &I);
513 void visitGetElementPtr(User &I);
514 void visitCast(User &I);
515 void visitSelect(User &I);
517 void visitMalloc(MallocInst &I);
518 void visitFree(FreeInst &I);
519 void visitAlloca(AllocaInst &I);
520 void visitLoad(LoadInst &I);
521 void visitStore(StoreInst &I);
522 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
523 void visitCall(CallInst &I);
524 void visitInlineAsm(CallInst &I);
525 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
526 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
528 void visitVAStart(CallInst &I);
529 void visitVAArg(VAArgInst &I);
530 void visitVAEnd(CallInst &I);
531 void visitVACopy(CallInst &I);
532 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
534 void visitMemIntrinsic(CallInst &I, unsigned Op);
536 void visitUserOp1(Instruction &I) {
537 assert(0 && "UserOp1 should not exist at instruction selection time!");
540 void visitUserOp2(Instruction &I) {
541 assert(0 && "UserOp2 should not exist at instruction selection time!");
545 } // end namespace llvm
547 SDOperand SelectionDAGLowering::getValue(const Value *V) {
548 SDOperand &N = NodeMap[V];
551 const Type *VTy = V->getType();
552 MVT::ValueType VT = TLI.getValueType(VTy);
553 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
554 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
555 visit(CE->getOpcode(), *CE);
556 assert(N.Val && "visit didn't populate the ValueMap!");
558 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
559 return N = DAG.getGlobalAddress(GV, VT);
560 } else if (isa<ConstantPointerNull>(C)) {
561 return N = DAG.getConstant(0, TLI.getPointerTy());
562 } else if (isa<UndefValue>(C)) {
563 if (!isa<PackedType>(VTy))
564 return N = DAG.getNode(ISD::UNDEF, VT);
566 // Create a VBUILD_VECTOR of undef nodes.
567 const PackedType *PTy = cast<PackedType>(VTy);
568 unsigned NumElements = PTy->getNumElements();
569 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
571 std::vector<SDOperand> Ops;
572 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
574 // Create a VConstant node with generic Vector type.
575 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
576 Ops.push_back(DAG.getValueType(PVT));
577 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
578 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
579 return N = DAG.getConstantFP(CFP->getValue(), VT);
580 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
581 unsigned NumElements = PTy->getNumElements();
582 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
584 // Now that we know the number and type of the elements, push a
585 // Constant or ConstantFP node onto the ops list for each element of
586 // the packed constant.
587 std::vector<SDOperand> Ops;
588 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
589 if (MVT::isFloatingPoint(PVT)) {
590 for (unsigned i = 0; i != NumElements; ++i) {
591 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
592 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
595 for (unsigned i = 0; i != NumElements; ++i) {
596 const ConstantIntegral *El =
597 cast<ConstantIntegral>(CP->getOperand(i));
598 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
602 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
604 if (MVT::isFloatingPoint(PVT))
605 Op = DAG.getConstantFP(0, PVT);
607 Op = DAG.getConstant(0, PVT);
608 Ops.assign(NumElements, Op);
611 // Create a VBUILD_VECTOR node with generic Vector type.
612 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
613 Ops.push_back(DAG.getValueType(PVT));
614 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
616 // Canonicalize all constant ints to be unsigned.
617 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
621 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
622 std::map<const AllocaInst*, int>::iterator SI =
623 FuncInfo.StaticAllocaMap.find(AI);
624 if (SI != FuncInfo.StaticAllocaMap.end())
625 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
628 std::map<const Value*, unsigned>::const_iterator VMI =
629 FuncInfo.ValueMap.find(V);
630 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
632 unsigned InReg = VMI->second;
634 // If this type is not legal, make it so now.
635 if (VT == MVT::Vector) {
636 // FIXME: We only handle legal vectors right now. We need a VBUILD_VECTOR
637 const PackedType *PTy = cast<PackedType>(VTy);
638 unsigned NumElements = PTy->getNumElements();
639 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
640 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
641 assert(TLI.isTypeLegal(TVT) &&
642 "FIXME: Cannot handle illegal vector types here yet!");
646 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
648 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
650 // Source must be expanded. This input value is actually coming from the
651 // register pair VMI->second and VMI->second+1.
652 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
653 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
655 if (DestVT > VT) { // Promotion case
656 if (MVT::isFloatingPoint(VT))
657 N = DAG.getNode(ISD::FP_ROUND, VT, N);
659 N = DAG.getNode(ISD::TRUNCATE, VT, N);
667 void SelectionDAGLowering::visitRet(ReturnInst &I) {
668 if (I.getNumOperands() == 0) {
669 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
672 std::vector<SDOperand> NewValues;
673 NewValues.push_back(getRoot());
674 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
675 SDOperand RetOp = getValue(I.getOperand(i));
677 // If this is an integer return value, we need to promote it ourselves to
678 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
680 if (MVT::isInteger(RetOp.getValueType()) &&
681 RetOp.getValueType() < MVT::i64) {
682 MVT::ValueType TmpVT;
683 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
684 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
688 if (I.getOperand(i)->getType()->isSigned())
689 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
691 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
693 NewValues.push_back(RetOp);
695 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
698 void SelectionDAGLowering::visitBr(BranchInst &I) {
699 // Update machine-CFG edges.
700 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
701 CurMBB->addSuccessor(Succ0MBB);
703 // Figure out which block is immediately after the current one.
704 MachineBasicBlock *NextBlock = 0;
705 MachineFunction::iterator BBI = CurMBB;
706 if (++BBI != CurMBB->getParent()->end())
709 if (I.isUnconditional()) {
710 // If this is not a fall-through branch, emit the branch.
711 if (Succ0MBB != NextBlock)
712 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
713 DAG.getBasicBlock(Succ0MBB)));
715 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
716 CurMBB->addSuccessor(Succ1MBB);
718 SDOperand Cond = getValue(I.getCondition());
719 if (Succ1MBB == NextBlock) {
720 // If the condition is false, fall through. This means we should branch
721 // if the condition is true to Succ #0.
722 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
723 Cond, DAG.getBasicBlock(Succ0MBB)));
724 } else if (Succ0MBB == NextBlock) {
725 // If the condition is true, fall through. This means we should branch if
726 // the condition is false to Succ #1. Invert the condition first.
727 SDOperand True = DAG.getConstant(1, Cond.getValueType());
728 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
729 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
730 Cond, DAG.getBasicBlock(Succ1MBB)));
732 std::vector<SDOperand> Ops;
733 Ops.push_back(getRoot());
734 // If the false case is the current basic block, then this is a self
735 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
736 // adds an extra instruction in the loop. Instead, invert the
737 // condition and emit "Loop: ... br!cond Loop; br Out.
738 if (CurMBB == Succ1MBB) {
739 std::swap(Succ0MBB, Succ1MBB);
740 SDOperand True = DAG.getConstant(1, Cond.getValueType());
741 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
743 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
744 DAG.getBasicBlock(Succ0MBB));
745 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
746 DAG.getBasicBlock(Succ1MBB)));
751 /// visitSwitchCase - Emits the necessary code to represent a single node in
752 /// the binary search tree resulting from lowering a switch instruction.
753 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
754 SDOperand SwitchOp = getValue(CB.SwitchV);
755 SDOperand CaseOp = getValue(CB.CaseC);
756 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
758 // Set NextBlock to be the MBB immediately after the current one, if any.
759 // This is used to avoid emitting unnecessary branches to the next block.
760 MachineBasicBlock *NextBlock = 0;
761 MachineFunction::iterator BBI = CurMBB;
762 if (++BBI != CurMBB->getParent()->end())
765 // If the lhs block is the next block, invert the condition so that we can
766 // fall through to the lhs instead of the rhs block.
767 if (CB.LHSBB == NextBlock) {
768 std::swap(CB.LHSBB, CB.RHSBB);
769 SDOperand True = DAG.getConstant(1, Cond.getValueType());
770 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
772 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
773 DAG.getBasicBlock(CB.LHSBB));
774 if (CB.RHSBB == NextBlock)
777 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
778 DAG.getBasicBlock(CB.RHSBB)));
779 // Update successor info
780 CurMBB->addSuccessor(CB.LHSBB);
781 CurMBB->addSuccessor(CB.RHSBB);
784 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
785 // Figure out which block is immediately after the current one.
786 MachineBasicBlock *NextBlock = 0;
787 MachineFunction::iterator BBI = CurMBB;
788 if (++BBI != CurMBB->getParent()->end())
791 // If there is only the default destination, branch to it if it is not the
792 // next basic block. Otherwise, just fall through.
793 if (I.getNumOperands() == 2) {
794 // Update machine-CFG edges.
795 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
796 // If this is not a fall-through branch, emit the branch.
797 if (DefaultMBB != NextBlock)
798 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
799 DAG.getBasicBlock(DefaultMBB)));
803 // If there are any non-default case statements, create a vector of Cases
804 // representing each one, and sort the vector so that we can efficiently
805 // create a binary search tree from them.
806 std::vector<Case> Cases;
807 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
808 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
809 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
811 std::sort(Cases.begin(), Cases.end(), CaseCmp());
813 // Get the Value to be switched on and default basic blocks, which will be
814 // inserted into CaseBlock records, representing basic blocks in the binary
816 Value *SV = I.getOperand(0);
817 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
819 // Get the current MachineFunction and LLVM basic block, for use in creating
820 // and inserting new MBBs during the creation of the binary search tree.
821 MachineFunction *CurMF = CurMBB->getParent();
822 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
824 // Push the initial CaseRec onto the worklist
825 std::vector<CaseRec> CaseVec;
826 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
828 while (!CaseVec.empty()) {
829 // Grab a record representing a case range to process off the worklist
830 CaseRec CR = CaseVec.back();
833 // Size is the number of Cases represented by this range. If Size is 1,
834 // then we are processing a leaf of the binary search tree. Otherwise,
835 // we need to pick a pivot, and push left and right ranges onto the
837 unsigned Size = CR.Range.second - CR.Range.first;
840 // Create a CaseBlock record representing a conditional branch to
841 // the Case's target mbb if the value being switched on SV is equal
842 // to C. Otherwise, branch to default.
843 Constant *C = CR.Range.first->first;
844 MachineBasicBlock *Target = CR.Range.first->second;
845 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
847 // If the MBB representing the leaf node is the current MBB, then just
848 // call visitSwitchCase to emit the code into the current block.
849 // Otherwise, push the CaseBlock onto the vector to be later processed
850 // by SDISel, and insert the node's MBB before the next MBB.
851 if (CR.CaseBB == CurMBB)
854 SwitchCases.push_back(CB);
855 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
858 // split case range at pivot
859 CaseItr Pivot = CR.Range.first + (Size / 2);
860 CaseRange LHSR(CR.Range.first, Pivot);
861 CaseRange RHSR(Pivot, CR.Range.second);
862 Constant *C = Pivot->first;
863 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
864 // We know that we branch to the LHS if the Value being switched on is
865 // less than the Pivot value, C. We use this to optimize our binary
866 // tree a bit, by recognizing that if SV is greater than or equal to the
867 // LHS's Case Value, and that Case Value is exactly one less than the
868 // Pivot's Value, then we can branch directly to the LHS's Target,
869 // rather than creating a leaf node for it.
870 if ((LHSR.second - LHSR.first) == 1 &&
871 LHSR.first->first == CR.GE &&
872 cast<ConstantIntegral>(C)->getRawValue() ==
873 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
874 LHSBB = LHSR.first->second;
876 LHSBB = new MachineBasicBlock(LLVMBB);
877 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
879 // Similar to the optimization above, if the Value being switched on is
880 // known to be less than the Constant CR.LT, and the current Case Value
881 // is CR.LT - 1, then we can branch directly to the target block for
882 // the current Case Value, rather than emitting a RHS leaf node for it.
883 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
884 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
885 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
886 RHSBB = RHSR.first->second;
888 RHSBB = new MachineBasicBlock(LLVMBB);
889 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
891 // Create a CaseBlock record representing a conditional branch to
892 // the LHS node if the value being switched on SV is less than C.
893 // Otherwise, branch to LHS.
894 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
895 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
896 if (CR.CaseBB == CurMBB)
899 SwitchCases.push_back(CB);
900 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
906 void SelectionDAGLowering::visitSub(User &I) {
908 if (I.getType()->isFloatingPoint()) {
909 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
910 if (CFP->isExactlyValue(-0.0)) {
911 SDOperand Op2 = getValue(I.getOperand(1));
912 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
916 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
919 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
921 const Type *Ty = I.getType();
922 SDOperand Op1 = getValue(I.getOperand(0));
923 SDOperand Op2 = getValue(I.getOperand(1));
925 if (Ty->isIntegral()) {
926 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
927 } else if (Ty->isFloatingPoint()) {
928 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
930 const PackedType *PTy = cast<PackedType>(Ty);
931 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
932 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
933 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
937 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
938 SDOperand Op1 = getValue(I.getOperand(0));
939 SDOperand Op2 = getValue(I.getOperand(1));
941 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
943 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
946 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
947 ISD::CondCode UnsignedOpcode) {
948 SDOperand Op1 = getValue(I.getOperand(0));
949 SDOperand Op2 = getValue(I.getOperand(1));
950 ISD::CondCode Opcode = SignedOpcode;
951 if (I.getOperand(0)->getType()->isUnsigned())
952 Opcode = UnsignedOpcode;
953 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
956 void SelectionDAGLowering::visitSelect(User &I) {
957 SDOperand Cond = getValue(I.getOperand(0));
958 SDOperand TrueVal = getValue(I.getOperand(1));
959 SDOperand FalseVal = getValue(I.getOperand(2));
960 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
964 void SelectionDAGLowering::visitCast(User &I) {
965 SDOperand N = getValue(I.getOperand(0));
966 MVT::ValueType SrcVT = N.getValueType();
967 MVT::ValueType DestVT = TLI.getValueType(I.getType());
969 if (DestVT == MVT::Vector) {
970 // This is a cast to a vector from something else. This is always a bit
971 // convert. Get information about the input vector.
972 const PackedType *DestTy = cast<PackedType>(I.getType());
973 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
974 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
975 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
976 DAG.getValueType(EltVT)));
977 } else if (SrcVT == DestVT) {
978 setValue(&I, N); // noop cast.
979 } else if (DestVT == MVT::i1) {
980 // Cast to bool is a comparison against zero, not truncation to zero.
981 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
982 DAG.getConstantFP(0.0, N.getValueType());
983 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
984 } else if (isInteger(SrcVT)) {
985 if (isInteger(DestVT)) { // Int -> Int cast
986 if (DestVT < SrcVT) // Truncating cast?
987 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
988 else if (I.getOperand(0)->getType()->isSigned())
989 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
991 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
992 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
993 if (I.getOperand(0)->getType()->isSigned())
994 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
996 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
998 assert(0 && "Unknown cast!");
1000 } else if (isFloatingPoint(SrcVT)) {
1001 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1002 if (DestVT < SrcVT) // Rounding cast?
1003 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1005 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1006 } else if (isInteger(DestVT)) { // FP -> Int cast.
1007 if (I.getType()->isSigned())
1008 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1010 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1012 assert(0 && "Unknown cast!");
1015 assert(SrcVT == MVT::Vector && "Unknown cast!");
1016 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1017 // This is a cast from a vector to something else. This is always a bit
1018 // convert. Get information about the input vector.
1019 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1023 void SelectionDAGLowering::visitInsertElement(InsertElementInst &I) {
1024 SDOperand InVec = getValue(I.getOperand(0));
1025 SDOperand InVal = getValue(I.getOperand(1));
1026 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1027 getValue(I.getOperand(2)));
1029 SDOperand Num = *(InVec.Val->op_end()-2);
1030 SDOperand Typ = *(InVec.Val->op_end()-1);
1031 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1032 InVec, InVal, InIdx, Num, Typ));
1035 void SelectionDAGLowering::visitExtractElement(ExtractElementInst &I) {
1036 SDOperand InVec = getValue(I.getOperand(0));
1037 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1038 getValue(I.getOperand(1)));
1039 SDOperand Typ = *(InVec.Val->op_end()-1);
1040 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1041 TLI.getValueType(I.getType()), InVec, InIdx));
1044 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1045 SDOperand N = getValue(I.getOperand(0));
1046 const Type *Ty = I.getOperand(0)->getType();
1047 const Type *UIntPtrTy = TD.getIntPtrType();
1049 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1052 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1053 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1056 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
1057 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1058 getIntPtrConstant(Offset));
1060 Ty = StTy->getElementType(Field);
1062 Ty = cast<SequentialType>(Ty)->getElementType();
1064 // If this is a constant subscript, handle it quickly.
1065 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1066 if (CI->getRawValue() == 0) continue;
1069 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1070 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1072 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1073 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1077 // N = N + Idx * ElementSize;
1078 uint64_t ElementSize = TD.getTypeSize(Ty);
1079 SDOperand IdxN = getValue(Idx);
1081 // If the index is smaller or larger than intptr_t, truncate or extend
1083 if (IdxN.getValueType() < N.getValueType()) {
1084 if (Idx->getType()->isSigned())
1085 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1087 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1088 } else if (IdxN.getValueType() > N.getValueType())
1089 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1091 // If this is a multiply by a power of two, turn it into a shl
1092 // immediately. This is a very common case.
1093 if (isPowerOf2_64(ElementSize)) {
1094 unsigned Amt = Log2_64(ElementSize);
1095 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1096 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1097 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1101 SDOperand Scale = getIntPtrConstant(ElementSize);
1102 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1103 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1109 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1110 // If this is a fixed sized alloca in the entry block of the function,
1111 // allocate it statically on the stack.
1112 if (FuncInfo.StaticAllocaMap.count(&I))
1113 return; // getValue will auto-populate this.
1115 const Type *Ty = I.getAllocatedType();
1116 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1117 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
1120 SDOperand AllocSize = getValue(I.getArraySize());
1121 MVT::ValueType IntPtr = TLI.getPointerTy();
1122 if (IntPtr < AllocSize.getValueType())
1123 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1124 else if (IntPtr > AllocSize.getValueType())
1125 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1127 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1128 getIntPtrConstant(TySize));
1130 // Handle alignment. If the requested alignment is less than or equal to the
1131 // stack alignment, ignore it and round the size of the allocation up to the
1132 // stack alignment size. If the size is greater than the stack alignment, we
1133 // note this in the DYNAMIC_STACKALLOC node.
1134 unsigned StackAlign =
1135 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1136 if (Align <= StackAlign) {
1138 // Add SA-1 to the size.
1139 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1140 getIntPtrConstant(StackAlign-1));
1141 // Mask out the low bits for alignment purposes.
1142 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1143 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1146 std::vector<MVT::ValueType> VTs;
1147 VTs.push_back(AllocSize.getValueType());
1148 VTs.push_back(MVT::Other);
1149 std::vector<SDOperand> Ops;
1150 Ops.push_back(getRoot());
1151 Ops.push_back(AllocSize);
1152 Ops.push_back(getIntPtrConstant(Align));
1153 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
1154 DAG.setRoot(setValue(&I, DSA).getValue(1));
1156 // Inform the Frame Information that we have just allocated a variable-sized
1158 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1161 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1162 SDOperand Ptr = getValue(I.getOperand(0));
1168 // Do not serialize non-volatile loads against each other.
1169 Root = DAG.getRoot();
1172 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1173 Root, I.isVolatile()));
1176 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1177 SDOperand SrcValue, SDOperand Root,
1180 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1181 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1182 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
1184 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
1188 DAG.setRoot(L.getValue(1));
1190 PendingLoads.push_back(L.getValue(1));
1196 void SelectionDAGLowering::visitStore(StoreInst &I) {
1197 Value *SrcV = I.getOperand(0);
1198 SDOperand Src = getValue(SrcV);
1199 SDOperand Ptr = getValue(I.getOperand(1));
1200 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1201 DAG.getSrcValue(I.getOperand(1))));
1204 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1205 /// access memory and has no other side effects at all.
1206 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1207 #define GET_NO_MEMORY_INTRINSICS
1208 #include "llvm/Intrinsics.gen"
1209 #undef GET_NO_MEMORY_INTRINSICS
1213 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1215 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1216 unsigned Intrinsic) {
1217 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1219 // Build the operand list.
1220 std::vector<SDOperand> Ops;
1221 if (HasChain) // If this intrinsic has side-effects, chainify it.
1222 Ops.push_back(getRoot());
1224 // Add the intrinsic ID as an integer operand.
1225 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1227 // Add all operands of the call to the operand list.
1228 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1229 SDOperand Op = getValue(I.getOperand(i));
1231 // If this is a vector type, force it to the right packed type.
1232 if (Op.getValueType() == MVT::Vector) {
1233 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1234 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1236 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1237 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1238 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1241 assert(TLI.isTypeLegal(Op.getValueType()) &&
1242 "Intrinsic uses a non-legal type?");
1246 std::vector<MVT::ValueType> VTs;
1247 if (I.getType() != Type::VoidTy) {
1248 MVT::ValueType VT = TLI.getValueType(I.getType());
1249 if (VT == MVT::Vector) {
1250 const PackedType *DestTy = cast<PackedType>(I.getType());
1251 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1253 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1254 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1257 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1261 VTs.push_back(MVT::Other);
1266 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1267 else if (I.getType() != Type::VoidTy)
1268 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1270 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1273 DAG.setRoot(Result.getValue(Result.Val->getNumValues()-1));
1274 if (I.getType() != Type::VoidTy) {
1275 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1276 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1277 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1278 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1279 DAG.getValueType(EVT));
1281 setValue(&I, Result);
1285 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1286 /// we want to emit this as a call to a named external function, return the name
1287 /// otherwise lower it and return null.
1289 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1290 switch (Intrinsic) {
1292 // By default, turn this into a target intrinsic node.
1293 visitTargetIntrinsic(I, Intrinsic);
1295 case Intrinsic::vastart: visitVAStart(I); return 0;
1296 case Intrinsic::vaend: visitVAEnd(I); return 0;
1297 case Intrinsic::vacopy: visitVACopy(I); return 0;
1298 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1299 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1300 case Intrinsic::setjmp:
1301 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1303 case Intrinsic::longjmp:
1304 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1306 case Intrinsic::memcpy_i32:
1307 case Intrinsic::memcpy_i64:
1308 visitMemIntrinsic(I, ISD::MEMCPY);
1310 case Intrinsic::memset_i32:
1311 case Intrinsic::memset_i64:
1312 visitMemIntrinsic(I, ISD::MEMSET);
1314 case Intrinsic::memmove_i32:
1315 case Intrinsic::memmove_i64:
1316 visitMemIntrinsic(I, ISD::MEMMOVE);
1319 case Intrinsic::dbg_stoppoint: {
1320 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1321 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1322 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1323 std::vector<SDOperand> Ops;
1325 Ops.push_back(getRoot());
1326 Ops.push_back(getValue(SPI.getLineValue()));
1327 Ops.push_back(getValue(SPI.getColumnValue()));
1329 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1330 assert(DD && "Not a debug information descriptor");
1331 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1333 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1334 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1336 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1341 case Intrinsic::dbg_region_start: {
1342 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1343 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1344 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1345 std::vector<SDOperand> Ops;
1347 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1349 Ops.push_back(getRoot());
1350 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1352 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1357 case Intrinsic::dbg_region_end: {
1358 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1359 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1360 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1361 std::vector<SDOperand> Ops;
1363 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1365 Ops.push_back(getRoot());
1366 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1368 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1373 case Intrinsic::dbg_func_start: {
1374 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1375 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1376 if (DebugInfo && FSI.getSubprogram() &&
1377 DebugInfo->Verify(FSI.getSubprogram())) {
1378 std::vector<SDOperand> Ops;
1380 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1382 Ops.push_back(getRoot());
1383 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1385 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1390 case Intrinsic::dbg_declare: {
1391 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1392 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1393 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1394 std::vector<SDOperand> Ops;
1396 SDOperand AddressOp = getValue(DI.getAddress());
1397 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
1398 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1405 case Intrinsic::isunordered_f32:
1406 case Intrinsic::isunordered_f64:
1407 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1408 getValue(I.getOperand(2)), ISD::SETUO));
1411 case Intrinsic::sqrt_f32:
1412 case Intrinsic::sqrt_f64:
1413 setValue(&I, DAG.getNode(ISD::FSQRT,
1414 getValue(I.getOperand(1)).getValueType(),
1415 getValue(I.getOperand(1))));
1417 case Intrinsic::pcmarker: {
1418 SDOperand Tmp = getValue(I.getOperand(1));
1419 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1422 case Intrinsic::readcyclecounter: {
1423 std::vector<MVT::ValueType> VTs;
1424 VTs.push_back(MVT::i64);
1425 VTs.push_back(MVT::Other);
1426 std::vector<SDOperand> Ops;
1427 Ops.push_back(getRoot());
1428 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1430 DAG.setRoot(Tmp.getValue(1));
1433 case Intrinsic::bswap_i16:
1434 case Intrinsic::bswap_i32:
1435 case Intrinsic::bswap_i64:
1436 setValue(&I, DAG.getNode(ISD::BSWAP,
1437 getValue(I.getOperand(1)).getValueType(),
1438 getValue(I.getOperand(1))));
1440 case Intrinsic::cttz_i8:
1441 case Intrinsic::cttz_i16:
1442 case Intrinsic::cttz_i32:
1443 case Intrinsic::cttz_i64:
1444 setValue(&I, DAG.getNode(ISD::CTTZ,
1445 getValue(I.getOperand(1)).getValueType(),
1446 getValue(I.getOperand(1))));
1448 case Intrinsic::ctlz_i8:
1449 case Intrinsic::ctlz_i16:
1450 case Intrinsic::ctlz_i32:
1451 case Intrinsic::ctlz_i64:
1452 setValue(&I, DAG.getNode(ISD::CTLZ,
1453 getValue(I.getOperand(1)).getValueType(),
1454 getValue(I.getOperand(1))));
1456 case Intrinsic::ctpop_i8:
1457 case Intrinsic::ctpop_i16:
1458 case Intrinsic::ctpop_i32:
1459 case Intrinsic::ctpop_i64:
1460 setValue(&I, DAG.getNode(ISD::CTPOP,
1461 getValue(I.getOperand(1)).getValueType(),
1462 getValue(I.getOperand(1))));
1464 case Intrinsic::stacksave: {
1465 std::vector<MVT::ValueType> VTs;
1466 VTs.push_back(TLI.getPointerTy());
1467 VTs.push_back(MVT::Other);
1468 std::vector<SDOperand> Ops;
1469 Ops.push_back(getRoot());
1470 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1472 DAG.setRoot(Tmp.getValue(1));
1475 case Intrinsic::stackrestore: {
1476 SDOperand Tmp = getValue(I.getOperand(1));
1477 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1480 case Intrinsic::prefetch:
1481 // FIXME: Currently discarding prefetches.
1487 void SelectionDAGLowering::visitCall(CallInst &I) {
1488 const char *RenameFn = 0;
1489 if (Function *F = I.getCalledFunction()) {
1490 if (F->isExternal())
1491 if (unsigned IID = F->getIntrinsicID()) {
1492 RenameFn = visitIntrinsicCall(I, IID);
1495 } else { // Not an LLVM intrinsic.
1496 const std::string &Name = F->getName();
1497 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1498 if (I.getNumOperands() == 3 && // Basic sanity checks.
1499 I.getOperand(1)->getType()->isFloatingPoint() &&
1500 I.getType() == I.getOperand(1)->getType() &&
1501 I.getType() == I.getOperand(2)->getType()) {
1502 SDOperand LHS = getValue(I.getOperand(1));
1503 SDOperand RHS = getValue(I.getOperand(2));
1504 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1508 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1509 if (I.getNumOperands() == 2 && // Basic sanity checks.
1510 I.getOperand(1)->getType()->isFloatingPoint() &&
1511 I.getType() == I.getOperand(1)->getType()) {
1512 SDOperand Tmp = getValue(I.getOperand(1));
1513 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1516 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1517 if (I.getNumOperands() == 2 && // Basic sanity checks.
1518 I.getOperand(1)->getType()->isFloatingPoint() &&
1519 I.getType() == I.getOperand(1)->getType()) {
1520 SDOperand Tmp = getValue(I.getOperand(1));
1521 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1524 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1525 if (I.getNumOperands() == 2 && // Basic sanity checks.
1526 I.getOperand(1)->getType()->isFloatingPoint() &&
1527 I.getType() == I.getOperand(1)->getType()) {
1528 SDOperand Tmp = getValue(I.getOperand(1));
1529 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1534 } else if (isa<InlineAsm>(I.getOperand(0))) {
1541 Callee = getValue(I.getOperand(0));
1543 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1544 std::vector<std::pair<SDOperand, const Type*> > Args;
1545 Args.reserve(I.getNumOperands());
1546 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1547 Value *Arg = I.getOperand(i);
1548 SDOperand ArgNode = getValue(Arg);
1549 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1552 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1553 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1555 std::pair<SDOperand,SDOperand> Result =
1556 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1557 I.isTailCall(), Callee, Args, DAG);
1558 if (I.getType() != Type::VoidTy)
1559 setValue(&I, Result.first);
1560 DAG.setRoot(Result.second);
1563 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1564 SDOperand &Chain, SDOperand &Flag)const{
1565 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1566 Chain = Val.getValue(1);
1567 Flag = Val.getValue(2);
1569 // If the result was expanded, copy from the top part.
1570 if (Regs.size() > 1) {
1571 assert(Regs.size() == 2 &&
1572 "Cannot expand to more than 2 elts yet!");
1573 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1574 Chain = Val.getValue(1);
1575 Flag = Val.getValue(2);
1576 if (DAG.getTargetLoweringInfo().isLittleEndian())
1577 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1579 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
1582 // Otherwise, if the return value was promoted, truncate it to the
1583 // appropriate type.
1584 if (RegVT == ValueVT)
1587 if (MVT::isInteger(RegVT))
1588 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1590 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1593 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1594 /// specified value into the registers specified by this object. This uses
1595 /// Chain/Flag as the input and updates them for the output Chain/Flag.
1596 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1597 SDOperand &Chain, SDOperand &Flag) const {
1598 if (Regs.size() == 1) {
1599 // If there is a single register and the types differ, this must be
1601 if (RegVT != ValueVT) {
1602 if (MVT::isInteger(RegVT))
1603 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1605 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1607 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1608 Flag = Chain.getValue(1);
1610 std::vector<unsigned> R(Regs);
1611 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1612 std::reverse(R.begin(), R.end());
1614 for (unsigned i = 0, e = R.size(); i != e; ++i) {
1615 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1616 DAG.getConstant(i, MVT::i32));
1617 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
1618 Flag = Chain.getValue(1);
1623 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
1624 /// operand list. This adds the code marker and includes the number of
1625 /// values added into it.
1626 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1627 std::vector<SDOperand> &Ops) const {
1628 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1629 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1630 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1633 /// isAllocatableRegister - If the specified register is safe to allocate,
1634 /// i.e. it isn't a stack pointer or some other special register, return the
1635 /// register class for the register. Otherwise, return null.
1636 static const TargetRegisterClass *
1637 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1638 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1639 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1640 E = MRI->regclass_end(); RCI != E; ++RCI) {
1641 const TargetRegisterClass *RC = *RCI;
1642 // If none of the the value types for this register class are valid, we
1643 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1644 bool isLegal = false;
1645 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1647 if (TLI.isTypeLegal(*I)) {
1653 if (!isLegal) continue;
1655 // NOTE: This isn't ideal. In particular, this might allocate the
1656 // frame pointer in functions that need it (due to them not being taken
1657 // out of allocation, because a variable sized allocation hasn't been seen
1658 // yet). This is a slight code pessimization, but should still work.
1659 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1660 E = RC->allocation_order_end(MF); I != E; ++I)
1667 RegsForValue SelectionDAGLowering::
1668 GetRegistersForValue(const std::string &ConstrCode,
1669 MVT::ValueType VT, bool isOutReg, bool isInReg,
1670 std::set<unsigned> &OutputRegs,
1671 std::set<unsigned> &InputRegs) {
1672 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1673 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1674 std::vector<unsigned> Regs;
1676 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1677 MVT::ValueType RegVT;
1678 MVT::ValueType ValueVT = VT;
1680 if (PhysReg.first) {
1681 if (VT == MVT::Other)
1682 ValueVT = *PhysReg.second->vt_begin();
1685 // This is a explicit reference to a physical register.
1686 Regs.push_back(PhysReg.first);
1688 // If this is an expanded reference, add the rest of the regs to Regs.
1690 RegVT = *PhysReg.second->vt_begin();
1691 TargetRegisterClass::iterator I = PhysReg.second->begin();
1692 TargetRegisterClass::iterator E = PhysReg.second->end();
1693 for (; *I != PhysReg.first; ++I)
1694 assert(I != E && "Didn't find reg!");
1696 // Already added the first reg.
1698 for (; NumRegs; --NumRegs, ++I) {
1699 assert(I != E && "Ran out of registers to allocate!");
1703 return RegsForValue(Regs, RegVT, ValueVT);
1706 // This is a reference to a register class. Allocate NumRegs consecutive,
1707 // available, registers from the class.
1708 std::vector<unsigned> RegClassRegs =
1709 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1711 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1712 MachineFunction &MF = *CurMBB->getParent();
1713 unsigned NumAllocated = 0;
1714 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1715 unsigned Reg = RegClassRegs[i];
1716 // See if this register is available.
1717 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1718 (isInReg && InputRegs.count(Reg))) { // Already used.
1719 // Make sure we find consecutive registers.
1724 // Check to see if this register is allocatable (i.e. don't give out the
1726 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1728 // Make sure we find consecutive registers.
1733 // Okay, this register is good, we can use it.
1736 // If we allocated enough consecutive
1737 if (NumAllocated == NumRegs) {
1738 unsigned RegStart = (i-NumAllocated)+1;
1739 unsigned RegEnd = i+1;
1740 // Mark all of the allocated registers used.
1741 for (unsigned i = RegStart; i != RegEnd; ++i) {
1742 unsigned Reg = RegClassRegs[i];
1743 Regs.push_back(Reg);
1744 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1745 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1748 return RegsForValue(Regs, *RC->vt_begin(), VT);
1752 // Otherwise, we couldn't allocate enough registers for this.
1753 return RegsForValue();
1757 /// visitInlineAsm - Handle a call to an InlineAsm object.
1759 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1760 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1762 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1765 // Note, we treat inline asms both with and without side-effects as the same.
1766 // If an inline asm doesn't have side effects and doesn't access memory, we
1767 // could not choose to not chain it.
1768 bool hasSideEffects = IA->hasSideEffects();
1770 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1771 std::vector<MVT::ValueType> ConstraintVTs;
1773 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1774 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1775 /// if it is a def of that register.
1776 std::vector<SDOperand> AsmNodeOperands;
1777 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1778 AsmNodeOperands.push_back(AsmStr);
1780 SDOperand Chain = getRoot();
1783 // We fully assign registers here at isel time. This is not optimal, but
1784 // should work. For register classes that correspond to LLVM classes, we
1785 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1786 // over the constraints, collecting fixed registers that we know we can't use.
1787 std::set<unsigned> OutputRegs, InputRegs;
1789 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1790 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1791 std::string &ConstraintCode = Constraints[i].Codes[0];
1793 MVT::ValueType OpVT;
1795 // Compute the value type for each operand and add it to ConstraintVTs.
1796 switch (Constraints[i].Type) {
1797 case InlineAsm::isOutput:
1798 if (!Constraints[i].isIndirectOutput) {
1799 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1800 OpVT = TLI.getValueType(I.getType());
1802 const Type *OpTy = I.getOperand(OpNum)->getType();
1803 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1804 OpNum++; // Consumes a call operand.
1807 case InlineAsm::isInput:
1808 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1809 OpNum++; // Consumes a call operand.
1811 case InlineAsm::isClobber:
1816 ConstraintVTs.push_back(OpVT);
1818 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1819 continue; // Not assigned a fixed reg.
1821 // Build a list of regs that this operand uses. This always has a single
1822 // element for promoted/expanded operands.
1823 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1825 OutputRegs, InputRegs);
1827 switch (Constraints[i].Type) {
1828 case InlineAsm::isOutput:
1829 // We can't assign any other output to this register.
1830 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1831 // If this is an early-clobber output, it cannot be assigned to the same
1832 // value as the input reg.
1833 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1834 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1836 case InlineAsm::isInput:
1837 // We can't assign any other input to this register.
1838 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1840 case InlineAsm::isClobber:
1841 // Clobbered regs cannot be used as inputs or outputs.
1842 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1843 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1848 // Loop over all of the inputs, copying the operand values into the
1849 // appropriate registers and processing the output regs.
1850 RegsForValue RetValRegs;
1851 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
1854 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1855 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1856 std::string &ConstraintCode = Constraints[i].Codes[0];
1858 switch (Constraints[i].Type) {
1859 case InlineAsm::isOutput: {
1860 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1861 if (ConstraintCode.size() == 1) // not a physreg name.
1862 CTy = TLI.getConstraintType(ConstraintCode[0]);
1864 if (CTy == TargetLowering::C_Memory) {
1866 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1868 // Check that the operand (the address to store to) isn't a float.
1869 if (!MVT::isInteger(InOperandVal.getValueType()))
1870 assert(0 && "MATCH FAIL!");
1872 if (!Constraints[i].isIndirectOutput)
1873 assert(0 && "MATCH FAIL!");
1875 OpNum++; // Consumes a call operand.
1877 // Extend/truncate to the right pointer type if needed.
1878 MVT::ValueType PtrType = TLI.getPointerTy();
1879 if (InOperandVal.getValueType() < PtrType)
1880 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1881 else if (InOperandVal.getValueType() > PtrType)
1882 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1884 // Add information to the INLINEASM node to know about this output.
1885 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1886 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1887 AsmNodeOperands.push_back(InOperandVal);
1891 // Otherwise, this is a register output.
1892 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1894 // If this is an early-clobber output, or if there is an input
1895 // constraint that matches this, we need to reserve the input register
1896 // so no other inputs allocate to it.
1897 bool UsesInputRegister = false;
1898 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1899 UsesInputRegister = true;
1901 // Copy the output from the appropriate register. Find a register that
1904 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1905 true, UsesInputRegister,
1906 OutputRegs, InputRegs);
1907 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
1909 if (!Constraints[i].isIndirectOutput) {
1910 assert(RetValRegs.Regs.empty() &&
1911 "Cannot have multiple output constraints yet!");
1912 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1915 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1916 I.getOperand(OpNum)));
1917 OpNum++; // Consumes a call operand.
1920 // Add information to the INLINEASM node to know that this register is
1922 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
1925 case InlineAsm::isInput: {
1926 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1927 OpNum++; // Consumes a call operand.
1929 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1930 // If this is required to match an output register we have already set,
1931 // just use its register.
1932 unsigned OperandNo = atoi(ConstraintCode.c_str());
1934 // Scan until we find the definition we already emitted of this operand.
1935 // When we find it, create a RegsForValue operand.
1936 unsigned CurOp = 2; // The first operand.
1937 for (; OperandNo; --OperandNo) {
1938 // Advance to the next operand.
1940 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1941 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1942 "Skipped past definitions?");
1943 CurOp += (NumOps>>3)+1;
1947 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1948 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1949 "Skipped past definitions?");
1951 // Add NumOps>>3 registers to MatchedRegs.
1952 RegsForValue MatchedRegs;
1953 MatchedRegs.ValueVT = InOperandVal.getValueType();
1954 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1955 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1956 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1957 MatchedRegs.Regs.push_back(Reg);
1960 // Use the produced MatchedRegs object to
1961 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1962 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
1966 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1967 if (ConstraintCode.size() == 1) // not a physreg name.
1968 CTy = TLI.getConstraintType(ConstraintCode[0]);
1970 if (CTy == TargetLowering::C_Other) {
1971 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1972 assert(0 && "MATCH FAIL!");
1974 // Add information to the INLINEASM node to know about this input.
1975 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1976 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1977 AsmNodeOperands.push_back(InOperandVal);
1979 } else if (CTy == TargetLowering::C_Memory) {
1982 // Check that the operand isn't a float.
1983 if (!MVT::isInteger(InOperandVal.getValueType()))
1984 assert(0 && "MATCH FAIL!");
1986 // Extend/truncate to the right pointer type if needed.
1987 MVT::ValueType PtrType = TLI.getPointerTy();
1988 if (InOperandVal.getValueType() < PtrType)
1989 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1990 else if (InOperandVal.getValueType() > PtrType)
1991 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1993 // Add information to the INLINEASM node to know about this input.
1994 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1995 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1996 AsmNodeOperands.push_back(InOperandVal);
2000 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2002 // Copy the input into the appropriate registers.
2003 RegsForValue InRegs =
2004 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2005 false, true, OutputRegs, InputRegs);
2006 // FIXME: should be match fail.
2007 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2009 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2011 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2014 case InlineAsm::isClobber: {
2015 RegsForValue ClobberedRegs =
2016 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2017 OutputRegs, InputRegs);
2018 // Add the clobbered value to the operand list, so that the register
2019 // allocator is aware that the physreg got clobbered.
2020 if (!ClobberedRegs.Regs.empty())
2021 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2027 // Finish up input operands.
2028 AsmNodeOperands[0] = Chain;
2029 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2031 std::vector<MVT::ValueType> VTs;
2032 VTs.push_back(MVT::Other);
2033 VTs.push_back(MVT::Flag);
2034 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2035 Flag = Chain.getValue(1);
2037 // If this asm returns a register value, copy the result from that register
2038 // and set it as the value of the call.
2039 if (!RetValRegs.Regs.empty())
2040 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2042 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2044 // Process indirect outputs, first output all of the flagged copies out of
2046 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2047 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2048 Value *Ptr = IndirectStoresToEmit[i].second;
2049 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2050 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2053 // Emit the non-flagged stores from the physregs.
2054 std::vector<SDOperand> OutChains;
2055 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2056 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2057 StoresToEmit[i].first,
2058 getValue(StoresToEmit[i].second),
2059 DAG.getSrcValue(StoresToEmit[i].second)));
2060 if (!OutChains.empty())
2061 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2066 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2067 SDOperand Src = getValue(I.getOperand(0));
2069 MVT::ValueType IntPtr = TLI.getPointerTy();
2071 if (IntPtr < Src.getValueType())
2072 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2073 else if (IntPtr > Src.getValueType())
2074 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2076 // Scale the source by the type size.
2077 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
2078 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2079 Src, getIntPtrConstant(ElementSize));
2081 std::vector<std::pair<SDOperand, const Type*> > Args;
2082 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
2084 std::pair<SDOperand,SDOperand> Result =
2085 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2086 DAG.getExternalSymbol("malloc", IntPtr),
2088 setValue(&I, Result.first); // Pointers always fit in registers
2089 DAG.setRoot(Result.second);
2092 void SelectionDAGLowering::visitFree(FreeInst &I) {
2093 std::vector<std::pair<SDOperand, const Type*> > Args;
2094 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2095 TLI.getTargetData().getIntPtrType()));
2096 MVT::ValueType IntPtr = TLI.getPointerTy();
2097 std::pair<SDOperand,SDOperand> Result =
2098 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2099 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2100 DAG.setRoot(Result.second);
2103 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2104 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2105 // instructions are special in various ways, which require special support to
2106 // insert. The specified MachineInstr is created but not inserted into any
2107 // basic blocks, and the scheduler passes ownership of it to this method.
2108 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2109 MachineBasicBlock *MBB) {
2110 std::cerr << "If a target marks an instruction with "
2111 "'usesCustomDAGSchedInserter', it must implement "
2112 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2117 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2118 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2119 getValue(I.getOperand(1)),
2120 DAG.getSrcValue(I.getOperand(1))));
2123 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2124 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2125 getValue(I.getOperand(0)),
2126 DAG.getSrcValue(I.getOperand(0)));
2128 DAG.setRoot(V.getValue(1));
2131 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2132 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2133 getValue(I.getOperand(1)),
2134 DAG.getSrcValue(I.getOperand(1))));
2137 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2138 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2139 getValue(I.getOperand(1)),
2140 getValue(I.getOperand(2)),
2141 DAG.getSrcValue(I.getOperand(1)),
2142 DAG.getSrcValue(I.getOperand(2))));
2145 // It is always conservatively correct for llvm.returnaddress and
2146 // llvm.frameaddress to return 0.
2147 std::pair<SDOperand, SDOperand>
2148 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2149 unsigned Depth, SelectionDAG &DAG) {
2150 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
2153 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
2154 assert(0 && "LowerOperation not implemented for this target!");
2159 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2160 SelectionDAG &DAG) {
2161 assert(0 && "CustomPromoteOperation not implemented for this target!");
2166 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2167 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2168 std::pair<SDOperand,SDOperand> Result =
2169 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
2170 setValue(&I, Result.first);
2171 DAG.setRoot(Result.second);
2174 /// getMemsetValue - Vectorized representation of the memset value
2176 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2177 SelectionDAG &DAG) {
2178 MVT::ValueType CurVT = VT;
2179 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2180 uint64_t Val = C->getValue() & 255;
2182 while (CurVT != MVT::i8) {
2183 Val = (Val << Shift) | Val;
2185 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2187 return DAG.getConstant(Val, VT);
2189 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2191 while (CurVT != MVT::i8) {
2193 DAG.getNode(ISD::OR, VT,
2194 DAG.getNode(ISD::SHL, VT, Value,
2195 DAG.getConstant(Shift, MVT::i8)), Value);
2197 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2204 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2205 /// used when a memcpy is turned into a memset when the source is a constant
2207 static SDOperand getMemsetStringVal(MVT::ValueType VT,
2208 SelectionDAG &DAG, TargetLowering &TLI,
2209 std::string &Str, unsigned Offset) {
2210 MVT::ValueType CurVT = VT;
2212 unsigned MSB = getSizeInBits(VT) / 8;
2213 if (TLI.isLittleEndian())
2214 Offset = Offset + MSB - 1;
2215 for (unsigned i = 0; i != MSB; ++i) {
2216 Val = (Val << 8) | Str[Offset];
2217 Offset += TLI.isLittleEndian() ? -1 : 1;
2219 return DAG.getConstant(Val, VT);
2222 /// getMemBasePlusOffset - Returns base and offset node for the
2223 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2224 SelectionDAG &DAG, TargetLowering &TLI) {
2225 MVT::ValueType VT = Base.getValueType();
2226 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2229 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2230 /// to replace the memset / memcpy is below the threshold. It also returns the
2231 /// types of the sequence of memory ops to perform memset / memcpy.
2232 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2233 unsigned Limit, uint64_t Size,
2234 unsigned Align, TargetLowering &TLI) {
2237 if (TLI.allowsUnalignedMemoryAccesses()) {
2240 switch (Align & 7) {
2256 MVT::ValueType LVT = MVT::i64;
2257 while (!TLI.isTypeLegal(LVT))
2258 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2259 assert(MVT::isInteger(LVT));
2264 unsigned NumMemOps = 0;
2266 unsigned VTSize = getSizeInBits(VT) / 8;
2267 while (VTSize > Size) {
2268 VT = (MVT::ValueType)((unsigned)VT - 1);
2271 assert(MVT::isInteger(VT));
2273 if (++NumMemOps > Limit)
2275 MemOps.push_back(VT);
2282 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
2283 SDOperand Op1 = getValue(I.getOperand(1));
2284 SDOperand Op2 = getValue(I.getOperand(2));
2285 SDOperand Op3 = getValue(I.getOperand(3));
2286 SDOperand Op4 = getValue(I.getOperand(4));
2287 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2288 if (Align == 0) Align = 1;
2290 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2291 std::vector<MVT::ValueType> MemOps;
2293 // Expand memset / memcpy to a series of load / store ops
2294 // if the size operand falls below a certain threshold.
2295 std::vector<SDOperand> OutChains;
2297 default: break; // Do nothing for now.
2299 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2300 Size->getValue(), Align, TLI)) {
2301 unsigned NumMemOps = MemOps.size();
2302 unsigned Offset = 0;
2303 for (unsigned i = 0; i < NumMemOps; i++) {
2304 MVT::ValueType VT = MemOps[i];
2305 unsigned VTSize = getSizeInBits(VT) / 8;
2306 SDOperand Value = getMemsetValue(Op2, VT, DAG);
2307 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2309 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2310 DAG.getSrcValue(I.getOperand(1), Offset));
2311 OutChains.push_back(Store);
2318 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2319 Size->getValue(), Align, TLI)) {
2320 unsigned NumMemOps = MemOps.size();
2321 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
2322 GlobalAddressSDNode *G = NULL;
2324 bool CopyFromStr = false;
2326 if (Op2.getOpcode() == ISD::GlobalAddress)
2327 G = cast<GlobalAddressSDNode>(Op2);
2328 else if (Op2.getOpcode() == ISD::ADD &&
2329 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2330 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2331 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
2332 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
2335 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2337 Str = GV->getStringValue(false);
2345 for (unsigned i = 0; i < NumMemOps; i++) {
2346 MVT::ValueType VT = MemOps[i];
2347 unsigned VTSize = getSizeInBits(VT) / 8;
2348 SDOperand Value, Chain, Store;
2351 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2354 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2355 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2356 DAG.getSrcValue(I.getOperand(1), DstOff));
2358 Value = DAG.getLoad(VT, getRoot(),
2359 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2360 DAG.getSrcValue(I.getOperand(2), SrcOff));
2361 Chain = Value.getValue(1);
2363 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2364 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2365 DAG.getSrcValue(I.getOperand(1), DstOff));
2367 OutChains.push_back(Store);
2376 if (!OutChains.empty()) {
2377 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2382 std::vector<SDOperand> Ops;
2383 Ops.push_back(getRoot());
2388 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
2391 //===----------------------------------------------------------------------===//
2392 // SelectionDAGISel code
2393 //===----------------------------------------------------------------------===//
2395 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2396 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2399 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
2400 // FIXME: we only modify the CFG to split critical edges. This
2401 // updates dom and loop info.
2405 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2406 /// casting to the type of GEPI.
2407 static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2408 Value *Ptr, Value *PtrOffset) {
2409 if (V) return V; // Already computed.
2411 BasicBlock::iterator InsertPt;
2412 if (BB == GEPI->getParent()) {
2413 // If insert into the GEP's block, insert right after the GEP.
2417 // Otherwise, insert at the top of BB, after any PHI nodes
2418 InsertPt = BB->begin();
2419 while (isa<PHINode>(InsertPt)) ++InsertPt;
2422 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2423 // BB so that there is only one value live across basic blocks (the cast
2425 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2426 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2427 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2429 // Add the offset, cast it to the right type.
2430 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2431 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2436 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2437 /// selection, we want to be a bit careful about some things. In particular, if
2438 /// we have a GEP instruction that is used in a different block than it is
2439 /// defined, the addressing expression of the GEP cannot be folded into loads or
2440 /// stores that use it. In this case, decompose the GEP and move constant
2441 /// indices into blocks that use it.
2442 static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2443 const TargetData &TD) {
2444 // If this GEP is only used inside the block it is defined in, there is no
2445 // need to rewrite it.
2446 bool isUsedOutsideDefBB = false;
2447 BasicBlock *DefBB = GEPI->getParent();
2448 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2450 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2451 isUsedOutsideDefBB = true;
2455 if (!isUsedOutsideDefBB) return;
2457 // If this GEP has no non-zero constant indices, there is nothing we can do,
2459 bool hasConstantIndex = false;
2460 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2461 E = GEPI->op_end(); OI != E; ++OI) {
2462 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2463 if (CI->getRawValue()) {
2464 hasConstantIndex = true;
2468 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2469 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
2471 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2472 // constant offset (which we now know is non-zero) and deal with it later.
2473 uint64_t ConstantOffset = 0;
2474 const Type *UIntPtrTy = TD.getIntPtrType();
2475 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2476 const Type *Ty = GEPI->getOperand(0)->getType();
2478 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2479 E = GEPI->op_end(); OI != E; ++OI) {
2481 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2482 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2484 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2485 Ty = StTy->getElementType(Field);
2487 Ty = cast<SequentialType>(Ty)->getElementType();
2489 // Handle constant subscripts.
2490 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2491 if (CI->getRawValue() == 0) continue;
2493 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2494 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2496 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2500 // Ptr = Ptr + Idx * ElementSize;
2502 // Cast Idx to UIntPtrTy if needed.
2503 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2505 uint64_t ElementSize = TD.getTypeSize(Ty);
2506 // Mask off bits that should not be set.
2507 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2508 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2510 // Multiply by the element size and add to the base.
2511 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2512 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2516 // Make sure that the offset fits in uintptr_t.
2517 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2518 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2520 // Okay, we have now emitted all of the variable index parts to the BB that
2521 // the GEP is defined in. Loop over all of the using instructions, inserting
2522 // an "add Ptr, ConstantOffset" into each block that uses it and update the
2523 // instruction to use the newly computed value, making GEPI dead. When the
2524 // user is a load or store instruction address, we emit the add into the user
2525 // block, otherwise we use a canonical version right next to the gep (these
2526 // won't be foldable as addresses, so we might as well share the computation).
2528 std::map<BasicBlock*,Value*> InsertedExprs;
2529 while (!GEPI->use_empty()) {
2530 Instruction *User = cast<Instruction>(GEPI->use_back());
2532 // If this use is not foldable into the addressing mode, use a version
2533 // emitted in the GEP block.
2535 if (!isa<LoadInst>(User) &&
2536 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2537 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2540 // Otherwise, insert the code in the User's block so it can be folded into
2541 // any users in that block.
2542 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
2543 User->getParent(), GEPI,
2546 User->replaceUsesOfWith(GEPI, NewVal);
2549 // Finally, the GEP is dead, remove it.
2550 GEPI->eraseFromParent();
2553 bool SelectionDAGISel::runOnFunction(Function &Fn) {
2554 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2555 RegMap = MF.getSSARegMap();
2556 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2558 // First, split all critical edges for PHI nodes with incoming values that are
2559 // constants, this way the load of the constant into a vreg will not be placed
2560 // into MBBs that are used some other way.
2562 // In this pass we also look for GEP instructions that are used across basic
2563 // blocks and rewrites them to improve basic-block-at-a-time selection.
2565 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2567 BasicBlock::iterator BBI;
2568 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
2569 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2570 if (isa<Constant>(PN->getIncomingValue(i)))
2571 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
2573 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2574 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2575 OptimizeGEPExpression(GEPI, TLI.getTargetData());
2578 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2580 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2581 SelectBasicBlock(I, MF, FuncInfo);
2587 SDOperand SelectionDAGISel::
2588 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
2589 SDOperand Op = SDL.getValue(V);
2590 assert((Op.getOpcode() != ISD::CopyFromReg ||
2591 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
2592 "Copy from a reg to the same reg!");
2594 // If this type is not legal, we must make sure to not create an invalid
2596 MVT::ValueType SrcVT = Op.getValueType();
2597 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2598 SelectionDAG &DAG = SDL.DAG;
2599 if (SrcVT == DestVT) {
2600 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2601 } else if (SrcVT == MVT::Vector) {
2602 // FIXME: THIS DOES NOT SUPPORT PROMOTED/EXPANDED ELEMENTS!
2604 // Figure out the right, legal destination reg to copy into.
2605 const PackedType *PTy = cast<PackedType>(V->getType());
2606 unsigned NumElts = PTy->getNumElements();
2607 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
2609 unsigned NumVectorRegs = 1;
2611 // Divide the input until we get to a supported size. This will always
2612 // end with a scalar if the target doesn't support vectors.
2613 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
2615 NumVectorRegs <<= 1;
2622 VT = getVectorType(EltTy, NumElts);
2624 // FIXME: THIS ASSUMES THAT THE INPUT VECTOR WILL BE LEGAL!
2625 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
2626 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2627 } else if (SrcVT < DestVT) {
2628 // The src value is promoted to the register.
2629 if (MVT::isFloatingPoint(SrcVT))
2630 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2632 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
2633 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2635 // The src value is expanded into multiple registers.
2636 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2637 Op, DAG.getConstant(0, MVT::i32));
2638 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2639 Op, DAG.getConstant(1, MVT::i32));
2640 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2641 return DAG.getCopyToReg(Op, Reg+1, Hi);
2645 void SelectionDAGISel::
2646 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2647 std::vector<SDOperand> &UnorderedChains) {
2648 // If this is the entry block, emit arguments.
2649 Function &F = *BB->getParent();
2650 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
2651 SDOperand OldRoot = SDL.DAG.getRoot();
2652 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
2655 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2657 if (!AI->use_empty()) {
2658 SDL.setValue(AI, Args[a]);
2660 // If this argument is live outside of the entry block, insert a copy from
2661 // whereever we got it to the vreg that other BB's will reference it as.
2662 if (FuncInfo.ValueMap.count(AI)) {
2664 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2665 UnorderedChains.push_back(Copy);
2669 // Next, if the function has live ins that need to be copied into vregs,
2670 // emit the copies now, into the top of the block.
2671 MachineFunction &MF = SDL.DAG.getMachineFunction();
2672 if (MF.livein_begin() != MF.livein_end()) {
2673 SSARegMap *RegMap = MF.getSSARegMap();
2674 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2675 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2676 E = MF.livein_end(); LI != E; ++LI)
2678 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2679 LI->first, RegMap->getRegClass(LI->second));
2682 // Finally, if the target has anything special to do, allow it to do so.
2683 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
2687 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2688 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2689 FunctionLoweringInfo &FuncInfo) {
2690 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
2692 std::vector<SDOperand> UnorderedChains;
2694 // Lower any arguments needed in this block if this is the entry block.
2695 if (LLVMBB == &LLVMBB->getParent()->front())
2696 LowerArguments(LLVMBB, SDL, UnorderedChains);
2698 BB = FuncInfo.MBBMap[LLVMBB];
2699 SDL.setCurrentBasicBlock(BB);
2701 // Lower all of the non-terminator instructions.
2702 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2706 // Ensure that all instructions which are used outside of their defining
2707 // blocks are available as virtual registers.
2708 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
2709 if (!I->use_empty() && !isa<PHINode>(I)) {
2710 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
2711 if (VMI != FuncInfo.ValueMap.end())
2712 UnorderedChains.push_back(
2713 CopyValueToVirtualRegister(SDL, I, VMI->second));
2716 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2717 // ensure constants are generated when needed. Remember the virtual registers
2718 // that need to be added to the Machine PHI nodes as input. We cannot just
2719 // directly add them, because expansion might result in multiple MBB's for one
2720 // BB. As such, the start of the BB might correspond to a different MBB than
2724 // Emit constants only once even if used by multiple PHI nodes.
2725 std::map<Constant*, unsigned> ConstantsOut;
2727 // Check successor nodes PHI nodes that expect a constant to be available from
2729 TerminatorInst *TI = LLVMBB->getTerminator();
2730 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2731 BasicBlock *SuccBB = TI->getSuccessor(succ);
2732 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2735 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2736 // nodes and Machine PHI nodes, but the incoming operands have not been
2738 for (BasicBlock::iterator I = SuccBB->begin();
2739 (PN = dyn_cast<PHINode>(I)); ++I)
2740 if (!PN->use_empty()) {
2742 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2743 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2744 unsigned &RegOut = ConstantsOut[C];
2746 RegOut = FuncInfo.CreateRegForValue(C);
2747 UnorderedChains.push_back(
2748 CopyValueToVirtualRegister(SDL, C, RegOut));
2752 Reg = FuncInfo.ValueMap[PHIOp];
2754 assert(isa<AllocaInst>(PHIOp) &&
2755 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2756 "Didn't codegen value into a register!??");
2757 Reg = FuncInfo.CreateRegForValue(PHIOp);
2758 UnorderedChains.push_back(
2759 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
2763 // Remember that this register needs to added to the machine PHI node as
2764 // the input for this MBB.
2765 unsigned NumElements =
2766 TLI.getNumElements(TLI.getValueType(PN->getType()));
2767 for (unsigned i = 0, e = NumElements; i != e; ++i)
2768 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
2771 ConstantsOut.clear();
2773 // Turn all of the unordered chains into one factored node.
2774 if (!UnorderedChains.empty()) {
2775 SDOperand Root = SDL.getRoot();
2776 if (Root.getOpcode() != ISD::EntryToken) {
2777 unsigned i = 0, e = UnorderedChains.size();
2778 for (; i != e; ++i) {
2779 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2780 if (UnorderedChains[i].Val->getOperand(0) == Root)
2781 break; // Don't add the root if we already indirectly depend on it.
2785 UnorderedChains.push_back(Root);
2787 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2790 // Lower the terminator after the copies are emitted.
2791 SDL.visit(*LLVMBB->getTerminator());
2793 // Copy over any CaseBlock records that may now exist due to SwitchInst
2795 SwitchCases.clear();
2796 SwitchCases = SDL.SwitchCases;
2798 // Make sure the root of the DAG is up-to-date.
2799 DAG.setRoot(SDL.getRoot());
2802 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
2803 // Run the DAG combiner in pre-legalize mode.
2806 DEBUG(std::cerr << "Lowered selection DAG:\n");
2809 // Second step, hack on the DAG until it only uses operations and types that
2810 // the target supports.
2813 DEBUG(std::cerr << "Legalized selection DAG:\n");
2816 // Run the DAG combiner in post-legalize mode.
2819 if (ViewISelDAGs) DAG.viewGraph();
2821 // Third, instruction select all of the operations to machine code, adding the
2822 // code to the MachineBasicBlock.
2823 InstructionSelectBasicBlock(DAG);
2825 DEBUG(std::cerr << "Selected machine code:\n");
2829 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2830 FunctionLoweringInfo &FuncInfo) {
2831 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2833 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2836 // First step, lower LLVM code to some DAG. This DAG may use operations and
2837 // types that are not supported by the target.
2838 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2840 // Second step, emit the lowered DAG as machine code.
2841 CodeGenAndEmitDAG(DAG);
2844 // Next, now that we know what the last MBB the LLVM BB expanded is, update
2845 // PHI nodes in successors.
2846 if (SwitchCases.empty()) {
2847 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2848 MachineInstr *PHI = PHINodesToUpdate[i].first;
2849 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2850 "This is not a machine PHI node that we are updating!");
2851 PHI->addRegOperand(PHINodesToUpdate[i].second);
2852 PHI->addMachineBasicBlockOperand(BB);
2857 // If we generated any switch lowering information, build and codegen any
2858 // additional DAGs necessary.
2859 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
2860 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2862 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
2863 // Set the current basic block to the mbb we wish to insert the code into
2864 BB = SwitchCases[i].ThisBB;
2865 SDL.setCurrentBasicBlock(BB);
2867 SDL.visitSwitchCase(SwitchCases[i]);
2868 SDAG.setRoot(SDL.getRoot());
2869 CodeGenAndEmitDAG(SDAG);
2870 // Iterate over the phi nodes, if there is a phi node in a successor of this
2871 // block (for instance, the default block), then add a pair of operands to
2872 // the phi node for this block, as if we were coming from the original
2873 // BB before switch expansion.
2874 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
2875 MachineInstr *PHI = PHINodesToUpdate[pi].first;
2876 MachineBasicBlock *PHIBB = PHI->getParent();
2877 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2878 "This is not a machine PHI node that we are updating!");
2879 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
2880 PHI->addRegOperand(PHINodesToUpdate[pi].second);
2881 PHI->addMachineBasicBlockOperand(BB);
2887 //===----------------------------------------------------------------------===//
2888 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2889 /// target node in the graph.
2890 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2891 if (ViewSchedDAGs) DAG.viewGraph();
2892 ScheduleDAG *SL = NULL;
2894 switch (ISHeuristic) {
2895 default: assert(0 && "Unrecognized scheduling heuristic");
2896 case defaultScheduling:
2897 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2898 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2899 else /* TargetLowering::SchedulingForRegPressure */
2900 SL = createBURRListDAGScheduler(DAG, BB);
2903 SL = createBFS_DAGScheduler(DAG, BB);
2905 case simpleScheduling:
2906 SL = createSimpleDAGScheduler(false, DAG, BB);
2908 case simpleNoItinScheduling:
2909 SL = createSimpleDAGScheduler(true, DAG, BB);
2911 case listSchedulingBURR:
2912 SL = createBURRListDAGScheduler(DAG, BB);
2914 case listSchedulingTD:
2915 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
2922 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2923 return new HazardRecognizer();
2926 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2927 /// by tblgen. Others should not call it.
2928 void SelectionDAGISel::
2929 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2930 std::vector<SDOperand> InOps;
2931 std::swap(InOps, Ops);
2933 Ops.push_back(InOps[0]); // input chain.
2934 Ops.push_back(InOps[1]); // input asm string.
2936 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2937 unsigned i = 2, e = InOps.size();
2938 if (InOps[e-1].getValueType() == MVT::Flag)
2939 --e; // Don't process a flag operand if it is here.
2942 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2943 if ((Flags & 7) != 4 /*MEM*/) {
2944 // Just skip over this operand, copying the operands verbatim.
2945 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2946 i += (Flags >> 3) + 1;
2948 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2949 // Otherwise, this is a memory operand. Ask the target to select it.
2950 std::vector<SDOperand> SelOps;
2951 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2952 std::cerr << "Could not match memory address. Inline asm failure!\n";
2956 // Add this to the output node.
2957 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2958 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2963 // Add the flag input back if present.
2964 if (e != InOps.size())
2965 Ops.push_back(InOps.back());