1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineDebugInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachinePassRegistry.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/CodeGen/SSARegMap.h"
35 #include "llvm/Target/MRegisterInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetFrameInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/Visibility.h"
55 ViewISelDAGs("view-isel-dags", cl::Hidden,
56 cl::desc("Pop up a window to show isel dags as they are selected"));
58 ViewSchedDAGs("view-sched-dags", cl::Hidden,
59 cl::desc("Pop up a window to show sched dags as they are processed"));
61 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
65 cl::opt<const char *, false, RegisterPassParser<RegisterScheduler> >
68 cl::desc("Instruction schedulers available:"));
71 defaultListDAGScheduler("default", " Best scheduler for the target", NULL);
75 /// RegsForValue - This struct represents the physical registers that a
76 /// particular value is assigned and the type information about the value.
77 /// This is needed because values can be promoted into larger registers and
78 /// expanded into multiple smaller registers than the value.
79 struct VISIBILITY_HIDDEN RegsForValue {
80 /// Regs - This list hold the register (for legal and promoted values)
81 /// or register set (for expanded values) that the value should be assigned
83 std::vector<unsigned> Regs;
85 /// RegVT - The value type of each register.
89 /// ValueVT - The value type of the LLVM value, which may be promoted from
90 /// RegVT or made from merging the two expanded parts.
91 MVT::ValueType ValueVT;
93 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
95 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
96 : RegVT(regvt), ValueVT(valuevt) {
99 RegsForValue(const std::vector<unsigned> ®s,
100 MVT::ValueType regvt, MVT::ValueType valuevt)
101 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
104 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
105 /// this value and returns the result as a ValueVT value. This uses
106 /// Chain/Flag as the input and updates them for the output Chain/Flag.
107 SDOperand getCopyFromRegs(SelectionDAG &DAG,
108 SDOperand &Chain, SDOperand &Flag) const;
110 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
111 /// specified value into the registers specified by this object. This uses
112 /// Chain/Flag as the input and updates them for the output Chain/Flag.
113 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
114 SDOperand &Chain, SDOperand &Flag,
115 MVT::ValueType PtrVT) const;
117 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
118 /// operand list. This adds the code marker and includes the number of
119 /// values added into it.
120 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
121 std::vector<SDOperand> &Ops) const;
126 //===--------------------------------------------------------------------===//
127 /// FunctionLoweringInfo - This contains information that is global to a
128 /// function that is used when lowering a region of the function.
129 class FunctionLoweringInfo {
136 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
138 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
139 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
141 /// ValueMap - Since we emit code for the function a basic block at a time,
142 /// we must remember which virtual registers hold the values for
143 /// cross-basic-block values.
144 std::map<const Value*, unsigned> ValueMap;
146 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
147 /// the entry block. This allows the allocas to be efficiently referenced
148 /// anywhere in the function.
149 std::map<const AllocaInst*, int> StaticAllocaMap;
151 unsigned MakeReg(MVT::ValueType VT) {
152 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
155 unsigned CreateRegForValue(const Value *V);
157 unsigned InitializeRegForValue(const Value *V) {
158 unsigned &R = ValueMap[V];
159 assert(R == 0 && "Already initialized this value register!");
160 return R = CreateRegForValue(V);
165 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
166 /// PHI nodes or outside of the basic block that defines it, or used by a
167 /// switch instruction, which may expand to multiple basic blocks.
168 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
169 if (isa<PHINode>(I)) return true;
170 BasicBlock *BB = I->getParent();
171 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
172 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
173 isa<SwitchInst>(*UI))
178 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
179 /// entry block, return true. This includes arguments used by switches, since
180 /// the switch may expand into multiple basic blocks.
181 static bool isOnlyUsedInEntryBlock(Argument *A) {
182 BasicBlock *Entry = A->getParent()->begin();
183 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
184 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
185 return false; // Use not in entry block.
189 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
190 Function &fn, MachineFunction &mf)
191 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
193 // Create a vreg for each argument register that is not dead and is used
194 // outside of the entry block for the function.
195 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
197 if (!isOnlyUsedInEntryBlock(AI))
198 InitializeRegForValue(AI);
200 // Initialize the mapping of values to registers. This is only set up for
201 // instruction values that are used outside of the block that defines
203 Function::iterator BB = Fn.begin(), EB = Fn.end();
204 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
205 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
206 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
207 const Type *Ty = AI->getAllocatedType();
208 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
210 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
213 // If the alignment of the value is smaller than the size of the value,
214 // and if the size of the value is particularly small (<= 8 bytes),
215 // round up to the size of the value for potentially better performance.
217 // FIXME: This could be made better with a preferred alignment hook in
218 // TargetData. It serves primarily to 8-byte align doubles for X86.
219 if (Align < TySize && TySize <= 8) Align = TySize;
220 TySize *= CUI->getValue(); // Get total allocated size.
221 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
222 StaticAllocaMap[AI] =
223 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
226 for (; BB != EB; ++BB)
227 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
228 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
229 if (!isa<AllocaInst>(I) ||
230 !StaticAllocaMap.count(cast<AllocaInst>(I)))
231 InitializeRegForValue(I);
233 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
234 // also creates the initial PHI MachineInstrs, though none of the input
235 // operands are populated.
236 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
237 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
239 MF.getBasicBlockList().push_back(MBB);
241 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
244 for (BasicBlock::iterator I = BB->begin();
245 (PN = dyn_cast<PHINode>(I)); ++I)
246 if (!PN->use_empty()) {
247 MVT::ValueType VT = TLI.getValueType(PN->getType());
248 unsigned NumElements;
249 if (VT != MVT::Vector)
250 NumElements = TLI.getNumElements(VT);
252 MVT::ValueType VT1,VT2;
254 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
257 unsigned PHIReg = ValueMap[PN];
258 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
259 for (unsigned i = 0; i != NumElements; ++i)
260 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
265 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
266 /// the correctly promoted or expanded types. Assign these registers
267 /// consecutive vreg numbers and return the first assigned number.
268 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
269 MVT::ValueType VT = TLI.getValueType(V->getType());
271 // The number of multiples of registers that we need, to, e.g., split up
272 // a <2 x int64> -> 4 x i32 registers.
273 unsigned NumVectorRegs = 1;
275 // If this is a packed type, figure out what type it will decompose into
276 // and how many of the elements it will use.
277 if (VT == MVT::Vector) {
278 const PackedType *PTy = cast<PackedType>(V->getType());
279 unsigned NumElts = PTy->getNumElements();
280 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
282 // Divide the input until we get to a supported size. This will always
283 // end with a scalar if the target doesn't support vectors.
284 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
291 VT = getVectorType(EltTy, NumElts);
294 // The common case is that we will only create one register for this
295 // value. If we have that case, create and return the virtual register.
296 unsigned NV = TLI.getNumElements(VT);
298 // If we are promoting this value, pick the next largest supported type.
299 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
300 unsigned Reg = MakeReg(PromotedType);
301 // If this is a vector of supported or promoted types (e.g. 4 x i16),
302 // create all of the registers.
303 for (unsigned i = 1; i != NumVectorRegs; ++i)
304 MakeReg(PromotedType);
308 // If this value is represented with multiple target registers, make sure
309 // to create enough consecutive registers of the right (smaller) type.
310 unsigned NT = VT-1; // Find the type to use.
311 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
314 unsigned R = MakeReg((MVT::ValueType)NT);
315 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
316 MakeReg((MVT::ValueType)NT);
320 //===----------------------------------------------------------------------===//
321 /// SelectionDAGLowering - This is the common target-independent lowering
322 /// implementation that is parameterized by a TargetLowering object.
323 /// Also, targets can overload any lowering method.
326 class SelectionDAGLowering {
327 MachineBasicBlock *CurMBB;
329 std::map<const Value*, SDOperand> NodeMap;
331 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
332 /// them up and then emit token factor nodes when possible. This allows us to
333 /// get simple disambiguation between loads without worrying about alias
335 std::vector<SDOperand> PendingLoads;
337 /// Case - A pair of values to record the Value for a switch case, and the
338 /// case's target basic block.
339 typedef std::pair<Constant*, MachineBasicBlock*> Case;
340 typedef std::vector<Case>::iterator CaseItr;
341 typedef std::pair<CaseItr, CaseItr> CaseRange;
343 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
344 /// of conditional branches.
346 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
347 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
349 /// CaseBB - The MBB in which to emit the compare and branch
350 MachineBasicBlock *CaseBB;
351 /// LT, GE - If nonzero, we know the current case value must be less-than or
352 /// greater-than-or-equal-to these Constants.
355 /// Range - A pair of iterators representing the range of case values to be
356 /// processed at this point in the binary search tree.
360 /// The comparison function for sorting Case values.
362 bool operator () (const Case& C1, const Case& C2) {
363 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
364 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
366 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
367 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
372 // TLI - This is information that describes the available target features we
373 // need for lowering. This indicates when operations are unavailable,
374 // implemented with a libcall, etc.
377 const TargetData *TD;
379 /// SwitchCases - Vector of CaseBlock structures used to communicate
380 /// SwitchInst code generation information.
381 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
382 SelectionDAGISel::JumpTable JT;
384 /// FuncInfo - Information about the function as a whole.
386 FunctionLoweringInfo &FuncInfo;
388 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
389 FunctionLoweringInfo &funcinfo)
390 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
391 JT(0,0,0,0), FuncInfo(funcinfo) {
394 /// getRoot - Return the current virtual root of the Selection DAG.
396 SDOperand getRoot() {
397 if (PendingLoads.empty())
398 return DAG.getRoot();
400 if (PendingLoads.size() == 1) {
401 SDOperand Root = PendingLoads[0];
403 PendingLoads.clear();
407 // Otherwise, we have to make a token factor node.
408 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
409 PendingLoads.clear();
414 void visit(Instruction &I) { visit(I.getOpcode(), I); }
416 void visit(unsigned Opcode, User &I) {
418 default: assert(0 && "Unknown instruction type encountered!");
420 // Build the switch statement using the Instruction.def file.
421 #define HANDLE_INST(NUM, OPCODE, CLASS) \
422 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
423 #include "llvm/Instruction.def"
427 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
429 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
430 SDOperand SrcValue, SDOperand Root,
433 SDOperand getIntPtrConstant(uint64_t Val) {
434 return DAG.getConstant(Val, TLI.getPointerTy());
437 SDOperand getValue(const Value *V);
439 const SDOperand &setValue(const Value *V, SDOperand NewN) {
440 SDOperand &N = NodeMap[V];
441 assert(N.Val == 0 && "Already set a value for this node!");
445 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
447 bool OutReg, bool InReg,
448 std::set<unsigned> &OutputRegs,
449 std::set<unsigned> &InputRegs);
451 // Terminator instructions.
452 void visitRet(ReturnInst &I);
453 void visitBr(BranchInst &I);
454 void visitSwitch(SwitchInst &I);
455 void visitUnreachable(UnreachableInst &I) { /* noop */ }
457 // Helper for visitSwitch
458 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
459 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
461 // These all get lowered before this pass.
462 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
463 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
465 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
466 void visitShift(User &I, unsigned Opcode);
467 void visitAdd(User &I) {
468 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
470 void visitSub(User &I);
471 void visitMul(User &I) {
472 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
474 void visitDiv(User &I) {
475 const Type *Ty = I.getType();
477 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
478 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
480 void visitRem(User &I) {
481 const Type *Ty = I.getType();
482 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
484 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
485 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
486 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
487 void visitShl(User &I) { visitShift(I, ISD::SHL); }
488 void visitShr(User &I) {
489 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
492 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
493 ISD::CondCode FPOpc);
494 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
496 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
498 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
500 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
502 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
504 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
507 void visitExtractElement(User &I);
508 void visitInsertElement(User &I);
509 void visitShuffleVector(User &I);
511 void visitGetElementPtr(User &I);
512 void visitCast(User &I);
513 void visitSelect(User &I);
515 void visitMalloc(MallocInst &I);
516 void visitFree(FreeInst &I);
517 void visitAlloca(AllocaInst &I);
518 void visitLoad(LoadInst &I);
519 void visitStore(StoreInst &I);
520 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
521 void visitCall(CallInst &I);
522 void visitInlineAsm(CallInst &I);
523 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
524 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
526 void visitVAStart(CallInst &I);
527 void visitVAArg(VAArgInst &I);
528 void visitVAEnd(CallInst &I);
529 void visitVACopy(CallInst &I);
530 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
532 void visitMemIntrinsic(CallInst &I, unsigned Op);
534 void visitUserOp1(Instruction &I) {
535 assert(0 && "UserOp1 should not exist at instruction selection time!");
538 void visitUserOp2(Instruction &I) {
539 assert(0 && "UserOp2 should not exist at instruction selection time!");
543 } // end namespace llvm
545 SDOperand SelectionDAGLowering::getValue(const Value *V) {
546 SDOperand &N = NodeMap[V];
549 const Type *VTy = V->getType();
550 MVT::ValueType VT = TLI.getValueType(VTy);
551 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
552 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
553 visit(CE->getOpcode(), *CE);
554 assert(N.Val && "visit didn't populate the ValueMap!");
556 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
557 return N = DAG.getGlobalAddress(GV, VT);
558 } else if (isa<ConstantPointerNull>(C)) {
559 return N = DAG.getConstant(0, TLI.getPointerTy());
560 } else if (isa<UndefValue>(C)) {
561 if (!isa<PackedType>(VTy))
562 return N = DAG.getNode(ISD::UNDEF, VT);
564 // Create a VBUILD_VECTOR of undef nodes.
565 const PackedType *PTy = cast<PackedType>(VTy);
566 unsigned NumElements = PTy->getNumElements();
567 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
569 std::vector<SDOperand> Ops;
570 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
572 // Create a VConstant node with generic Vector type.
573 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
574 Ops.push_back(DAG.getValueType(PVT));
575 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
576 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
577 return N = DAG.getConstantFP(CFP->getValue(), VT);
578 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
579 unsigned NumElements = PTy->getNumElements();
580 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
582 // Now that we know the number and type of the elements, push a
583 // Constant or ConstantFP node onto the ops list for each element of
584 // the packed constant.
585 std::vector<SDOperand> Ops;
586 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
587 for (unsigned i = 0; i != NumElements; ++i)
588 Ops.push_back(getValue(CP->getOperand(i)));
590 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
592 if (MVT::isFloatingPoint(PVT))
593 Op = DAG.getConstantFP(0, PVT);
595 Op = DAG.getConstant(0, PVT);
596 Ops.assign(NumElements, Op);
599 // Create a VBUILD_VECTOR node with generic Vector type.
600 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
601 Ops.push_back(DAG.getValueType(PVT));
602 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
604 // Canonicalize all constant ints to be unsigned.
605 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
609 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
610 std::map<const AllocaInst*, int>::iterator SI =
611 FuncInfo.StaticAllocaMap.find(AI);
612 if (SI != FuncInfo.StaticAllocaMap.end())
613 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
616 std::map<const Value*, unsigned>::const_iterator VMI =
617 FuncInfo.ValueMap.find(V);
618 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
620 unsigned InReg = VMI->second;
622 // If this type is not legal, make it so now.
623 if (VT != MVT::Vector) {
624 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
626 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
628 // Source must be expanded. This input value is actually coming from the
629 // register pair VMI->second and VMI->second+1.
630 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
631 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
632 } else if (DestVT > VT) { // Promotion case
633 if (MVT::isFloatingPoint(VT))
634 N = DAG.getNode(ISD::FP_ROUND, VT, N);
636 N = DAG.getNode(ISD::TRUNCATE, VT, N);
639 // Otherwise, if this is a vector, make it available as a generic vector
641 MVT::ValueType PTyElementVT, PTyLegalElementVT;
642 const PackedType *PTy = cast<PackedType>(VTy);
643 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
646 // Build a VBUILD_VECTOR with the input registers.
647 std::vector<SDOperand> Ops;
648 if (PTyElementVT == PTyLegalElementVT) {
649 // If the value types are legal, just VBUILD the CopyFromReg nodes.
650 for (unsigned i = 0; i != NE; ++i)
651 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
653 } else if (PTyElementVT < PTyLegalElementVT) {
654 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
655 for (unsigned i = 0; i != NE; ++i) {
656 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
658 if (MVT::isFloatingPoint(PTyElementVT))
659 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
661 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
665 // If the register was expanded, use BUILD_PAIR.
666 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
667 for (unsigned i = 0; i != NE/2; ++i) {
668 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
670 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
672 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
676 Ops.push_back(DAG.getConstant(NE, MVT::i32));
677 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
678 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
680 // Finally, use a VBIT_CONVERT to make this available as the appropriate
682 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
683 DAG.getConstant(PTy->getNumElements(),
685 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
692 void SelectionDAGLowering::visitRet(ReturnInst &I) {
693 if (I.getNumOperands() == 0) {
694 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
697 std::vector<SDOperand> NewValues;
698 NewValues.push_back(getRoot());
699 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
700 SDOperand RetOp = getValue(I.getOperand(i));
701 bool isSigned = I.getOperand(i)->getType()->isSigned();
703 // If this is an integer return value, we need to promote it ourselves to
704 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
706 // FIXME: C calling convention requires the return type to be promoted to
707 // at least 32-bit. But this is not necessary for non-C calling conventions.
708 if (MVT::isInteger(RetOp.getValueType()) &&
709 RetOp.getValueType() < MVT::i64) {
710 MVT::ValueType TmpVT;
711 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
712 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
717 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
719 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
721 NewValues.push_back(RetOp);
722 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
724 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
727 void SelectionDAGLowering::visitBr(BranchInst &I) {
728 // Update machine-CFG edges.
729 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
730 CurMBB->addSuccessor(Succ0MBB);
732 // Figure out which block is immediately after the current one.
733 MachineBasicBlock *NextBlock = 0;
734 MachineFunction::iterator BBI = CurMBB;
735 if (++BBI != CurMBB->getParent()->end())
738 if (I.isUnconditional()) {
739 // If this is not a fall-through branch, emit the branch.
740 if (Succ0MBB != NextBlock)
741 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
742 DAG.getBasicBlock(Succ0MBB)));
744 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
745 CurMBB->addSuccessor(Succ1MBB);
747 SDOperand Cond = getValue(I.getCondition());
748 if (Succ1MBB == NextBlock) {
749 // If the condition is false, fall through. This means we should branch
750 // if the condition is true to Succ #0.
751 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
752 Cond, DAG.getBasicBlock(Succ0MBB)));
753 } else if (Succ0MBB == NextBlock) {
754 // If the condition is true, fall through. This means we should branch if
755 // the condition is false to Succ #1. Invert the condition first.
756 SDOperand True = DAG.getConstant(1, Cond.getValueType());
757 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
758 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
759 Cond, DAG.getBasicBlock(Succ1MBB)));
761 std::vector<SDOperand> Ops;
762 Ops.push_back(getRoot());
763 // If the false case is the current basic block, then this is a self
764 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
765 // adds an extra instruction in the loop. Instead, invert the
766 // condition and emit "Loop: ... br!cond Loop; br Out.
767 if (CurMBB == Succ1MBB) {
768 std::swap(Succ0MBB, Succ1MBB);
769 SDOperand True = DAG.getConstant(1, Cond.getValueType());
770 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
772 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
773 DAG.getBasicBlock(Succ0MBB));
774 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
775 DAG.getBasicBlock(Succ1MBB)));
780 /// visitSwitchCase - Emits the necessary code to represent a single node in
781 /// the binary search tree resulting from lowering a switch instruction.
782 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
783 SDOperand SwitchOp = getValue(CB.SwitchV);
784 SDOperand CaseOp = getValue(CB.CaseC);
785 SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
787 // Set NextBlock to be the MBB immediately after the current one, if any.
788 // This is used to avoid emitting unnecessary branches to the next block.
789 MachineBasicBlock *NextBlock = 0;
790 MachineFunction::iterator BBI = CurMBB;
791 if (++BBI != CurMBB->getParent()->end())
794 // If the lhs block is the next block, invert the condition so that we can
795 // fall through to the lhs instead of the rhs block.
796 if (CB.LHSBB == NextBlock) {
797 std::swap(CB.LHSBB, CB.RHSBB);
798 SDOperand True = DAG.getConstant(1, Cond.getValueType());
799 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
801 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
802 DAG.getBasicBlock(CB.LHSBB));
803 if (CB.RHSBB == NextBlock)
806 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
807 DAG.getBasicBlock(CB.RHSBB)));
808 // Update successor info
809 CurMBB->addSuccessor(CB.LHSBB);
810 CurMBB->addSuccessor(CB.RHSBB);
813 /// visitSwitchCase - Emits the necessary code to represent a single node in
814 /// the binary search tree resulting from lowering a switch instruction.
815 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
816 // FIXME: Need to emit different code for PIC vs. Non-PIC, specifically,
817 // we need to add the address of the jump table to the value loaded, since
818 // the entries in the jump table will be differences rather than absolute
821 // Emit the code for the jump table
822 MVT::ValueType PTy = TLI.getPointerTy();
823 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
824 "Jump table entries are 32-bit values");
825 // PIC jump table entries are 32-bit values.
827 (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_)
828 ? 4 : MVT::getSizeInBits(PTy)/8;
829 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
830 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
831 DAG.getConstant(EntrySize, PTy));
832 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
833 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
834 SDOperand LD = DAG.getLoad(MVT::i32, Copy.getValue(1), ADD,
836 if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
837 ADD = DAG.getNode(ISD::ADD, PTy,
838 ((PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD), TAB);
839 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
841 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
845 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
846 // Figure out which block is immediately after the current one.
847 MachineBasicBlock *NextBlock = 0;
848 MachineFunction::iterator BBI = CurMBB;
849 if (++BBI != CurMBB->getParent()->end())
852 // If there is only the default destination, branch to it if it is not the
853 // next basic block. Otherwise, just fall through.
854 if (I.getNumOperands() == 2) {
855 // Update machine-CFG edges.
856 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
857 // If this is not a fall-through branch, emit the branch.
858 if (DefaultMBB != NextBlock)
859 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
860 DAG.getBasicBlock(DefaultMBB)));
861 CurMBB->addSuccessor(DefaultMBB);
865 // If there are any non-default case statements, create a vector of Cases
866 // representing each one, and sort the vector so that we can efficiently
867 // create a binary search tree from them.
868 std::vector<Case> Cases;
869 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
870 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
871 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
873 std::sort(Cases.begin(), Cases.end(), CaseCmp());
875 // Get the Value to be switched on and default basic blocks, which will be
876 // inserted into CaseBlock records, representing basic blocks in the binary
878 Value *SV = I.getOperand(0);
879 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
881 // Get the MachineFunction which holds the current MBB. This is used during
882 // emission of jump tables, and when inserting any additional MBBs necessary
883 // to represent the switch.
884 MachineFunction *CurMF = CurMBB->getParent();
885 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
887 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
888 // target supports indirect branches, then emit a jump table rather than
889 // lowering the switch to a binary tree of conditional branches.
890 // FIXME: Make this work with PIC code
891 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
893 uint64_t First = cast<ConstantIntegral>(Cases.front().first)->getRawValue();
894 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getRawValue();
895 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
897 if (Density >= 0.3125) {
898 // Create a new basic block to hold the code for loading the address
899 // of the jump table, and jumping to it. Update successor information;
900 // we will either branch to the default case for the switch, or the jump
902 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
903 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
904 CurMBB->addSuccessor(Default);
905 CurMBB->addSuccessor(JumpTableBB);
907 // Subtract the lowest switch case value from the value being switched on
908 // and conditional branch to default mbb if the result is greater than the
909 // difference between smallest and largest cases.
910 SDOperand SwitchOp = getValue(SV);
911 MVT::ValueType VT = SwitchOp.getValueType();
912 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
913 DAG.getConstant(First, VT));
915 // The SDNode we just created, which holds the value being switched on
916 // minus the the smallest case value, needs to be copied to a virtual
917 // register so it can be used as an index into the jump table in a
918 // subsequent basic block. This value may be smaller or larger than the
919 // target's pointer type, and therefore require extension or truncating.
920 if (VT > TLI.getPointerTy())
921 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
923 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
924 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
925 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
927 // Emit the range check for the jump table, and branch to the default
928 // block for the switch statement if the value being switched on exceeds
929 // the largest case in the switch.
930 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
931 DAG.getConstant(Last-First,VT), ISD::SETUGT);
932 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
933 DAG.getBasicBlock(Default)));
935 // Build a vector of destination BBs, corresponding to each target
936 // of the jump table. If the value of the jump table slot corresponds to
937 // a case statement, push the case's BB onto the vector, otherwise, push
939 std::set<MachineBasicBlock*> UniqueBBs;
940 std::vector<MachineBasicBlock*> DestBBs;
941 uint64_t TEI = First;
942 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI) {
943 if (cast<ConstantIntegral>(ii->first)->getRawValue() == TEI) {
944 DestBBs.push_back(ii->second);
945 UniqueBBs.insert(ii->second);
948 DestBBs.push_back(Default);
949 UniqueBBs.insert(Default);
953 // Update successor info
954 for (std::set<MachineBasicBlock*>::iterator ii = UniqueBBs.begin(),
955 ee = UniqueBBs.end(); ii != ee; ++ii)
956 JumpTableBB->addSuccessor(*ii);
958 // Create a jump table index for this jump table, or return an existing
960 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
962 // Set the jump table information so that we can codegen it as a second
964 JT.Reg = JumpTableReg;
966 JT.MBB = JumpTableBB;
967 JT.Default = Default;
972 // Push the initial CaseRec onto the worklist
973 std::vector<CaseRec> CaseVec;
974 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
976 while (!CaseVec.empty()) {
977 // Grab a record representing a case range to process off the worklist
978 CaseRec CR = CaseVec.back();
981 // Size is the number of Cases represented by this range. If Size is 1,
982 // then we are processing a leaf of the binary search tree. Otherwise,
983 // we need to pick a pivot, and push left and right ranges onto the
985 unsigned Size = CR.Range.second - CR.Range.first;
988 // Create a CaseBlock record representing a conditional branch to
989 // the Case's target mbb if the value being switched on SV is equal
990 // to C. Otherwise, branch to default.
991 Constant *C = CR.Range.first->first;
992 MachineBasicBlock *Target = CR.Range.first->second;
993 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
995 // If the MBB representing the leaf node is the current MBB, then just
996 // call visitSwitchCase to emit the code into the current block.
997 // Otherwise, push the CaseBlock onto the vector to be later processed
998 // by SDISel, and insert the node's MBB before the next MBB.
999 if (CR.CaseBB == CurMBB)
1000 visitSwitchCase(CB);
1002 SwitchCases.push_back(CB);
1003 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1006 // split case range at pivot
1007 CaseItr Pivot = CR.Range.first + (Size / 2);
1008 CaseRange LHSR(CR.Range.first, Pivot);
1009 CaseRange RHSR(Pivot, CR.Range.second);
1010 Constant *C = Pivot->first;
1011 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
1012 // We know that we branch to the LHS if the Value being switched on is
1013 // less than the Pivot value, C. We use this to optimize our binary
1014 // tree a bit, by recognizing that if SV is greater than or equal to the
1015 // LHS's Case Value, and that Case Value is exactly one less than the
1016 // Pivot's Value, then we can branch directly to the LHS's Target,
1017 // rather than creating a leaf node for it.
1018 if ((LHSR.second - LHSR.first) == 1 &&
1019 LHSR.first->first == CR.GE &&
1020 cast<ConstantIntegral>(C)->getRawValue() ==
1021 (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
1022 LHSBB = LHSR.first->second;
1024 LHSBB = new MachineBasicBlock(LLVMBB);
1025 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1027 // Similar to the optimization above, if the Value being switched on is
1028 // known to be less than the Constant CR.LT, and the current Case Value
1029 // is CR.LT - 1, then we can branch directly to the target block for
1030 // the current Case Value, rather than emitting a RHS leaf node for it.
1031 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1032 cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
1033 (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
1034 RHSBB = RHSR.first->second;
1036 RHSBB = new MachineBasicBlock(LLVMBB);
1037 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1039 // Create a CaseBlock record representing a conditional branch to
1040 // the LHS node if the value being switched on SV is less than C.
1041 // Otherwise, branch to LHS.
1042 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1043 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
1044 if (CR.CaseBB == CurMBB)
1045 visitSwitchCase(CB);
1047 SwitchCases.push_back(CB);
1048 CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1054 void SelectionDAGLowering::visitSub(User &I) {
1055 // -0.0 - X --> fneg
1056 if (I.getType()->isFloatingPoint()) {
1057 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1058 if (CFP->isExactlyValue(-0.0)) {
1059 SDOperand Op2 = getValue(I.getOperand(1));
1060 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1064 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
1067 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1069 const Type *Ty = I.getType();
1070 SDOperand Op1 = getValue(I.getOperand(0));
1071 SDOperand Op2 = getValue(I.getOperand(1));
1073 if (Ty->isIntegral()) {
1074 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1075 } else if (Ty->isFloatingPoint()) {
1076 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1078 const PackedType *PTy = cast<PackedType>(Ty);
1079 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1080 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1081 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1085 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1086 SDOperand Op1 = getValue(I.getOperand(0));
1087 SDOperand Op2 = getValue(I.getOperand(1));
1089 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1091 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1094 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
1095 ISD::CondCode UnsignedOpcode,
1096 ISD::CondCode FPOpcode) {
1097 SDOperand Op1 = getValue(I.getOperand(0));
1098 SDOperand Op2 = getValue(I.getOperand(1));
1099 ISD::CondCode Opcode = SignedOpcode;
1100 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
1102 else if (I.getOperand(0)->getType()->isUnsigned())
1103 Opcode = UnsignedOpcode;
1104 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1107 void SelectionDAGLowering::visitSelect(User &I) {
1108 SDOperand Cond = getValue(I.getOperand(0));
1109 SDOperand TrueVal = getValue(I.getOperand(1));
1110 SDOperand FalseVal = getValue(I.getOperand(2));
1111 if (!isa<PackedType>(I.getType())) {
1112 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1113 TrueVal, FalseVal));
1115 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1116 *(TrueVal.Val->op_end()-2),
1117 *(TrueVal.Val->op_end()-1)));
1121 void SelectionDAGLowering::visitCast(User &I) {
1122 SDOperand N = getValue(I.getOperand(0));
1123 MVT::ValueType SrcVT = N.getValueType();
1124 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1126 if (DestVT == MVT::Vector) {
1127 // This is a cast to a vector from something else. This is always a bit
1128 // convert. Get information about the input vector.
1129 const PackedType *DestTy = cast<PackedType>(I.getType());
1130 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1131 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1132 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1133 DAG.getValueType(EltVT)));
1134 } else if (SrcVT == DestVT) {
1135 setValue(&I, N); // noop cast.
1136 } else if (DestVT == MVT::i1) {
1137 // Cast to bool is a comparison against zero, not truncation to zero.
1138 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1139 DAG.getConstantFP(0.0, N.getValueType());
1140 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1141 } else if (isInteger(SrcVT)) {
1142 if (isInteger(DestVT)) { // Int -> Int cast
1143 if (DestVT < SrcVT) // Truncating cast?
1144 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1145 else if (I.getOperand(0)->getType()->isSigned())
1146 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1148 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1149 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
1150 if (I.getOperand(0)->getType()->isSigned())
1151 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1153 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1155 assert(0 && "Unknown cast!");
1157 } else if (isFloatingPoint(SrcVT)) {
1158 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1159 if (DestVT < SrcVT) // Rounding cast?
1160 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1162 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1163 } else if (isInteger(DestVT)) { // FP -> Int cast.
1164 if (I.getType()->isSigned())
1165 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1167 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1169 assert(0 && "Unknown cast!");
1172 assert(SrcVT == MVT::Vector && "Unknown cast!");
1173 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1174 // This is a cast from a vector to something else. This is always a bit
1175 // convert. Get information about the input vector.
1176 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1180 void SelectionDAGLowering::visitInsertElement(User &I) {
1181 SDOperand InVec = getValue(I.getOperand(0));
1182 SDOperand InVal = getValue(I.getOperand(1));
1183 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1184 getValue(I.getOperand(2)));
1186 SDOperand Num = *(InVec.Val->op_end()-2);
1187 SDOperand Typ = *(InVec.Val->op_end()-1);
1188 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1189 InVec, InVal, InIdx, Num, Typ));
1192 void SelectionDAGLowering::visitExtractElement(User &I) {
1193 SDOperand InVec = getValue(I.getOperand(0));
1194 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1195 getValue(I.getOperand(1)));
1196 SDOperand Typ = *(InVec.Val->op_end()-1);
1197 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1198 TLI.getValueType(I.getType()), InVec, InIdx));
1201 void SelectionDAGLowering::visitShuffleVector(User &I) {
1202 SDOperand V1 = getValue(I.getOperand(0));
1203 SDOperand V2 = getValue(I.getOperand(1));
1204 SDOperand Mask = getValue(I.getOperand(2));
1206 SDOperand Num = *(V1.Val->op_end()-2);
1207 SDOperand Typ = *(V2.Val->op_end()-1);
1208 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1209 V1, V2, Mask, Num, Typ));
1213 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1214 SDOperand N = getValue(I.getOperand(0));
1215 const Type *Ty = I.getOperand(0)->getType();
1217 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1220 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1221 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1224 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1225 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1226 getIntPtrConstant(Offset));
1228 Ty = StTy->getElementType(Field);
1230 Ty = cast<SequentialType>(Ty)->getElementType();
1232 // If this is a constant subscript, handle it quickly.
1233 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1234 if (CI->getRawValue() == 0) continue;
1237 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1238 Offs = (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
1240 Offs = TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1241 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1245 // N = N + Idx * ElementSize;
1246 uint64_t ElementSize = TD->getTypeSize(Ty);
1247 SDOperand IdxN = getValue(Idx);
1249 // If the index is smaller or larger than intptr_t, truncate or extend
1251 if (IdxN.getValueType() < N.getValueType()) {
1252 if (Idx->getType()->isSigned())
1253 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1255 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1256 } else if (IdxN.getValueType() > N.getValueType())
1257 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1259 // If this is a multiply by a power of two, turn it into a shl
1260 // immediately. This is a very common case.
1261 if (isPowerOf2_64(ElementSize)) {
1262 unsigned Amt = Log2_64(ElementSize);
1263 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1264 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1265 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1269 SDOperand Scale = getIntPtrConstant(ElementSize);
1270 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1271 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1277 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1278 // If this is a fixed sized alloca in the entry block of the function,
1279 // allocate it statically on the stack.
1280 if (FuncInfo.StaticAllocaMap.count(&I))
1281 return; // getValue will auto-populate this.
1283 const Type *Ty = I.getAllocatedType();
1284 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1285 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
1288 SDOperand AllocSize = getValue(I.getArraySize());
1289 MVT::ValueType IntPtr = TLI.getPointerTy();
1290 if (IntPtr < AllocSize.getValueType())
1291 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1292 else if (IntPtr > AllocSize.getValueType())
1293 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1295 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1296 getIntPtrConstant(TySize));
1298 // Handle alignment. If the requested alignment is less than or equal to the
1299 // stack alignment, ignore it and round the size of the allocation up to the
1300 // stack alignment size. If the size is greater than the stack alignment, we
1301 // note this in the DYNAMIC_STACKALLOC node.
1302 unsigned StackAlign =
1303 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1304 if (Align <= StackAlign) {
1306 // Add SA-1 to the size.
1307 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1308 getIntPtrConstant(StackAlign-1));
1309 // Mask out the low bits for alignment purposes.
1310 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1311 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1314 std::vector<MVT::ValueType> VTs;
1315 VTs.push_back(AllocSize.getValueType());
1316 VTs.push_back(MVT::Other);
1317 std::vector<SDOperand> Ops;
1318 Ops.push_back(getRoot());
1319 Ops.push_back(AllocSize);
1320 Ops.push_back(getIntPtrConstant(Align));
1321 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
1322 DAG.setRoot(setValue(&I, DSA).getValue(1));
1324 // Inform the Frame Information that we have just allocated a variable-sized
1326 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1329 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1330 SDOperand Ptr = getValue(I.getOperand(0));
1336 // Do not serialize non-volatile loads against each other.
1337 Root = DAG.getRoot();
1340 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1341 Root, I.isVolatile()));
1344 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1345 SDOperand SrcValue, SDOperand Root,
1348 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1349 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1350 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
1352 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
1356 DAG.setRoot(L.getValue(1));
1358 PendingLoads.push_back(L.getValue(1));
1364 void SelectionDAGLowering::visitStore(StoreInst &I) {
1365 Value *SrcV = I.getOperand(0);
1366 SDOperand Src = getValue(SrcV);
1367 SDOperand Ptr = getValue(I.getOperand(1));
1368 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1369 DAG.getSrcValue(I.getOperand(1))));
1372 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1373 /// access memory and has no other side effects at all.
1374 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1375 #define GET_NO_MEMORY_INTRINSICS
1376 #include "llvm/Intrinsics.gen"
1377 #undef GET_NO_MEMORY_INTRINSICS
1381 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1382 // have any side-effects or if it only reads memory.
1383 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1384 #define GET_SIDE_EFFECT_INFO
1385 #include "llvm/Intrinsics.gen"
1386 #undef GET_SIDE_EFFECT_INFO
1390 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1392 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1393 unsigned Intrinsic) {
1394 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1395 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1397 // Build the operand list.
1398 std::vector<SDOperand> Ops;
1399 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1401 // We don't need to serialize loads against other loads.
1402 Ops.push_back(DAG.getRoot());
1404 Ops.push_back(getRoot());
1408 // Add the intrinsic ID as an integer operand.
1409 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1411 // Add all operands of the call to the operand list.
1412 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1413 SDOperand Op = getValue(I.getOperand(i));
1415 // If this is a vector type, force it to the right packed type.
1416 if (Op.getValueType() == MVT::Vector) {
1417 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1418 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1420 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1421 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1422 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1425 assert(TLI.isTypeLegal(Op.getValueType()) &&
1426 "Intrinsic uses a non-legal type?");
1430 std::vector<MVT::ValueType> VTs;
1431 if (I.getType() != Type::VoidTy) {
1432 MVT::ValueType VT = TLI.getValueType(I.getType());
1433 if (VT == MVT::Vector) {
1434 const PackedType *DestTy = cast<PackedType>(I.getType());
1435 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1437 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1438 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1441 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1445 VTs.push_back(MVT::Other);
1450 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1451 else if (I.getType() != Type::VoidTy)
1452 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1454 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1457 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1459 PendingLoads.push_back(Chain);
1463 if (I.getType() != Type::VoidTy) {
1464 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1465 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1466 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1467 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1468 DAG.getValueType(EVT));
1470 setValue(&I, Result);
1474 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1475 /// we want to emit this as a call to a named external function, return the name
1476 /// otherwise lower it and return null.
1478 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1479 switch (Intrinsic) {
1481 // By default, turn this into a target intrinsic node.
1482 visitTargetIntrinsic(I, Intrinsic);
1484 case Intrinsic::vastart: visitVAStart(I); return 0;
1485 case Intrinsic::vaend: visitVAEnd(I); return 0;
1486 case Intrinsic::vacopy: visitVACopy(I); return 0;
1487 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1488 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1489 case Intrinsic::setjmp:
1490 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1492 case Intrinsic::longjmp:
1493 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1495 case Intrinsic::memcpy_i32:
1496 case Intrinsic::memcpy_i64:
1497 visitMemIntrinsic(I, ISD::MEMCPY);
1499 case Intrinsic::memset_i32:
1500 case Intrinsic::memset_i64:
1501 visitMemIntrinsic(I, ISD::MEMSET);
1503 case Intrinsic::memmove_i32:
1504 case Intrinsic::memmove_i64:
1505 visitMemIntrinsic(I, ISD::MEMMOVE);
1508 case Intrinsic::dbg_stoppoint: {
1509 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1510 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1511 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1512 std::vector<SDOperand> Ops;
1514 Ops.push_back(getRoot());
1515 Ops.push_back(getValue(SPI.getLineValue()));
1516 Ops.push_back(getValue(SPI.getColumnValue()));
1518 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1519 assert(DD && "Not a debug information descriptor");
1520 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1522 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1523 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1525 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1530 case Intrinsic::dbg_region_start: {
1531 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1532 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1533 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1534 std::vector<SDOperand> Ops;
1536 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1538 Ops.push_back(getRoot());
1539 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1541 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1546 case Intrinsic::dbg_region_end: {
1547 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1548 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1549 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1550 std::vector<SDOperand> Ops;
1552 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1554 Ops.push_back(getRoot());
1555 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1557 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1562 case Intrinsic::dbg_func_start: {
1563 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1564 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1565 if (DebugInfo && FSI.getSubprogram() &&
1566 DebugInfo->Verify(FSI.getSubprogram())) {
1567 std::vector<SDOperand> Ops;
1569 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1571 Ops.push_back(getRoot());
1572 Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1574 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1579 case Intrinsic::dbg_declare: {
1580 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1581 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1582 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1583 std::vector<SDOperand> Ops;
1585 SDOperand AddressOp = getValue(DI.getAddress());
1586 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
1587 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1594 case Intrinsic::isunordered_f32:
1595 case Intrinsic::isunordered_f64:
1596 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1597 getValue(I.getOperand(2)), ISD::SETUO));
1600 case Intrinsic::sqrt_f32:
1601 case Intrinsic::sqrt_f64:
1602 setValue(&I, DAG.getNode(ISD::FSQRT,
1603 getValue(I.getOperand(1)).getValueType(),
1604 getValue(I.getOperand(1))));
1606 case Intrinsic::pcmarker: {
1607 SDOperand Tmp = getValue(I.getOperand(1));
1608 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1611 case Intrinsic::readcyclecounter: {
1612 std::vector<MVT::ValueType> VTs;
1613 VTs.push_back(MVT::i64);
1614 VTs.push_back(MVT::Other);
1615 std::vector<SDOperand> Ops;
1616 Ops.push_back(getRoot());
1617 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1619 DAG.setRoot(Tmp.getValue(1));
1622 case Intrinsic::bswap_i16:
1623 case Intrinsic::bswap_i32:
1624 case Intrinsic::bswap_i64:
1625 setValue(&I, DAG.getNode(ISD::BSWAP,
1626 getValue(I.getOperand(1)).getValueType(),
1627 getValue(I.getOperand(1))));
1629 case Intrinsic::cttz_i8:
1630 case Intrinsic::cttz_i16:
1631 case Intrinsic::cttz_i32:
1632 case Intrinsic::cttz_i64:
1633 setValue(&I, DAG.getNode(ISD::CTTZ,
1634 getValue(I.getOperand(1)).getValueType(),
1635 getValue(I.getOperand(1))));
1637 case Intrinsic::ctlz_i8:
1638 case Intrinsic::ctlz_i16:
1639 case Intrinsic::ctlz_i32:
1640 case Intrinsic::ctlz_i64:
1641 setValue(&I, DAG.getNode(ISD::CTLZ,
1642 getValue(I.getOperand(1)).getValueType(),
1643 getValue(I.getOperand(1))));
1645 case Intrinsic::ctpop_i8:
1646 case Intrinsic::ctpop_i16:
1647 case Intrinsic::ctpop_i32:
1648 case Intrinsic::ctpop_i64:
1649 setValue(&I, DAG.getNode(ISD::CTPOP,
1650 getValue(I.getOperand(1)).getValueType(),
1651 getValue(I.getOperand(1))));
1653 case Intrinsic::stacksave: {
1654 std::vector<MVT::ValueType> VTs;
1655 VTs.push_back(TLI.getPointerTy());
1656 VTs.push_back(MVT::Other);
1657 std::vector<SDOperand> Ops;
1658 Ops.push_back(getRoot());
1659 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1661 DAG.setRoot(Tmp.getValue(1));
1664 case Intrinsic::stackrestore: {
1665 SDOperand Tmp = getValue(I.getOperand(1));
1666 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1669 case Intrinsic::prefetch:
1670 // FIXME: Currently discarding prefetches.
1676 void SelectionDAGLowering::visitCall(CallInst &I) {
1677 const char *RenameFn = 0;
1678 if (Function *F = I.getCalledFunction()) {
1679 if (F->isExternal())
1680 if (unsigned IID = F->getIntrinsicID()) {
1681 RenameFn = visitIntrinsicCall(I, IID);
1684 } else { // Not an LLVM intrinsic.
1685 const std::string &Name = F->getName();
1686 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1687 if (I.getNumOperands() == 3 && // Basic sanity checks.
1688 I.getOperand(1)->getType()->isFloatingPoint() &&
1689 I.getType() == I.getOperand(1)->getType() &&
1690 I.getType() == I.getOperand(2)->getType()) {
1691 SDOperand LHS = getValue(I.getOperand(1));
1692 SDOperand RHS = getValue(I.getOperand(2));
1693 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1697 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1698 if (I.getNumOperands() == 2 && // Basic sanity checks.
1699 I.getOperand(1)->getType()->isFloatingPoint() &&
1700 I.getType() == I.getOperand(1)->getType()) {
1701 SDOperand Tmp = getValue(I.getOperand(1));
1702 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1705 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1706 if (I.getNumOperands() == 2 && // Basic sanity checks.
1707 I.getOperand(1)->getType()->isFloatingPoint() &&
1708 I.getType() == I.getOperand(1)->getType()) {
1709 SDOperand Tmp = getValue(I.getOperand(1));
1710 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1713 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1714 if (I.getNumOperands() == 2 && // Basic sanity checks.
1715 I.getOperand(1)->getType()->isFloatingPoint() &&
1716 I.getType() == I.getOperand(1)->getType()) {
1717 SDOperand Tmp = getValue(I.getOperand(1));
1718 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1723 } else if (isa<InlineAsm>(I.getOperand(0))) {
1730 Callee = getValue(I.getOperand(0));
1732 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1733 std::vector<std::pair<SDOperand, const Type*> > Args;
1734 Args.reserve(I.getNumOperands());
1735 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1736 Value *Arg = I.getOperand(i);
1737 SDOperand ArgNode = getValue(Arg);
1738 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1741 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1742 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1744 std::pair<SDOperand,SDOperand> Result =
1745 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1746 I.isTailCall(), Callee, Args, DAG);
1747 if (I.getType() != Type::VoidTy)
1748 setValue(&I, Result.first);
1749 DAG.setRoot(Result.second);
1752 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1753 SDOperand &Chain, SDOperand &Flag)const{
1754 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1755 Chain = Val.getValue(1);
1756 Flag = Val.getValue(2);
1758 // If the result was expanded, copy from the top part.
1759 if (Regs.size() > 1) {
1760 assert(Regs.size() == 2 &&
1761 "Cannot expand to more than 2 elts yet!");
1762 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1763 Chain = Val.getValue(1);
1764 Flag = Val.getValue(2);
1765 if (DAG.getTargetLoweringInfo().isLittleEndian())
1766 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1768 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
1771 // Otherwise, if the return value was promoted or extended, truncate it to the
1772 // appropriate type.
1773 if (RegVT == ValueVT)
1776 if (MVT::isInteger(RegVT)) {
1777 if (ValueVT < RegVT)
1778 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1780 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1782 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1786 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1787 /// specified value into the registers specified by this object. This uses
1788 /// Chain/Flag as the input and updates them for the output Chain/Flag.
1789 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1790 SDOperand &Chain, SDOperand &Flag,
1791 MVT::ValueType PtrVT) const {
1792 if (Regs.size() == 1) {
1793 // If there is a single register and the types differ, this must be
1795 if (RegVT != ValueVT) {
1796 if (MVT::isInteger(RegVT)) {
1797 if (RegVT < ValueVT)
1798 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
1800 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1802 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1804 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1805 Flag = Chain.getValue(1);
1807 std::vector<unsigned> R(Regs);
1808 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1809 std::reverse(R.begin(), R.end());
1811 for (unsigned i = 0, e = R.size(); i != e; ++i) {
1812 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1813 DAG.getConstant(i, PtrVT));
1814 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
1815 Flag = Chain.getValue(1);
1820 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
1821 /// operand list. This adds the code marker and includes the number of
1822 /// values added into it.
1823 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1824 std::vector<SDOperand> &Ops) const {
1825 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1826 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1827 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1830 /// isAllocatableRegister - If the specified register is safe to allocate,
1831 /// i.e. it isn't a stack pointer or some other special register, return the
1832 /// register class for the register. Otherwise, return null.
1833 static const TargetRegisterClass *
1834 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1835 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1836 MVT::ValueType FoundVT = MVT::Other;
1837 const TargetRegisterClass *FoundRC = 0;
1838 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1839 E = MRI->regclass_end(); RCI != E; ++RCI) {
1840 MVT::ValueType ThisVT = MVT::Other;
1842 const TargetRegisterClass *RC = *RCI;
1843 // If none of the the value types for this register class are valid, we
1844 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1845 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1847 if (TLI.isTypeLegal(*I)) {
1848 // If we have already found this register in a different register class,
1849 // choose the one with the largest VT specified. For example, on
1850 // PowerPC, we favor f64 register classes over f32.
1851 if (FoundVT == MVT::Other ||
1852 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1859 if (ThisVT == MVT::Other) continue;
1861 // NOTE: This isn't ideal. In particular, this might allocate the
1862 // frame pointer in functions that need it (due to them not being taken
1863 // out of allocation, because a variable sized allocation hasn't been seen
1864 // yet). This is a slight code pessimization, but should still work.
1865 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1866 E = RC->allocation_order_end(MF); I != E; ++I)
1868 // We found a matching register class. Keep looking at others in case
1869 // we find one with larger registers that this physreg is also in.
1878 RegsForValue SelectionDAGLowering::
1879 GetRegistersForValue(const std::string &ConstrCode,
1880 MVT::ValueType VT, bool isOutReg, bool isInReg,
1881 std::set<unsigned> &OutputRegs,
1882 std::set<unsigned> &InputRegs) {
1883 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1884 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1885 std::vector<unsigned> Regs;
1887 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1888 MVT::ValueType RegVT;
1889 MVT::ValueType ValueVT = VT;
1891 if (PhysReg.first) {
1892 if (VT == MVT::Other)
1893 ValueVT = *PhysReg.second->vt_begin();
1895 // Get the actual register value type. This is important, because the user
1896 // may have asked for (e.g.) the AX register in i32 type. We need to
1897 // remember that AX is actually i16 to get the right extension.
1898 RegVT = *PhysReg.second->vt_begin();
1900 // This is a explicit reference to a physical register.
1901 Regs.push_back(PhysReg.first);
1903 // If this is an expanded reference, add the rest of the regs to Regs.
1905 TargetRegisterClass::iterator I = PhysReg.second->begin();
1906 TargetRegisterClass::iterator E = PhysReg.second->end();
1907 for (; *I != PhysReg.first; ++I)
1908 assert(I != E && "Didn't find reg!");
1910 // Already added the first reg.
1912 for (; NumRegs; --NumRegs, ++I) {
1913 assert(I != E && "Ran out of registers to allocate!");
1917 return RegsForValue(Regs, RegVT, ValueVT);
1920 // This is a reference to a register class. Allocate NumRegs consecutive,
1921 // available, registers from the class.
1922 std::vector<unsigned> RegClassRegs =
1923 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1925 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1926 MachineFunction &MF = *CurMBB->getParent();
1927 unsigned NumAllocated = 0;
1928 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1929 unsigned Reg = RegClassRegs[i];
1930 // See if this register is available.
1931 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1932 (isInReg && InputRegs.count(Reg))) { // Already used.
1933 // Make sure we find consecutive registers.
1938 // Check to see if this register is allocatable (i.e. don't give out the
1940 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1942 // Make sure we find consecutive registers.
1947 // Okay, this register is good, we can use it.
1950 // If we allocated enough consecutive
1951 if (NumAllocated == NumRegs) {
1952 unsigned RegStart = (i-NumAllocated)+1;
1953 unsigned RegEnd = i+1;
1954 // Mark all of the allocated registers used.
1955 for (unsigned i = RegStart; i != RegEnd; ++i) {
1956 unsigned Reg = RegClassRegs[i];
1957 Regs.push_back(Reg);
1958 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1959 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1962 return RegsForValue(Regs, *RC->vt_begin(), VT);
1966 // Otherwise, we couldn't allocate enough registers for this.
1967 return RegsForValue();
1971 /// visitInlineAsm - Handle a call to an InlineAsm object.
1973 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1974 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1976 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1979 // Note, we treat inline asms both with and without side-effects as the same.
1980 // If an inline asm doesn't have side effects and doesn't access memory, we
1981 // could not choose to not chain it.
1982 bool hasSideEffects = IA->hasSideEffects();
1984 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1985 std::vector<MVT::ValueType> ConstraintVTs;
1987 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1988 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1989 /// if it is a def of that register.
1990 std::vector<SDOperand> AsmNodeOperands;
1991 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1992 AsmNodeOperands.push_back(AsmStr);
1994 SDOperand Chain = getRoot();
1997 // We fully assign registers here at isel time. This is not optimal, but
1998 // should work. For register classes that correspond to LLVM classes, we
1999 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2000 // over the constraints, collecting fixed registers that we know we can't use.
2001 std::set<unsigned> OutputRegs, InputRegs;
2003 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2004 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2005 std::string &ConstraintCode = Constraints[i].Codes[0];
2007 MVT::ValueType OpVT;
2009 // Compute the value type for each operand and add it to ConstraintVTs.
2010 switch (Constraints[i].Type) {
2011 case InlineAsm::isOutput:
2012 if (!Constraints[i].isIndirectOutput) {
2013 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2014 OpVT = TLI.getValueType(I.getType());
2016 const Type *OpTy = I.getOperand(OpNum)->getType();
2017 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2018 OpNum++; // Consumes a call operand.
2021 case InlineAsm::isInput:
2022 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2023 OpNum++; // Consumes a call operand.
2025 case InlineAsm::isClobber:
2030 ConstraintVTs.push_back(OpVT);
2032 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2033 continue; // Not assigned a fixed reg.
2035 // Build a list of regs that this operand uses. This always has a single
2036 // element for promoted/expanded operands.
2037 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2039 OutputRegs, InputRegs);
2041 switch (Constraints[i].Type) {
2042 case InlineAsm::isOutput:
2043 // We can't assign any other output to this register.
2044 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2045 // If this is an early-clobber output, it cannot be assigned to the same
2046 // value as the input reg.
2047 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2048 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2050 case InlineAsm::isInput:
2051 // We can't assign any other input to this register.
2052 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2054 case InlineAsm::isClobber:
2055 // Clobbered regs cannot be used as inputs or outputs.
2056 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2057 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2062 // Loop over all of the inputs, copying the operand values into the
2063 // appropriate registers and processing the output regs.
2064 RegsForValue RetValRegs;
2065 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2068 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2069 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2070 std::string &ConstraintCode = Constraints[i].Codes[0];
2072 switch (Constraints[i].Type) {
2073 case InlineAsm::isOutput: {
2074 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2075 if (ConstraintCode.size() == 1) // not a physreg name.
2076 CTy = TLI.getConstraintType(ConstraintCode[0]);
2078 if (CTy == TargetLowering::C_Memory) {
2080 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2082 // Check that the operand (the address to store to) isn't a float.
2083 if (!MVT::isInteger(InOperandVal.getValueType()))
2084 assert(0 && "MATCH FAIL!");
2086 if (!Constraints[i].isIndirectOutput)
2087 assert(0 && "MATCH FAIL!");
2089 OpNum++; // Consumes a call operand.
2091 // Extend/truncate to the right pointer type if needed.
2092 MVT::ValueType PtrType = TLI.getPointerTy();
2093 if (InOperandVal.getValueType() < PtrType)
2094 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2095 else if (InOperandVal.getValueType() > PtrType)
2096 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2098 // Add information to the INLINEASM node to know about this output.
2099 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2100 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2101 AsmNodeOperands.push_back(InOperandVal);
2105 // Otherwise, this is a register output.
2106 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2108 // If this is an early-clobber output, or if there is an input
2109 // constraint that matches this, we need to reserve the input register
2110 // so no other inputs allocate to it.
2111 bool UsesInputRegister = false;
2112 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2113 UsesInputRegister = true;
2115 // Copy the output from the appropriate register. Find a register that
2118 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2119 true, UsesInputRegister,
2120 OutputRegs, InputRegs);
2121 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
2123 if (!Constraints[i].isIndirectOutput) {
2124 assert(RetValRegs.Regs.empty() &&
2125 "Cannot have multiple output constraints yet!");
2126 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2129 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2130 I.getOperand(OpNum)));
2131 OpNum++; // Consumes a call operand.
2134 // Add information to the INLINEASM node to know that this register is
2136 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2139 case InlineAsm::isInput: {
2140 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2141 OpNum++; // Consumes a call operand.
2143 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2144 // If this is required to match an output register we have already set,
2145 // just use its register.
2146 unsigned OperandNo = atoi(ConstraintCode.c_str());
2148 // Scan until we find the definition we already emitted of this operand.
2149 // When we find it, create a RegsForValue operand.
2150 unsigned CurOp = 2; // The first operand.
2151 for (; OperandNo; --OperandNo) {
2152 // Advance to the next operand.
2154 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2155 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2156 (NumOps & 7) == 4 /*MEM*/) &&
2157 "Skipped past definitions?");
2158 CurOp += (NumOps>>3)+1;
2162 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2163 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2164 "Skipped past definitions?");
2166 // Add NumOps>>3 registers to MatchedRegs.
2167 RegsForValue MatchedRegs;
2168 MatchedRegs.ValueVT = InOperandVal.getValueType();
2169 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2170 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2171 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2172 MatchedRegs.Regs.push_back(Reg);
2175 // Use the produced MatchedRegs object to
2176 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2177 TLI.getPointerTy());
2178 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2182 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2183 if (ConstraintCode.size() == 1) // not a physreg name.
2184 CTy = TLI.getConstraintType(ConstraintCode[0]);
2186 if (CTy == TargetLowering::C_Other) {
2187 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2188 assert(0 && "MATCH FAIL!");
2190 // Add information to the INLINEASM node to know about this input.
2191 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2192 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2193 AsmNodeOperands.push_back(InOperandVal);
2195 } else if (CTy == TargetLowering::C_Memory) {
2198 // Check that the operand isn't a float.
2199 if (!MVT::isInteger(InOperandVal.getValueType()))
2200 assert(0 && "MATCH FAIL!");
2202 // Extend/truncate to the right pointer type if needed.
2203 MVT::ValueType PtrType = TLI.getPointerTy();
2204 if (InOperandVal.getValueType() < PtrType)
2205 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2206 else if (InOperandVal.getValueType() > PtrType)
2207 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2209 // Add information to the INLINEASM node to know about this input.
2210 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2211 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2212 AsmNodeOperands.push_back(InOperandVal);
2216 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2218 // Copy the input into the appropriate registers.
2219 RegsForValue InRegs =
2220 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2221 false, true, OutputRegs, InputRegs);
2222 // FIXME: should be match fail.
2223 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2225 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2227 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2230 case InlineAsm::isClobber: {
2231 RegsForValue ClobberedRegs =
2232 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2233 OutputRegs, InputRegs);
2234 // Add the clobbered value to the operand list, so that the register
2235 // allocator is aware that the physreg got clobbered.
2236 if (!ClobberedRegs.Regs.empty())
2237 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2243 // Finish up input operands.
2244 AsmNodeOperands[0] = Chain;
2245 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2247 std::vector<MVT::ValueType> VTs;
2248 VTs.push_back(MVT::Other);
2249 VTs.push_back(MVT::Flag);
2250 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2251 Flag = Chain.getValue(1);
2253 // If this asm returns a register value, copy the result from that register
2254 // and set it as the value of the call.
2255 if (!RetValRegs.Regs.empty())
2256 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2258 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2260 // Process indirect outputs, first output all of the flagged copies out of
2262 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2263 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2264 Value *Ptr = IndirectStoresToEmit[i].second;
2265 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2266 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2269 // Emit the non-flagged stores from the physregs.
2270 std::vector<SDOperand> OutChains;
2271 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2272 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2273 StoresToEmit[i].first,
2274 getValue(StoresToEmit[i].second),
2275 DAG.getSrcValue(StoresToEmit[i].second)));
2276 if (!OutChains.empty())
2277 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2282 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2283 SDOperand Src = getValue(I.getOperand(0));
2285 MVT::ValueType IntPtr = TLI.getPointerTy();
2287 if (IntPtr < Src.getValueType())
2288 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2289 else if (IntPtr > Src.getValueType())
2290 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2292 // Scale the source by the type size.
2293 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2294 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2295 Src, getIntPtrConstant(ElementSize));
2297 std::vector<std::pair<SDOperand, const Type*> > Args;
2298 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
2300 std::pair<SDOperand,SDOperand> Result =
2301 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2302 DAG.getExternalSymbol("malloc", IntPtr),
2304 setValue(&I, Result.first); // Pointers always fit in registers
2305 DAG.setRoot(Result.second);
2308 void SelectionDAGLowering::visitFree(FreeInst &I) {
2309 std::vector<std::pair<SDOperand, const Type*> > Args;
2310 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2311 TLI.getTargetData()->getIntPtrType()));
2312 MVT::ValueType IntPtr = TLI.getPointerTy();
2313 std::pair<SDOperand,SDOperand> Result =
2314 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2315 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2316 DAG.setRoot(Result.second);
2319 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2320 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2321 // instructions are special in various ways, which require special support to
2322 // insert. The specified MachineInstr is created but not inserted into any
2323 // basic blocks, and the scheduler passes ownership of it to this method.
2324 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2325 MachineBasicBlock *MBB) {
2326 std::cerr << "If a target marks an instruction with "
2327 "'usesCustomDAGSchedInserter', it must implement "
2328 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2333 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2334 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2335 getValue(I.getOperand(1)),
2336 DAG.getSrcValue(I.getOperand(1))));
2339 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2340 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2341 getValue(I.getOperand(0)),
2342 DAG.getSrcValue(I.getOperand(0)));
2344 DAG.setRoot(V.getValue(1));
2347 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2348 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2349 getValue(I.getOperand(1)),
2350 DAG.getSrcValue(I.getOperand(1))));
2353 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2354 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2355 getValue(I.getOperand(1)),
2356 getValue(I.getOperand(2)),
2357 DAG.getSrcValue(I.getOperand(1)),
2358 DAG.getSrcValue(I.getOperand(2))));
2361 /// TargetLowering::LowerArguments - This is the default LowerArguments
2362 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
2363 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2364 /// integrated into SDISel.
2365 std::vector<SDOperand>
2366 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2367 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2368 std::vector<SDOperand> Ops;
2369 Ops.push_back(DAG.getRoot());
2370 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2371 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2373 // Add one result value for each formal argument.
2374 std::vector<MVT::ValueType> RetVals;
2375 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2376 MVT::ValueType VT = getValueType(I->getType());
2378 switch (getTypeAction(VT)) {
2379 default: assert(0 && "Unknown type action!");
2381 RetVals.push_back(VT);
2384 RetVals.push_back(getTypeToTransformTo(VT));
2387 if (VT != MVT::Vector) {
2388 // If this is a large integer, it needs to be broken up into small
2389 // integers. Figure out what the destination type is and how many small
2390 // integers it turns into.
2391 MVT::ValueType NVT = getTypeToTransformTo(VT);
2392 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2393 for (unsigned i = 0; i != NumVals; ++i)
2394 RetVals.push_back(NVT);
2396 // Otherwise, this is a vector type. We only support legal vectors
2398 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2399 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2401 // Figure out if there is a Packed type corresponding to this Vector
2402 // type. If so, convert to the packed type.
2403 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2404 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2405 RetVals.push_back(TVT);
2407 assert(0 && "Don't support illegal by-val vector arguments yet!");
2414 RetVals.push_back(MVT::Other);
2417 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, RetVals, Ops).Val;
2419 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
2421 // Set up the return result vector.
2424 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2425 MVT::ValueType VT = getValueType(I->getType());
2427 switch (getTypeAction(VT)) {
2428 default: assert(0 && "Unknown type action!");
2430 Ops.push_back(SDOperand(Result, i++));
2433 SDOperand Op(Result, i++);
2434 if (MVT::isInteger(VT)) {
2435 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2437 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2438 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2440 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2441 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2447 if (VT != MVT::Vector) {
2448 // If this is a large integer, it needs to be reassembled from small
2449 // integers. Figure out what the source elt type is and how many small
2451 MVT::ValueType NVT = getTypeToTransformTo(VT);
2452 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2454 SDOperand Lo = SDOperand(Result, i++);
2455 SDOperand Hi = SDOperand(Result, i++);
2457 if (!isLittleEndian())
2460 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2462 // Value scalarized into many values. Unimp for now.
2463 assert(0 && "Cannot expand i64 -> i16 yet!");
2466 // Otherwise, this is a vector type. We only support legal vectors
2468 const PackedType *PTy = cast<PackedType>(I->getType());
2469 unsigned NumElems = PTy->getNumElements();
2470 const Type *EltTy = PTy->getElementType();
2472 // Figure out if there is a Packed type corresponding to this Vector
2473 // type. If so, convert to the packed type.
2474 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2475 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2476 SDOperand N = SDOperand(Result, i++);
2477 // Handle copies from generic vectors to registers.
2478 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2479 DAG.getConstant(NumElems, MVT::i32),
2480 DAG.getValueType(getValueType(EltTy)));
2483 assert(0 && "Don't support illegal by-val vector arguments yet!");
2494 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
2495 /// implementation, which just inserts an ISD::CALL node, which is later custom
2496 /// lowered by the target to something concrete. FIXME: When all targets are
2497 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2498 std::pair<SDOperand, SDOperand>
2499 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2500 unsigned CallingConv, bool isTailCall,
2502 ArgListTy &Args, SelectionDAG &DAG) {
2503 std::vector<SDOperand> Ops;
2504 Ops.push_back(Chain); // Op#0 - Chain
2505 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2506 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2507 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2508 Ops.push_back(Callee);
2510 // Handle all of the outgoing arguments.
2511 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2512 MVT::ValueType VT = getValueType(Args[i].second);
2513 SDOperand Op = Args[i].first;
2514 bool isSigned = Args[i].second->isSigned();
2515 switch (getTypeAction(VT)) {
2516 default: assert(0 && "Unknown type action!");
2519 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2522 if (MVT::isInteger(VT)) {
2523 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2524 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2526 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2527 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2530 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2533 if (VT != MVT::Vector) {
2534 // If this is a large integer, it needs to be broken down into small
2535 // integers. Figure out what the source elt type is and how many small
2537 MVT::ValueType NVT = getTypeToTransformTo(VT);
2538 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2540 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2541 DAG.getConstant(0, getPointerTy()));
2542 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2543 DAG.getConstant(1, getPointerTy()));
2544 if (!isLittleEndian())
2548 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2550 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2552 // Value scalarized into many values. Unimp for now.
2553 assert(0 && "Cannot expand i64 -> i16 yet!");
2556 // Otherwise, this is a vector type. We only support legal vectors
2558 const PackedType *PTy = cast<PackedType>(Args[i].second);
2559 unsigned NumElems = PTy->getNumElements();
2560 const Type *EltTy = PTy->getElementType();
2562 // Figure out if there is a Packed type corresponding to this Vector
2563 // type. If so, convert to the packed type.
2564 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2565 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2566 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2567 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2569 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2571 assert(0 && "Don't support illegal by-val vector call args yet!");
2579 // Figure out the result value types.
2580 std::vector<MVT::ValueType> RetTys;
2582 if (RetTy != Type::VoidTy) {
2583 MVT::ValueType VT = getValueType(RetTy);
2584 switch (getTypeAction(VT)) {
2585 default: assert(0 && "Unknown type action!");
2587 RetTys.push_back(VT);
2590 RetTys.push_back(getTypeToTransformTo(VT));
2593 if (VT != MVT::Vector) {
2594 // If this is a large integer, it needs to be reassembled from small
2595 // integers. Figure out what the source elt type is and how many small
2597 MVT::ValueType NVT = getTypeToTransformTo(VT);
2598 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2599 for (unsigned i = 0; i != NumVals; ++i)
2600 RetTys.push_back(NVT);
2602 // Otherwise, this is a vector type. We only support legal vectors
2604 const PackedType *PTy = cast<PackedType>(RetTy);
2605 unsigned NumElems = PTy->getNumElements();
2606 const Type *EltTy = PTy->getElementType();
2608 // Figure out if there is a Packed type corresponding to this Vector
2609 // type. If so, convert to the packed type.
2610 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2611 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2612 RetTys.push_back(TVT);
2614 assert(0 && "Don't support illegal by-val vector call results yet!");
2621 RetTys.push_back(MVT::Other); // Always has a chain.
2623 // Finally, create the CALL node.
2624 SDOperand Res = DAG.getNode(ISD::CALL, RetTys, Ops);
2626 // This returns a pair of operands. The first element is the
2627 // return value for the function (if RetTy is not VoidTy). The second
2628 // element is the outgoing token chain.
2630 if (RetTys.size() != 1) {
2631 MVT::ValueType VT = getValueType(RetTy);
2632 if (RetTys.size() == 2) {
2635 // If this value was promoted, truncate it down.
2636 if (ResVal.getValueType() != VT) {
2637 if (VT == MVT::Vector) {
2638 // Insert a VBITCONVERT to convert from the packed result type to the
2639 // MVT::Vector type.
2640 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2641 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2643 // Figure out if there is a Packed type corresponding to this Vector
2644 // type. If so, convert to the packed type.
2645 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2646 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2647 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2648 // "N x PTyElementVT" MVT::Vector type.
2649 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
2650 DAG.getConstant(NumElems, MVT::i32),
2651 DAG.getValueType(getValueType(EltTy)));
2655 } else if (MVT::isInteger(VT)) {
2656 unsigned AssertOp = RetTy->isSigned() ?
2657 ISD::AssertSext : ISD::AssertZext;
2658 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2659 DAG.getValueType(VT));
2660 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2662 assert(MVT::isFloatingPoint(VT));
2663 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2666 } else if (RetTys.size() == 3) {
2667 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2668 Res.getValue(0), Res.getValue(1));
2671 assert(0 && "Case not handled yet!");
2675 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2680 // It is always conservatively correct for llvm.returnaddress and
2681 // llvm.frameaddress to return 0.
2683 // FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2684 // expanded to 0 if the target wants.
2685 std::pair<SDOperand, SDOperand>
2686 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2687 unsigned Depth, SelectionDAG &DAG) {
2688 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
2691 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
2692 assert(0 && "LowerOperation not implemented for this target!");
2697 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2698 SelectionDAG &DAG) {
2699 assert(0 && "CustomPromoteOperation not implemented for this target!");
2704 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2705 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2706 std::pair<SDOperand,SDOperand> Result =
2707 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
2708 setValue(&I, Result.first);
2709 DAG.setRoot(Result.second);
2712 /// getMemsetValue - Vectorized representation of the memset value
2714 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2715 SelectionDAG &DAG) {
2716 MVT::ValueType CurVT = VT;
2717 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2718 uint64_t Val = C->getValue() & 255;
2720 while (CurVT != MVT::i8) {
2721 Val = (Val << Shift) | Val;
2723 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2725 return DAG.getConstant(Val, VT);
2727 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2729 while (CurVT != MVT::i8) {
2731 DAG.getNode(ISD::OR, VT,
2732 DAG.getNode(ISD::SHL, VT, Value,
2733 DAG.getConstant(Shift, MVT::i8)), Value);
2735 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2742 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2743 /// used when a memcpy is turned into a memset when the source is a constant
2745 static SDOperand getMemsetStringVal(MVT::ValueType VT,
2746 SelectionDAG &DAG, TargetLowering &TLI,
2747 std::string &Str, unsigned Offset) {
2748 MVT::ValueType CurVT = VT;
2750 unsigned MSB = getSizeInBits(VT) / 8;
2751 if (TLI.isLittleEndian())
2752 Offset = Offset + MSB - 1;
2753 for (unsigned i = 0; i != MSB; ++i) {
2754 Val = (Val << 8) | Str[Offset];
2755 Offset += TLI.isLittleEndian() ? -1 : 1;
2757 return DAG.getConstant(Val, VT);
2760 /// getMemBasePlusOffset - Returns base and offset node for the
2761 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2762 SelectionDAG &DAG, TargetLowering &TLI) {
2763 MVT::ValueType VT = Base.getValueType();
2764 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2767 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2768 /// to replace the memset / memcpy is below the threshold. It also returns the
2769 /// types of the sequence of memory ops to perform memset / memcpy.
2770 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2771 unsigned Limit, uint64_t Size,
2772 unsigned Align, TargetLowering &TLI) {
2775 if (TLI.allowsUnalignedMemoryAccesses()) {
2778 switch (Align & 7) {
2794 MVT::ValueType LVT = MVT::i64;
2795 while (!TLI.isTypeLegal(LVT))
2796 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2797 assert(MVT::isInteger(LVT));
2802 unsigned NumMemOps = 0;
2804 unsigned VTSize = getSizeInBits(VT) / 8;
2805 while (VTSize > Size) {
2806 VT = (MVT::ValueType)((unsigned)VT - 1);
2809 assert(MVT::isInteger(VT));
2811 if (++NumMemOps > Limit)
2813 MemOps.push_back(VT);
2820 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
2821 SDOperand Op1 = getValue(I.getOperand(1));
2822 SDOperand Op2 = getValue(I.getOperand(2));
2823 SDOperand Op3 = getValue(I.getOperand(3));
2824 SDOperand Op4 = getValue(I.getOperand(4));
2825 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2826 if (Align == 0) Align = 1;
2828 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2829 std::vector<MVT::ValueType> MemOps;
2831 // Expand memset / memcpy to a series of load / store ops
2832 // if the size operand falls below a certain threshold.
2833 std::vector<SDOperand> OutChains;
2835 default: break; // Do nothing for now.
2837 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2838 Size->getValue(), Align, TLI)) {
2839 unsigned NumMemOps = MemOps.size();
2840 unsigned Offset = 0;
2841 for (unsigned i = 0; i < NumMemOps; i++) {
2842 MVT::ValueType VT = MemOps[i];
2843 unsigned VTSize = getSizeInBits(VT) / 8;
2844 SDOperand Value = getMemsetValue(Op2, VT, DAG);
2845 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2847 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2848 DAG.getSrcValue(I.getOperand(1), Offset));
2849 OutChains.push_back(Store);
2856 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2857 Size->getValue(), Align, TLI)) {
2858 unsigned NumMemOps = MemOps.size();
2859 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
2860 GlobalAddressSDNode *G = NULL;
2862 bool CopyFromStr = false;
2864 if (Op2.getOpcode() == ISD::GlobalAddress)
2865 G = cast<GlobalAddressSDNode>(Op2);
2866 else if (Op2.getOpcode() == ISD::ADD &&
2867 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2868 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2869 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
2870 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
2873 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2875 Str = GV->getStringValue(false);
2883 for (unsigned i = 0; i < NumMemOps; i++) {
2884 MVT::ValueType VT = MemOps[i];
2885 unsigned VTSize = getSizeInBits(VT) / 8;
2886 SDOperand Value, Chain, Store;
2889 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2892 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2893 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2894 DAG.getSrcValue(I.getOperand(1), DstOff));
2896 Value = DAG.getLoad(VT, getRoot(),
2897 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2898 DAG.getSrcValue(I.getOperand(2), SrcOff));
2899 Chain = Value.getValue(1);
2901 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2902 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2903 DAG.getSrcValue(I.getOperand(1), DstOff));
2905 OutChains.push_back(Store);
2914 if (!OutChains.empty()) {
2915 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2920 std::vector<SDOperand> Ops;
2921 Ops.push_back(getRoot());
2926 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
2929 //===----------------------------------------------------------------------===//
2930 // SelectionDAGISel code
2931 //===----------------------------------------------------------------------===//
2933 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2934 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2937 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
2938 // FIXME: we only modify the CFG to split critical edges. This
2939 // updates dom and loop info.
2943 /// OptimizeNoopCopyExpression - We have determined that the specified cast
2944 /// instruction is a noop copy (e.g. it's casting from one pointer type to
2945 /// another, int->uint, or int->sbyte on PPC.
2947 /// Return true if any changes are made.
2948 static bool OptimizeNoopCopyExpression(CastInst *CI) {
2949 BasicBlock *DefBB = CI->getParent();
2951 /// InsertedCasts - Only insert a cast in each block once.
2952 std::map<BasicBlock*, CastInst*> InsertedCasts;
2954 bool MadeChange = false;
2955 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
2957 Use &TheUse = UI.getUse();
2958 Instruction *User = cast<Instruction>(*UI);
2960 // Figure out which BB this cast is used in. For PHI's this is the
2961 // appropriate predecessor block.
2962 BasicBlock *UserBB = User->getParent();
2963 if (PHINode *PN = dyn_cast<PHINode>(User)) {
2964 unsigned OpVal = UI.getOperandNo()/2;
2965 UserBB = PN->getIncomingBlock(OpVal);
2968 // Preincrement use iterator so we don't invalidate it.
2971 // If this user is in the same block as the cast, don't change the cast.
2972 if (UserBB == DefBB) continue;
2974 // If we have already inserted a cast into this block, use it.
2975 CastInst *&InsertedCast = InsertedCasts[UserBB];
2977 if (!InsertedCast) {
2978 BasicBlock::iterator InsertPt = UserBB->begin();
2979 while (isa<PHINode>(InsertPt)) ++InsertPt;
2982 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2986 // Replace a use of the cast with a use of the new casat.
2987 TheUse = InsertedCast;
2990 // If we removed all uses, nuke the cast.
2991 if (CI->use_empty())
2992 CI->eraseFromParent();
2997 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2998 /// casting to the type of GEPI.
2999 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3000 Instruction *GEPI, Value *Ptr,
3002 if (V) return V; // Already computed.
3004 BasicBlock::iterator InsertPt;
3005 if (BB == GEPI->getParent()) {
3006 // If insert into the GEP's block, insert right after the GEP.
3010 // Otherwise, insert at the top of BB, after any PHI nodes
3011 InsertPt = BB->begin();
3012 while (isa<PHINode>(InsertPt)) ++InsertPt;
3015 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3016 // BB so that there is only one value live across basic blocks (the cast
3018 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3019 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3020 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3022 // Add the offset, cast it to the right type.
3023 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3024 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
3027 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3028 /// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3029 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3030 /// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3031 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
3032 /// the constant add into a load or store instruction. Additionally, if a user
3033 /// is a pointer-pointer cast, we look through it to find its users.
3034 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3035 Constant *PtrOffset, BasicBlock *DefBB,
3036 GetElementPtrInst *GEPI,
3037 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3038 while (!RepPtr->use_empty()) {
3039 Instruction *User = cast<Instruction>(RepPtr->use_back());
3041 // If the user is a Pointer-Pointer cast, recurse.
3042 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3043 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3045 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3046 // could invalidate an iterator.
3047 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3051 // If this is a load of the pointer, or a store through the pointer, emit
3052 // the increment into the load/store block.
3053 Instruction *NewVal;
3054 if (isa<LoadInst>(User) ||
3055 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3056 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3057 User->getParent(), GEPI,
3060 // If this use is not foldable into the addressing mode, use a version
3061 // emitted in the GEP block.
3062 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3066 if (GEPI->getType() != RepPtr->getType()) {
3067 BasicBlock::iterator IP = NewVal;
3069 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3071 User->replaceUsesOfWith(RepPtr, NewVal);
3076 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3077 /// selection, we want to be a bit careful about some things. In particular, if
3078 /// we have a GEP instruction that is used in a different block than it is
3079 /// defined, the addressing expression of the GEP cannot be folded into loads or
3080 /// stores that use it. In this case, decompose the GEP and move constant
3081 /// indices into blocks that use it.
3082 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3083 const TargetData *TD) {
3084 // If this GEP is only used inside the block it is defined in, there is no
3085 // need to rewrite it.
3086 bool isUsedOutsideDefBB = false;
3087 BasicBlock *DefBB = GEPI->getParent();
3088 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3090 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3091 isUsedOutsideDefBB = true;
3095 if (!isUsedOutsideDefBB) return false;
3097 // If this GEP has no non-zero constant indices, there is nothing we can do,
3099 bool hasConstantIndex = false;
3100 bool hasVariableIndex = false;
3101 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3102 E = GEPI->op_end(); OI != E; ++OI) {
3103 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3104 if (CI->getRawValue()) {
3105 hasConstantIndex = true;
3109 hasVariableIndex = true;
3113 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3114 if (!hasConstantIndex && !hasVariableIndex) {
3115 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3116 GEPI->getName(), GEPI);
3117 GEPI->replaceAllUsesWith(NC);
3118 GEPI->eraseFromParent();
3122 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3123 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3126 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3127 // constant offset (which we now know is non-zero) and deal with it later.
3128 uint64_t ConstantOffset = 0;
3129 const Type *UIntPtrTy = TD->getIntPtrType();
3130 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3131 const Type *Ty = GEPI->getOperand(0)->getType();
3133 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3134 E = GEPI->op_end(); OI != E; ++OI) {
3136 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3137 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
3139 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
3140 Ty = StTy->getElementType(Field);
3142 Ty = cast<SequentialType>(Ty)->getElementType();
3144 // Handle constant subscripts.
3145 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3146 if (CI->getRawValue() == 0) continue;
3148 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
3149 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CSI->getValue();
3151 ConstantOffset+=TD->getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
3155 // Ptr = Ptr + Idx * ElementSize;
3157 // Cast Idx to UIntPtrTy if needed.
3158 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3160 uint64_t ElementSize = TD->getTypeSize(Ty);
3161 // Mask off bits that should not be set.
3162 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3163 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
3165 // Multiply by the element size and add to the base.
3166 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3167 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3171 // Make sure that the offset fits in uintptr_t.
3172 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3173 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
3175 // Okay, we have now emitted all of the variable index parts to the BB that
3176 // the GEP is defined in. Loop over all of the using instructions, inserting
3177 // an "add Ptr, ConstantOffset" into each block that uses it and update the
3178 // instruction to use the newly computed value, making GEPI dead. When the
3179 // user is a load or store instruction address, we emit the add into the user
3180 // block, otherwise we use a canonical version right next to the gep (these
3181 // won't be foldable as addresses, so we might as well share the computation).
3183 std::map<BasicBlock*,Instruction*> InsertedExprs;
3184 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3186 // Finally, the GEP is dead, remove it.
3187 GEPI->eraseFromParent();
3192 bool SelectionDAGISel::runOnFunction(Function &Fn) {
3193 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3194 RegMap = MF.getSSARegMap();
3195 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3197 // First, split all critical edges for PHI nodes with incoming values that are
3198 // constants, this way the load of the constant into a vreg will not be placed
3199 // into MBBs that are used some other way.
3201 // In this pass we also look for GEP and cast instructions that are used
3202 // across basic blocks and rewrite them to improve basic-block-at-a-time
3206 bool MadeChange = true;
3207 while (MadeChange) {
3209 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3211 BasicBlock::iterator BBI;
3212 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
3213 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3214 if (isa<Constant>(PN->getIncomingValue(i)))
3215 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3217 for (BasicBlock::iterator E = BB->end(); BBI != E; ) {
3218 Instruction *I = BBI++;
3219 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3220 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3221 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3222 // If this is a noop copy, sink it into user blocks to reduce the number
3223 // of virtual registers that must be created and coallesced.
3224 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3225 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3227 // This is an fp<->int conversion?
3228 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3231 // If this is an extension, it will be a zero or sign extension, which
3233 if (SrcVT < DstVT) continue;
3235 // If these values will be promoted, find out what they will be promoted
3236 // to. This helps us consider truncates on PPC as noop copies when they
3238 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3239 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3240 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3241 DstVT = TLI.getTypeToTransformTo(DstVT);
3243 // If, after promotion, these are the same types, this is a noop copy.
3245 MadeChange |= OptimizeNoopCopyExpression(CI);
3251 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3253 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3254 SelectBasicBlock(I, MF, FuncInfo);
3260 SDOperand SelectionDAGISel::
3261 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
3262 SDOperand Op = SDL.getValue(V);
3263 assert((Op.getOpcode() != ISD::CopyFromReg ||
3264 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3265 "Copy from a reg to the same reg!");
3267 // If this type is not legal, we must make sure to not create an invalid
3269 MVT::ValueType SrcVT = Op.getValueType();
3270 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3271 SelectionDAG &DAG = SDL.DAG;
3272 if (SrcVT == DestVT) {
3273 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3274 } else if (SrcVT == MVT::Vector) {
3275 // Handle copies from generic vectors to registers.
3276 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3277 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3278 PTyElementVT, PTyLegalElementVT);
3280 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3281 // MVT::Vector type.
3282 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3283 DAG.getConstant(NE, MVT::i32),
3284 DAG.getValueType(PTyElementVT));
3286 // Loop over all of the elements of the resultant vector,
3287 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3288 // copying them into output registers.
3289 std::vector<SDOperand> OutChains;
3290 SDOperand Root = SDL.getRoot();
3291 for (unsigned i = 0; i != NE; ++i) {
3292 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3293 Op, DAG.getConstant(i, TLI.getPointerTy()));
3294 if (PTyElementVT == PTyLegalElementVT) {
3295 // Elements are legal.
3296 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3297 } else if (PTyLegalElementVT > PTyElementVT) {
3298 // Elements are promoted.
3299 if (MVT::isFloatingPoint(PTyLegalElementVT))
3300 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3302 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3303 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3305 // Elements are expanded.
3306 // The src value is expanded into multiple registers.
3307 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3308 Elt, DAG.getConstant(0, TLI.getPointerTy()));
3309 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3310 Elt, DAG.getConstant(1, TLI.getPointerTy()));
3311 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3312 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3315 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
3316 } else if (SrcVT < DestVT) {
3317 // The src value is promoted to the register.
3318 if (MVT::isFloatingPoint(SrcVT))
3319 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3321 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3322 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3324 // The src value is expanded into multiple registers.
3325 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3326 Op, DAG.getConstant(0, TLI.getPointerTy()));
3327 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3328 Op, DAG.getConstant(1, TLI.getPointerTy()));
3329 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3330 return DAG.getCopyToReg(Op, Reg+1, Hi);
3334 void SelectionDAGISel::
3335 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3336 std::vector<SDOperand> &UnorderedChains) {
3337 // If this is the entry block, emit arguments.
3338 Function &F = *BB->getParent();
3339 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3340 SDOperand OldRoot = SDL.DAG.getRoot();
3341 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3344 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3346 if (!AI->use_empty()) {
3347 SDL.setValue(AI, Args[a]);
3349 // If this argument is live outside of the entry block, insert a copy from
3350 // whereever we got it to the vreg that other BB's will reference it as.
3351 if (FuncInfo.ValueMap.count(AI)) {
3353 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3354 UnorderedChains.push_back(Copy);
3358 // Finally, if the target has anything special to do, allow it to do so.
3359 // FIXME: this should insert code into the DAG!
3360 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3363 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3364 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3365 FunctionLoweringInfo &FuncInfo) {
3366 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3368 std::vector<SDOperand> UnorderedChains;
3370 // Lower any arguments needed in this block if this is the entry block.
3371 if (LLVMBB == &LLVMBB->getParent()->front())
3372 LowerArguments(LLVMBB, SDL, UnorderedChains);
3374 BB = FuncInfo.MBBMap[LLVMBB];
3375 SDL.setCurrentBasicBlock(BB);
3377 // Lower all of the non-terminator instructions.
3378 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3382 // Ensure that all instructions which are used outside of their defining
3383 // blocks are available as virtual registers.
3384 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3385 if (!I->use_empty() && !isa<PHINode>(I)) {
3386 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3387 if (VMI != FuncInfo.ValueMap.end())
3388 UnorderedChains.push_back(
3389 CopyValueToVirtualRegister(SDL, I, VMI->second));
3392 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3393 // ensure constants are generated when needed. Remember the virtual registers
3394 // that need to be added to the Machine PHI nodes as input. We cannot just
3395 // directly add them, because expansion might result in multiple MBB's for one
3396 // BB. As such, the start of the BB might correspond to a different MBB than
3400 // Emit constants only once even if used by multiple PHI nodes.
3401 std::map<Constant*, unsigned> ConstantsOut;
3403 // Check successor nodes PHI nodes that expect a constant to be available from
3405 TerminatorInst *TI = LLVMBB->getTerminator();
3406 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3407 BasicBlock *SuccBB = TI->getSuccessor(succ);
3408 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3411 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3412 // nodes and Machine PHI nodes, but the incoming operands have not been
3414 for (BasicBlock::iterator I = SuccBB->begin();
3415 (PN = dyn_cast<PHINode>(I)); ++I)
3416 if (!PN->use_empty()) {
3418 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3419 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3420 unsigned &RegOut = ConstantsOut[C];
3422 RegOut = FuncInfo.CreateRegForValue(C);
3423 UnorderedChains.push_back(
3424 CopyValueToVirtualRegister(SDL, C, RegOut));
3428 Reg = FuncInfo.ValueMap[PHIOp];
3430 assert(isa<AllocaInst>(PHIOp) &&
3431 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3432 "Didn't codegen value into a register!??");
3433 Reg = FuncInfo.CreateRegForValue(PHIOp);
3434 UnorderedChains.push_back(
3435 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
3439 // Remember that this register needs to added to the machine PHI node as
3440 // the input for this MBB.
3441 MVT::ValueType VT = TLI.getValueType(PN->getType());
3442 unsigned NumElements;
3443 if (VT != MVT::Vector)
3444 NumElements = TLI.getNumElements(VT);
3446 MVT::ValueType VT1,VT2;
3448 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3451 for (unsigned i = 0, e = NumElements; i != e; ++i)
3452 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3455 ConstantsOut.clear();
3457 // Turn all of the unordered chains into one factored node.
3458 if (!UnorderedChains.empty()) {
3459 SDOperand Root = SDL.getRoot();
3460 if (Root.getOpcode() != ISD::EntryToken) {
3461 unsigned i = 0, e = UnorderedChains.size();
3462 for (; i != e; ++i) {
3463 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3464 if (UnorderedChains[i].Val->getOperand(0) == Root)
3465 break; // Don't add the root if we already indirectly depend on it.
3469 UnorderedChains.push_back(Root);
3471 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
3474 // Lower the terminator after the copies are emitted.
3475 SDL.visit(*LLVMBB->getTerminator());
3477 // Copy over any CaseBlock records that may now exist due to SwitchInst
3478 // lowering, as well as any jump table information.
3479 SwitchCases.clear();
3480 SwitchCases = SDL.SwitchCases;
3483 // Make sure the root of the DAG is up-to-date.
3484 DAG.setRoot(SDL.getRoot());
3487 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
3488 // Run the DAG combiner in pre-legalize mode.
3491 DEBUG(std::cerr << "Lowered selection DAG:\n");
3494 // Second step, hack on the DAG until it only uses operations and types that
3495 // the target supports.
3498 DEBUG(std::cerr << "Legalized selection DAG:\n");
3501 // Run the DAG combiner in post-legalize mode.
3504 if (ViewISelDAGs) DAG.viewGraph();
3506 // Third, instruction select all of the operations to machine code, adding the
3507 // code to the MachineBasicBlock.
3508 InstructionSelectBasicBlock(DAG);
3510 DEBUG(std::cerr << "Selected machine code:\n");
3514 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3515 FunctionLoweringInfo &FuncInfo) {
3516 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3518 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3521 // First step, lower LLVM code to some DAG. This DAG may use operations and
3522 // types that are not supported by the target.
3523 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3525 // Second step, emit the lowered DAG as machine code.
3526 CodeGenAndEmitDAG(DAG);
3529 // Next, now that we know what the last MBB the LLVM BB expanded is, update
3530 // PHI nodes in successors.
3531 if (SwitchCases.empty() && JT.Reg == 0) {
3532 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3533 MachineInstr *PHI = PHINodesToUpdate[i].first;
3534 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3535 "This is not a machine PHI node that we are updating!");
3536 PHI->addRegOperand(PHINodesToUpdate[i].second);
3537 PHI->addMachineBasicBlockOperand(BB);
3542 // If the JumpTable record is filled in, then we need to emit a jump table.
3543 // Updating the PHI nodes is tricky in this case, since we need to determine
3544 // whether the PHI is a successor of the range check MBB or the jump table MBB
3546 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3547 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3549 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3550 MachineBasicBlock *RangeBB = BB;
3551 // Set the current basic block to the mbb we wish to insert the code into
3553 SDL.setCurrentBasicBlock(BB);
3555 SDL.visitJumpTable(JT);
3556 SDAG.setRoot(SDL.getRoot());
3557 CodeGenAndEmitDAG(SDAG);
3559 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3560 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3561 MachineBasicBlock *PHIBB = PHI->getParent();
3562 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3563 "This is not a machine PHI node that we are updating!");
3564 if (PHIBB == JT.Default) {
3565 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3566 PHI->addMachineBasicBlockOperand(RangeBB);
3568 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
3569 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3570 PHI->addMachineBasicBlockOperand(BB);
3576 // If we generated any switch lowering information, build and codegen any
3577 // additional DAGs necessary.
3578 for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
3579 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3581 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3582 // Set the current basic block to the mbb we wish to insert the code into
3583 BB = SwitchCases[i].ThisBB;
3584 SDL.setCurrentBasicBlock(BB);
3586 SDL.visitSwitchCase(SwitchCases[i]);
3587 SDAG.setRoot(SDL.getRoot());
3588 CodeGenAndEmitDAG(SDAG);
3589 // Iterate over the phi nodes, if there is a phi node in a successor of this
3590 // block (for instance, the default block), then add a pair of operands to
3591 // the phi node for this block, as if we were coming from the original
3592 // BB before switch expansion.
3593 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3594 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3595 MachineBasicBlock *PHIBB = PHI->getParent();
3596 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3597 "This is not a machine PHI node that we are updating!");
3598 if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
3599 PHI->addRegOperand(PHINodesToUpdate[pi].second);
3600 PHI->addMachineBasicBlockOperand(BB);
3607 //===----------------------------------------------------------------------===//
3608 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3609 /// target node in the graph.
3610 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3611 if (ViewSchedDAGs) DAG.viewGraph();
3613 static RegisterScheduler::FunctionPassCtor Ctor =
3614 RegisterScheduler::getCache();
3617 if (std::string("default") == std::string(ISHeuristic)) {
3618 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
3619 Ctor = RegisterScheduler::FindCtor("list-td");
3621 assert(TLI.getSchedulingPreference() ==
3622 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
3623 Ctor = RegisterScheduler::FindCtor("list-burr");
3626 assert(Ctor && "Default instruction scheduler not present");
3627 if (!Ctor) Ctor = RegisterScheduler::FindCtor("none");
3629 Ctor = RegisterScheduler::FindCtor(ISHeuristic);
3632 RegisterScheduler::setCache(Ctor);
3635 assert(Ctor && "No instruction scheduler found");
3636 ScheduleDAG *SL = Ctor(&DAG, BB);
3642 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3643 /// by tblgen. Others should not call it.
3644 void SelectionDAGISel::
3645 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3646 std::vector<SDOperand> InOps;
3647 std::swap(InOps, Ops);
3649 Ops.push_back(InOps[0]); // input chain.
3650 Ops.push_back(InOps[1]); // input asm string.
3652 unsigned i = 2, e = InOps.size();
3653 if (InOps[e-1].getValueType() == MVT::Flag)
3654 --e; // Don't process a flag operand if it is here.
3657 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3658 if ((Flags & 7) != 4 /*MEM*/) {
3659 // Just skip over this operand, copying the operands verbatim.
3660 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3661 i += (Flags >> 3) + 1;
3663 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3664 // Otherwise, this is a memory operand. Ask the target to select it.
3665 std::vector<SDOperand> SelOps;
3666 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3667 std::cerr << "Could not match memory address. Inline asm failure!\n";
3671 // Add this to the output node.
3672 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3673 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3678 // Add the flag input back if present.
3679 if (e != InOps.size())
3680 Ops.push_back(InOps.back());