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/Analysis/AliasAnalysis.h"
16 #include "llvm/CodeGen/SelectionDAGISel.h"
17 #include "llvm/CodeGen/ScheduleDAG.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/CodeGen/MachineModuleInfo.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/SchedulerRegistry.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/CodeGen/SSARegMap.h"
35 #include "llvm/Target/MRegisterInfo.h"
36 #include "llvm/Target/TargetAsmInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetFrameInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/Compiler.h"
52 ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
55 ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
58 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
62 //===---------------------------------------------------------------------===//
64 /// RegisterScheduler class - Track the registration of instruction schedulers.
66 //===---------------------------------------------------------------------===//
67 MachinePassRegistry RegisterScheduler::Registry;
69 //===---------------------------------------------------------------------===//
71 /// ISHeuristic command line option for instruction schedulers.
73 //===---------------------------------------------------------------------===//
75 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
78 cl::init(&createDefaultScheduler),
79 cl::desc("Instruction schedulers available:"));
81 static RegisterScheduler
82 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
91 struct VISIBILITY_HIDDEN RegsForValue {
92 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
95 std::vector<unsigned> Regs;
97 /// RegVT - The value type of each register.
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
111 RegsForValue(const std::vector<unsigned> ®s,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
120 SDOperand &Chain, SDOperand &Flag) const;
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
133 std::vector<SDOperand> &Ops) const;
138 //===--------------------------------------------------------------------===//
139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
156 //===--------------------------------------------------------------------===//
157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
159 class FunctionLoweringInfo {
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
174 std::map<const Value*, unsigned> ValueMap;
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
191 unsigned CreateRegForValue(const Value *V);
193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
201 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
202 /// PHI nodes or outside of the basic block that defines it, or used by a
203 /// switch instruction, which may expand to multiple basic blocks.
204 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
209 // FIXME: Remove switchinst special case.
210 isa<SwitchInst>(*UI))
215 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
216 /// entry block, return true. This includes arguments used by switches, since
217 /// the switch may expand into multiple basic blocks.
218 static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
222 return false; // Use not in entry block.
226 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
227 Function &fn, MachineFunction &mf)
228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
240 Function::iterator BB = Fn.begin(), EB = Fn.end();
241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
244 const Type *Ty = AI->getAllocatedType();
245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
247 std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
250 TySize *= CUI->getZExtValue(); // Get total allocated size.
251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
252 StaticAllocaMap[AI] =
253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
258 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259 if (!isa<AllocaInst>(I) ||
260 !StaticAllocaMap.count(cast<AllocaInst>(I)))
261 InitializeRegForValue(I);
263 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
264 // also creates the initial PHI MachineInstrs, though none of the input
265 // operands are populated.
266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
267 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
269 MF.getBasicBlockList().push_back(MBB);
271 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
274 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275 if (PN->use_empty()) continue;
277 MVT::ValueType VT = TLI.getValueType(PN->getType());
278 unsigned NumElements;
279 if (VT != MVT::Vector)
280 NumElements = TLI.getNumElements(VT);
282 MVT::ValueType VT1,VT2;
284 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
290 for (unsigned i = 0; i != NumElements; ++i)
291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
296 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
297 /// the correctly promoted or expanded types. Assign these registers
298 /// consecutive vreg numbers and return the first assigned number.
299 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300 MVT::ValueType VT = TLI.getValueType(V->getType());
302 // The number of multiples of registers that we need, to, e.g., split up
303 // a <2 x int64> -> 4 x i32 registers.
304 unsigned NumVectorRegs = 1;
306 // If this is a packed type, figure out what type it will decompose into
307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
309 const PackedType *PTy = cast<PackedType>(V->getType());
310 unsigned NumElts = PTy->getNumElements();
311 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
315 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
322 VT = getVectorType(EltTy, NumElts);
325 // The common case is that we will only create one register for this
326 // value. If we have that case, create and return the virtual register.
327 unsigned NV = TLI.getNumElements(VT);
329 // If we are promoting this value, pick the next largest supported type.
330 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331 unsigned Reg = MakeReg(PromotedType);
332 // If this is a vector of supported or promoted types (e.g. 4 x i16),
333 // create all of the registers.
334 for (unsigned i = 1; i != NumVectorRegs; ++i)
335 MakeReg(PromotedType);
339 // If this value is represented with multiple target registers, make sure
340 // to create enough consecutive registers of the right (smaller) type.
341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
348 //===----------------------------------------------------------------------===//
349 /// SelectionDAGLowering - This is the common target-independent lowering
350 /// implementation that is parameterized by a TargetLowering object.
351 /// Also, targets can overload any lowering method.
354 class SelectionDAGLowering {
355 MachineBasicBlock *CurMBB;
357 std::map<const Value*, SDOperand> NodeMap;
359 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
360 /// them up and then emit token factor nodes when possible. This allows us to
361 /// get simple disambiguation between loads without worrying about alias
363 std::vector<SDOperand> PendingLoads;
365 /// Case - A pair of values to record the Value for a switch case, and the
366 /// case's target basic block.
367 typedef std::pair<Constant*, MachineBasicBlock*> Case;
368 typedef std::vector<Case>::iterator CaseItr;
369 typedef std::pair<CaseItr, CaseItr> CaseRange;
371 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372 /// of conditional branches.
374 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
377 /// CaseBB - The MBB in which to emit the compare and branch
378 MachineBasicBlock *CaseBB;
379 /// LT, GE - If nonzero, we know the current case value must be less-than or
380 /// greater-than-or-equal-to these Constants.
383 /// Range - A pair of iterators representing the range of case values to be
384 /// processed at this point in the binary search tree.
388 /// The comparison function for sorting Case values.
390 bool operator () (const Case& C1, const Case& C2) {
391 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
392 return cast<const ConstantInt>(C1.first)->getSExtValue() <
393 cast<const ConstantInt>(C2.first)->getSExtValue();
398 // TLI - This is information that describes the available target features we
399 // need for lowering. This indicates when operations are unavailable,
400 // implemented with a libcall, etc.
403 const TargetData *TD;
405 /// SwitchCases - Vector of CaseBlock structures used to communicate
406 /// SwitchInst code generation information.
407 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
408 SelectionDAGISel::JumpTable JT;
410 /// FuncInfo - Information about the function as a whole.
412 FunctionLoweringInfo &FuncInfo;
414 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
415 FunctionLoweringInfo &funcinfo)
416 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
417 JT(0,0,0,0), FuncInfo(funcinfo) {
420 /// getRoot - Return the current virtual root of the Selection DAG.
422 SDOperand getRoot() {
423 if (PendingLoads.empty())
424 return DAG.getRoot();
426 if (PendingLoads.size() == 1) {
427 SDOperand Root = PendingLoads[0];
429 PendingLoads.clear();
433 // Otherwise, we have to make a token factor node.
434 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435 &PendingLoads[0], PendingLoads.size());
436 PendingLoads.clear();
441 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
443 void visit(Instruction &I) { visit(I.getOpcode(), I); }
445 void visit(unsigned Opcode, User &I) {
446 // Note: this doesn't use InstVisitor, because it has to work with
447 // ConstantExpr's in addition to instructions.
449 default: assert(0 && "Unknown instruction type encountered!");
451 // Build the switch statement using the Instruction.def file.
452 #define HANDLE_INST(NUM, OPCODE, CLASS) \
453 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454 #include "llvm/Instruction.def"
458 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
460 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
461 const Value *SV, SDOperand Root,
464 SDOperand getIntPtrConstant(uint64_t Val) {
465 return DAG.getConstant(Val, TLI.getPointerTy());
468 SDOperand getValue(const Value *V);
470 const SDOperand &setValue(const Value *V, SDOperand NewN) {
471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
476 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
478 bool OutReg, bool InReg,
479 std::set<unsigned> &OutputRegs,
480 std::set<unsigned> &InputRegs);
482 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
485 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
486 void ExportFromCurrentBlock(Value *V);
488 // Terminator instructions.
489 void visitRet(ReturnInst &I);
490 void visitBr(BranchInst &I);
491 void visitSwitch(SwitchInst &I);
492 void visitUnreachable(UnreachableInst &I) { /* noop */ }
494 // Helper for visitSwitch
495 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
496 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
498 // These all get lowered before this pass.
499 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
500 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
502 void visitScalarBinary(User &I, unsigned OpCode);
503 void visitVectorBinary(User &I, unsigned OpCode);
504 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
505 void visitShift(User &I, unsigned Opcode);
506 void visitAdd(User &I) {
507 if (isa<PackedType>(I.getType()))
508 visitVectorBinary(I, ISD::VADD);
509 else if (I.getType()->isFloatingPoint())
510 visitScalarBinary(I, ISD::FADD);
512 visitScalarBinary(I, ISD::ADD);
514 void visitSub(User &I);
515 void visitMul(User &I) {
516 if (isa<PackedType>(I.getType()))
517 visitVectorBinary(I, ISD::VMUL);
518 else if (I.getType()->isFloatingPoint())
519 visitScalarBinary(I, ISD::FMUL);
521 visitScalarBinary(I, ISD::MUL);
523 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
524 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
525 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
526 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
527 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
528 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
529 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
530 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
531 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
532 void visitShl (User &I) { visitShift(I, ISD::SHL); }
533 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
534 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
535 void visitICmp(User &I);
536 void visitFCmp(User &I);
537 // Visit the conversion instructions
538 void visitTrunc(User &I);
539 void visitZExt(User &I);
540 void visitSExt(User &I);
541 void visitFPTrunc(User &I);
542 void visitFPExt(User &I);
543 void visitFPToUI(User &I);
544 void visitFPToSI(User &I);
545 void visitUIToFP(User &I);
546 void visitSIToFP(User &I);
547 void visitPtrToInt(User &I);
548 void visitIntToPtr(User &I);
549 void visitBitCast(User &I);
551 void visitExtractElement(User &I);
552 void visitInsertElement(User &I);
553 void visitShuffleVector(User &I);
555 void visitGetElementPtr(User &I);
556 void visitSelect(User &I);
558 void visitMalloc(MallocInst &I);
559 void visitFree(FreeInst &I);
560 void visitAlloca(AllocaInst &I);
561 void visitLoad(LoadInst &I);
562 void visitStore(StoreInst &I);
563 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
564 void visitCall(CallInst &I);
565 void visitInlineAsm(CallInst &I);
566 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
567 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
569 void visitVAStart(CallInst &I);
570 void visitVAArg(VAArgInst &I);
571 void visitVAEnd(CallInst &I);
572 void visitVACopy(CallInst &I);
574 void visitMemIntrinsic(CallInst &I, unsigned Op);
576 void visitUserOp1(Instruction &I) {
577 assert(0 && "UserOp1 should not exist at instruction selection time!");
580 void visitUserOp2(Instruction &I) {
581 assert(0 && "UserOp2 should not exist at instruction selection time!");
585 } // end namespace llvm
587 SDOperand SelectionDAGLowering::getValue(const Value *V) {
588 SDOperand &N = NodeMap[V];
591 const Type *VTy = V->getType();
592 MVT::ValueType VT = TLI.getValueType(VTy);
593 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
594 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
595 visit(CE->getOpcode(), *CE);
596 assert(N.Val && "visit didn't populate the ValueMap!");
598 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
599 return N = DAG.getGlobalAddress(GV, VT);
600 } else if (isa<ConstantPointerNull>(C)) {
601 return N = DAG.getConstant(0, TLI.getPointerTy());
602 } else if (isa<UndefValue>(C)) {
603 if (!isa<PackedType>(VTy))
604 return N = DAG.getNode(ISD::UNDEF, VT);
606 // Create a VBUILD_VECTOR of undef nodes.
607 const PackedType *PTy = cast<PackedType>(VTy);
608 unsigned NumElements = PTy->getNumElements();
609 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
611 SmallVector<SDOperand, 8> Ops;
612 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
614 // Create a VConstant node with generic Vector type.
615 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
616 Ops.push_back(DAG.getValueType(PVT));
617 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
618 &Ops[0], Ops.size());
619 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
620 return N = DAG.getConstantFP(CFP->getValue(), VT);
621 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
622 unsigned NumElements = PTy->getNumElements();
623 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
625 // Now that we know the number and type of the elements, push a
626 // Constant or ConstantFP node onto the ops list for each element of
627 // the packed constant.
628 SmallVector<SDOperand, 8> Ops;
629 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
630 for (unsigned i = 0; i != NumElements; ++i)
631 Ops.push_back(getValue(CP->getOperand(i)));
633 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
635 if (MVT::isFloatingPoint(PVT))
636 Op = DAG.getConstantFP(0, PVT);
638 Op = DAG.getConstant(0, PVT);
639 Ops.assign(NumElements, Op);
642 // Create a VBUILD_VECTOR node with generic Vector type.
643 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
644 Ops.push_back(DAG.getValueType(PVT));
645 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
647 // Canonicalize all constant ints to be unsigned.
648 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
652 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
653 std::map<const AllocaInst*, int>::iterator SI =
654 FuncInfo.StaticAllocaMap.find(AI);
655 if (SI != FuncInfo.StaticAllocaMap.end())
656 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
659 std::map<const Value*, unsigned>::const_iterator VMI =
660 FuncInfo.ValueMap.find(V);
661 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
663 unsigned InReg = VMI->second;
665 // If this type is not legal, make it so now.
666 if (VT != MVT::Vector) {
667 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
668 // Source must be expanded. This input value is actually coming from the
669 // register pair VMI->second and VMI->second+1.
670 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
671 unsigned NumVals = TLI.getNumElements(VT);
672 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
674 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
676 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
677 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
678 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
681 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
682 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
683 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
684 N = MVT::isFloatingPoint(VT)
685 ? DAG.getNode(ISD::FP_ROUND, VT, N)
686 : DAG.getNode(ISD::TRUNCATE, VT, N);
689 // Otherwise, if this is a vector, make it available as a generic vector
691 MVT::ValueType PTyElementVT, PTyLegalElementVT;
692 const PackedType *PTy = cast<PackedType>(VTy);
693 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
696 // Build a VBUILD_VECTOR with the input registers.
697 SmallVector<SDOperand, 8> Ops;
698 if (PTyElementVT == PTyLegalElementVT) {
699 // If the value types are legal, just VBUILD the CopyFromReg nodes.
700 for (unsigned i = 0; i != NE; ++i)
701 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
703 } else if (PTyElementVT < PTyLegalElementVT) {
704 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
705 for (unsigned i = 0; i != NE; ++i) {
706 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
708 if (MVT::isFloatingPoint(PTyElementVT))
709 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
711 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
715 // If the register was expanded, use BUILD_PAIR.
716 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
717 for (unsigned i = 0; i != NE/2; ++i) {
718 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
720 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
722 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
726 Ops.push_back(DAG.getConstant(NE, MVT::i32));
727 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
728 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
730 // Finally, use a VBIT_CONVERT to make this available as the appropriate
732 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
733 DAG.getConstant(PTy->getNumElements(),
735 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
742 void SelectionDAGLowering::visitRet(ReturnInst &I) {
743 if (I.getNumOperands() == 0) {
744 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
747 SmallVector<SDOperand, 8> NewValues;
748 NewValues.push_back(getRoot());
749 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
750 SDOperand RetOp = getValue(I.getOperand(i));
752 // If this is an integer return value, we need to promote it ourselves to
753 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
755 // FIXME: C calling convention requires the return type to be promoted to
756 // at least 32-bit. But this is not necessary for non-C calling conventions.
757 if (MVT::isInteger(RetOp.getValueType()) &&
758 RetOp.getValueType() < MVT::i64) {
759 MVT::ValueType TmpVT;
760 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
761 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
764 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
765 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
766 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
767 ExtendKind = ISD::SIGN_EXTEND;
768 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
769 ExtendKind = ISD::ZERO_EXTEND;
770 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
772 NewValues.push_back(RetOp);
773 NewValues.push_back(DAG.getConstant(false, MVT::i32));
775 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
776 &NewValues[0], NewValues.size()));
779 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
780 /// the current basic block, add it to ValueMap now so that we'll get a
782 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
783 // No need to export constants.
784 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
787 if (FuncInfo.isExportedInst(V)) return;
789 unsigned Reg = FuncInfo.InitializeRegForValue(V);
790 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
793 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
794 const BasicBlock *FromBB) {
795 // The operands of the setcc have to be in this block. We don't know
796 // how to export them from some other block.
797 if (Instruction *VI = dyn_cast<Instruction>(V)) {
798 // Can export from current BB.
799 if (VI->getParent() == FromBB)
802 // Is already exported, noop.
803 return FuncInfo.isExportedInst(V);
806 // If this is an argument, we can export it if the BB is the entry block or
807 // if it is already exported.
808 if (isa<Argument>(V)) {
809 if (FromBB == &FromBB->getParent()->getEntryBlock())
812 // Otherwise, can only export this if it is already exported.
813 return FuncInfo.isExportedInst(V);
816 // Otherwise, constants can always be exported.
820 static bool InBlock(const Value *V, const BasicBlock *BB) {
821 if (const Instruction *I = dyn_cast<Instruction>(V))
822 return I->getParent() == BB;
826 /// FindMergedConditions - If Cond is an expression like
827 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
828 MachineBasicBlock *TBB,
829 MachineBasicBlock *FBB,
830 MachineBasicBlock *CurBB,
832 // If this node is not part of the or/and tree, emit it as a branch.
833 Instruction *BOp = dyn_cast<Instruction>(Cond);
835 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
836 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
837 BOp->getParent() != CurBB->getBasicBlock() ||
838 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
839 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
840 const BasicBlock *BB = CurBB->getBasicBlock();
842 // If the leaf of the tree is a comparison, merge the condition into
844 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
845 // The operands of the cmp have to be in this block. We don't know
846 // how to export them from some other block. If this is the first block
847 // of the sequence, no exporting is needed.
849 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
850 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
851 BOp = cast<Instruction>(Cond);
852 ISD::CondCode Condition;
853 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
854 switch (IC->getPredicate()) {
855 default: assert(0 && "Unknown icmp predicate opcode!");
856 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
857 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
858 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
859 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
860 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
861 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
862 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
863 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
864 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
865 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
867 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
868 ISD::CondCode FPC, FOC;
869 switch (FC->getPredicate()) {
870 default: assert(0 && "Unknown fcmp predicate opcode!");
871 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
872 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
873 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
874 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
875 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
876 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
877 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
878 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
879 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
880 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
881 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
882 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
883 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
884 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
885 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
886 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
888 if (FiniteOnlyFPMath())
893 assert(0 && "Unknown compare instruction");
896 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
897 BOp->getOperand(1), TBB, FBB, CurBB);
898 SwitchCases.push_back(CB);
902 // Create a CaseBlock record representing this branch.
903 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
905 SwitchCases.push_back(CB);
910 // Create TmpBB after CurBB.
911 MachineFunction::iterator BBI = CurBB;
912 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
913 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
915 if (Opc == Instruction::Or) {
924 // Emit the LHS condition.
925 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
927 // Emit the RHS condition into TmpBB.
928 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
930 assert(Opc == Instruction::And && "Unknown merge op!");
938 // This requires creation of TmpBB after CurBB.
940 // Emit the LHS condition.
941 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
943 // Emit the RHS condition into TmpBB.
944 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
948 /// If the set of cases should be emitted as a series of branches, return true.
949 /// If we should emit this as a bunch of and/or'd together conditions, return
952 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
953 if (Cases.size() != 2) return true;
955 // If this is two comparisons of the same values or'd or and'd together, they
956 // will get folded into a single comparison, so don't emit two blocks.
957 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
958 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
959 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
960 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
967 void SelectionDAGLowering::visitBr(BranchInst &I) {
968 // Update machine-CFG edges.
969 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
971 // Figure out which block is immediately after the current one.
972 MachineBasicBlock *NextBlock = 0;
973 MachineFunction::iterator BBI = CurMBB;
974 if (++BBI != CurMBB->getParent()->end())
977 if (I.isUnconditional()) {
978 // If this is not a fall-through branch, emit the branch.
979 if (Succ0MBB != NextBlock)
980 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
981 DAG.getBasicBlock(Succ0MBB)));
983 // Update machine-CFG edges.
984 CurMBB->addSuccessor(Succ0MBB);
989 // If this condition is one of the special cases we handle, do special stuff
991 Value *CondVal = I.getCondition();
992 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
994 // If this is a series of conditions that are or'd or and'd together, emit
995 // this as a sequence of branches instead of setcc's with and/or operations.
996 // For example, instead of something like:
1009 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1010 if (BOp->hasOneUse() &&
1011 (BOp->getOpcode() == Instruction::And ||
1012 BOp->getOpcode() == Instruction::Or)) {
1013 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1014 // If the compares in later blocks need to use values not currently
1015 // exported from this block, export them now. This block should always
1016 // be the first entry.
1017 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1019 // Allow some cases to be rejected.
1020 if (ShouldEmitAsBranches(SwitchCases)) {
1021 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1022 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1023 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1026 // Emit the branch for this block.
1027 visitSwitchCase(SwitchCases[0]);
1028 SwitchCases.erase(SwitchCases.begin());
1032 // Okay, we decided not to do this, remove any inserted MBB's and clear
1034 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1035 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1037 SwitchCases.clear();
1041 // Create a CaseBlock record representing this branch.
1042 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1043 Succ0MBB, Succ1MBB, CurMBB);
1044 // Use visitSwitchCase to actually insert the fast branch sequence for this
1046 visitSwitchCase(CB);
1049 /// visitSwitchCase - Emits the necessary code to represent a single node in
1050 /// the binary search tree resulting from lowering a switch instruction.
1051 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1053 SDOperand CondLHS = getValue(CB.CmpLHS);
1055 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1056 // handle common cases produced by branch lowering.
1057 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1059 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1060 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1061 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1063 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1065 // Set NextBlock to be the MBB immediately after the current one, if any.
1066 // This is used to avoid emitting unnecessary branches to the next block.
1067 MachineBasicBlock *NextBlock = 0;
1068 MachineFunction::iterator BBI = CurMBB;
1069 if (++BBI != CurMBB->getParent()->end())
1072 // If the lhs block is the next block, invert the condition so that we can
1073 // fall through to the lhs instead of the rhs block.
1074 if (CB.TrueBB == NextBlock) {
1075 std::swap(CB.TrueBB, CB.FalseBB);
1076 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1077 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1079 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1080 DAG.getBasicBlock(CB.TrueBB));
1081 if (CB.FalseBB == NextBlock)
1082 DAG.setRoot(BrCond);
1084 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1085 DAG.getBasicBlock(CB.FalseBB)));
1086 // Update successor info
1087 CurMBB->addSuccessor(CB.TrueBB);
1088 CurMBB->addSuccessor(CB.FalseBB);
1091 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1092 // Emit the code for the jump table
1093 MVT::ValueType PTy = TLI.getPointerTy();
1094 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1095 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1096 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1101 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1102 // Figure out which block is immediately after the current one.
1103 MachineBasicBlock *NextBlock = 0;
1104 MachineFunction::iterator BBI = CurMBB;
1106 if (++BBI != CurMBB->getParent()->end())
1109 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1111 // If there is only the default destination, branch to it if it is not the
1112 // next basic block. Otherwise, just fall through.
1113 if (I.getNumOperands() == 2) {
1114 // Update machine-CFG edges.
1116 // If this is not a fall-through branch, emit the branch.
1117 if (Default != NextBlock)
1118 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1119 DAG.getBasicBlock(Default)));
1121 CurMBB->addSuccessor(Default);
1125 // If there are any non-default case statements, create a vector of Cases
1126 // representing each one, and sort the vector so that we can efficiently
1127 // create a binary search tree from them.
1128 std::vector<Case> Cases;
1130 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1131 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1132 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1135 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1137 // Get the Value to be switched on and default basic blocks, which will be
1138 // inserted into CaseBlock records, representing basic blocks in the binary
1140 Value *SV = I.getOperand(0);
1142 // Get the MachineFunction which holds the current MBB. This is used during
1143 // emission of jump tables, and when inserting any additional MBBs necessary
1144 // to represent the switch.
1145 MachineFunction *CurMF = CurMBB->getParent();
1146 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
1148 // If the switch has few cases (two or less) emit a series of specific
1150 if (Cases.size() < 3) {
1151 // TODO: If any two of the cases has the same destination, and if one value
1152 // is the same as the other, but has one bit unset that the other has set,
1153 // use bit manipulation to do two compares at once. For example:
1154 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1156 // Rearrange the case blocks so that the last one falls through if possible.
1157 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1158 // The last case block won't fall through into 'NextBlock' if we emit the
1159 // branches in this order. See if rearranging a case value would help.
1160 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1161 if (Cases[i].second == NextBlock) {
1162 std::swap(Cases[i], Cases.back());
1168 // Create a CaseBlock record representing a conditional branch to
1169 // the Case's target mbb if the value being switched on SV is equal
1171 MachineBasicBlock *CurBlock = CurMBB;
1172 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1173 MachineBasicBlock *FallThrough;
1175 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1176 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1178 // If the last case doesn't match, go to the default block.
1179 FallThrough = Default;
1182 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1183 Cases[i].second, FallThrough, CurBlock);
1185 // If emitting the first comparison, just call visitSwitchCase to emit the
1186 // code into the current block. Otherwise, push the CaseBlock onto the
1187 // vector to be later processed by SDISel, and insert the node's MBB
1188 // before the next MBB.
1189 if (CurBlock == CurMBB)
1190 visitSwitchCase(CB);
1192 SwitchCases.push_back(CB);
1194 CurBlock = FallThrough;
1199 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1200 // target supports indirect branches, then emit a jump table rather than
1201 // lowering the switch to a binary tree of conditional branches.
1202 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1203 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
1205 uint64_t First =cast<ConstantInt>(Cases.front().first)->getZExtValue();
1206 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getZExtValue();
1207 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1209 if (Density >= 0.3125) {
1210 // Create a new basic block to hold the code for loading the address
1211 // of the jump table, and jumping to it. Update successor information;
1212 // we will either branch to the default case for the switch, or the jump
1214 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1215 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1216 CurMBB->addSuccessor(Default);
1217 CurMBB->addSuccessor(JumpTableBB);
1219 // Subtract the lowest switch case value from the value being switched on
1220 // and conditional branch to default mbb if the result is greater than the
1221 // difference between smallest and largest cases.
1222 SDOperand SwitchOp = getValue(SV);
1223 MVT::ValueType VT = SwitchOp.getValueType();
1224 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1225 DAG.getConstant(First, VT));
1227 // The SDNode we just created, which holds the value being switched on
1228 // minus the the smallest case value, needs to be copied to a virtual
1229 // register so it can be used as an index into the jump table in a
1230 // subsequent basic block. This value may be smaller or larger than the
1231 // target's pointer type, and therefore require extension or truncating.
1232 if (VT > TLI.getPointerTy())
1233 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1235 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1237 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1238 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1240 // Emit the range check for the jump table, and branch to the default
1241 // block for the switch statement if the value being switched on exceeds
1242 // the largest case in the switch.
1243 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1244 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1245 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1246 DAG.getBasicBlock(Default)));
1248 // Build a vector of destination BBs, corresponding to each target
1249 // of the jump table. If the value of the jump table slot corresponds to
1250 // a case statement, push the case's BB onto the vector, otherwise, push
1252 std::vector<MachineBasicBlock*> DestBBs;
1253 uint64_t TEI = First;
1254 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
1255 if (cast<ConstantInt>(ii->first)->getZExtValue() == TEI) {
1256 DestBBs.push_back(ii->second);
1259 DestBBs.push_back(Default);
1262 // Update successor info. Add one edge to each unique successor.
1263 // Vector bool would be better, but vector<bool> is really slow.
1264 std::vector<unsigned char> SuccsHandled;
1265 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1267 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1268 E = DestBBs.end(); I != E; ++I) {
1269 if (!SuccsHandled[(*I)->getNumber()]) {
1270 SuccsHandled[(*I)->getNumber()] = true;
1271 JumpTableBB->addSuccessor(*I);
1275 // Create a jump table index for this jump table, or return an existing
1277 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1279 // Set the jump table information so that we can codegen it as a second
1280 // MachineBasicBlock
1281 JT.Reg = JumpTableReg;
1283 JT.MBB = JumpTableBB;
1284 JT.Default = Default;
1289 // Push the initial CaseRec onto the worklist
1290 std::vector<CaseRec> CaseVec;
1291 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1293 while (!CaseVec.empty()) {
1294 // Grab a record representing a case range to process off the worklist
1295 CaseRec CR = CaseVec.back();
1298 // Size is the number of Cases represented by this range. If Size is 1,
1299 // then we are processing a leaf of the binary search tree. Otherwise,
1300 // we need to pick a pivot, and push left and right ranges onto the
1302 unsigned Size = CR.Range.second - CR.Range.first;
1305 // Create a CaseBlock record representing a conditional branch to
1306 // the Case's target mbb if the value being switched on SV is equal
1307 // to C. Otherwise, branch to default.
1308 Constant *C = CR.Range.first->first;
1309 MachineBasicBlock *Target = CR.Range.first->second;
1310 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1313 // If the MBB representing the leaf node is the current MBB, then just
1314 // call visitSwitchCase to emit the code into the current block.
1315 // Otherwise, push the CaseBlock onto the vector to be later processed
1316 // by SDISel, and insert the node's MBB before the next MBB.
1317 if (CR.CaseBB == CurMBB)
1318 visitSwitchCase(CB);
1320 SwitchCases.push_back(CB);
1322 // split case range at pivot
1323 CaseItr Pivot = CR.Range.first + (Size / 2);
1324 CaseRange LHSR(CR.Range.first, Pivot);
1325 CaseRange RHSR(Pivot, CR.Range.second);
1326 Constant *C = Pivot->first;
1327 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1329 // We know that we branch to the LHS if the Value being switched on is
1330 // less than the Pivot value, C. We use this to optimize our binary
1331 // tree a bit, by recognizing that if SV is greater than or equal to the
1332 // LHS's Case Value, and that Case Value is exactly one less than the
1333 // Pivot's Value, then we can branch directly to the LHS's Target,
1334 // rather than creating a leaf node for it.
1335 if ((LHSR.second - LHSR.first) == 1 &&
1336 LHSR.first->first == CR.GE &&
1337 cast<ConstantInt>(C)->getZExtValue() ==
1338 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
1339 TrueBB = LHSR.first->second;
1341 TrueBB = new MachineBasicBlock(LLVMBB);
1342 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1343 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1346 // Similar to the optimization above, if the Value being switched on is
1347 // known to be less than the Constant CR.LT, and the current Case Value
1348 // is CR.LT - 1, then we can branch directly to the target block for
1349 // the current Case Value, rather than emitting a RHS leaf node for it.
1350 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1351 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1352 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
1353 FalseBB = RHSR.first->second;
1355 FalseBB = new MachineBasicBlock(LLVMBB);
1356 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1357 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1360 // Create a CaseBlock record representing a conditional branch to
1361 // the LHS node if the value being switched on SV is less than C.
1362 // Otherwise, branch to LHS.
1363 ISD::CondCode CC = ISD::SETLT;
1364 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
1366 if (CR.CaseBB == CurMBB)
1367 visitSwitchCase(CB);
1369 SwitchCases.push_back(CB);
1374 void SelectionDAGLowering::visitSub(User &I) {
1375 // -0.0 - X --> fneg
1376 const Type *Ty = I.getType();
1377 if (isa<PackedType>(Ty)) {
1378 visitVectorBinary(I, ISD::VSUB);
1379 } else if (Ty->isFloatingPoint()) {
1380 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1381 if (CFP->isExactlyValue(-0.0)) {
1382 SDOperand Op2 = getValue(I.getOperand(1));
1383 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1386 visitScalarBinary(I, ISD::FSUB);
1388 visitScalarBinary(I, ISD::SUB);
1391 void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
1392 SDOperand Op1 = getValue(I.getOperand(0));
1393 SDOperand Op2 = getValue(I.getOperand(1));
1395 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
1399 SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
1400 assert(isa<PackedType>(I.getType()));
1401 const PackedType *Ty = cast<PackedType>(I.getType());
1402 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
1404 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1405 getValue(I.getOperand(0)),
1406 getValue(I.getOperand(1)),
1407 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1411 void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1412 unsigned VectorOp) {
1413 if (isa<PackedType>(I.getType()))
1414 visitVectorBinary(I, VectorOp);
1416 visitScalarBinary(I, ScalarOp);
1419 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1420 SDOperand Op1 = getValue(I.getOperand(0));
1421 SDOperand Op2 = getValue(I.getOperand(1));
1423 if (TLI.getShiftAmountTy() < Op2.getValueType())
1424 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1425 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1426 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1428 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1431 void SelectionDAGLowering::visitICmp(User &I) {
1432 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1433 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1434 predicate = IC->getPredicate();
1435 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1436 predicate = ICmpInst::Predicate(IC->getPredicate());
1437 SDOperand Op1 = getValue(I.getOperand(0));
1438 SDOperand Op2 = getValue(I.getOperand(1));
1439 ISD::CondCode Opcode;
1440 switch (predicate) {
1441 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1442 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1443 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1444 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1445 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1446 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1447 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1448 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1449 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1450 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1452 assert(!"Invalid ICmp predicate value");
1453 Opcode = ISD::SETEQ;
1456 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1459 void SelectionDAGLowering::visitFCmp(User &I) {
1460 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1461 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1462 predicate = FC->getPredicate();
1463 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1464 predicate = FCmpInst::Predicate(FC->getPredicate());
1465 SDOperand Op1 = getValue(I.getOperand(0));
1466 SDOperand Op2 = getValue(I.getOperand(1));
1467 ISD::CondCode Condition, FOC, FPC;
1468 switch (predicate) {
1469 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1470 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1471 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1472 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1473 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1474 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1475 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1476 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1477 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1478 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1479 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1480 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1481 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1482 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1483 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1484 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1486 assert(!"Invalid FCmp predicate value");
1487 FOC = FPC = ISD::SETFALSE;
1490 if (FiniteOnlyFPMath())
1494 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
1497 void SelectionDAGLowering::visitSelect(User &I) {
1498 SDOperand Cond = getValue(I.getOperand(0));
1499 SDOperand TrueVal = getValue(I.getOperand(1));
1500 SDOperand FalseVal = getValue(I.getOperand(2));
1501 if (!isa<PackedType>(I.getType())) {
1502 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1503 TrueVal, FalseVal));
1505 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1506 *(TrueVal.Val->op_end()-2),
1507 *(TrueVal.Val->op_end()-1)));
1512 void SelectionDAGLowering::visitTrunc(User &I) {
1513 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1514 SDOperand N = getValue(I.getOperand(0));
1515 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1516 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1519 void SelectionDAGLowering::visitZExt(User &I) {
1520 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1521 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1522 SDOperand N = getValue(I.getOperand(0));
1523 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1524 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1527 void SelectionDAGLowering::visitSExt(User &I) {
1528 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1529 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1530 SDOperand N = getValue(I.getOperand(0));
1531 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1532 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1535 void SelectionDAGLowering::visitFPTrunc(User &I) {
1536 // FPTrunc is never a no-op cast, no need to check
1537 SDOperand N = getValue(I.getOperand(0));
1538 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1539 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1542 void SelectionDAGLowering::visitFPExt(User &I){
1543 // FPTrunc is never a no-op cast, no need to check
1544 SDOperand N = getValue(I.getOperand(0));
1545 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1546 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1549 void SelectionDAGLowering::visitFPToUI(User &I) {
1550 // FPToUI is never a no-op cast, no need to check
1551 SDOperand N = getValue(I.getOperand(0));
1552 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1553 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1556 void SelectionDAGLowering::visitFPToSI(User &I) {
1557 // FPToSI is never a no-op cast, no need to check
1558 SDOperand N = getValue(I.getOperand(0));
1559 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1560 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1563 void SelectionDAGLowering::visitUIToFP(User &I) {
1564 // UIToFP is never a no-op cast, no need to check
1565 SDOperand N = getValue(I.getOperand(0));
1566 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1567 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1570 void SelectionDAGLowering::visitSIToFP(User &I){
1571 // UIToFP is never a no-op cast, no need to check
1572 SDOperand N = getValue(I.getOperand(0));
1573 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1574 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1577 void SelectionDAGLowering::visitPtrToInt(User &I) {
1578 // What to do depends on the size of the integer and the size of the pointer.
1579 // We can either truncate, zero extend, or no-op, accordingly.
1580 SDOperand N = getValue(I.getOperand(0));
1581 MVT::ValueType SrcVT = N.getValueType();
1582 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1584 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1585 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1587 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1588 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1589 setValue(&I, Result);
1592 void SelectionDAGLowering::visitIntToPtr(User &I) {
1593 // What to do depends on the size of the integer and the size of the pointer.
1594 // We can either truncate, zero extend, or no-op, accordingly.
1595 SDOperand N = getValue(I.getOperand(0));
1596 MVT::ValueType SrcVT = N.getValueType();
1597 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1598 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1599 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1601 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1602 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1605 void SelectionDAGLowering::visitBitCast(User &I) {
1606 SDOperand N = getValue(I.getOperand(0));
1607 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1608 if (DestVT == MVT::Vector) {
1609 // This is a cast to a vector from something else.
1610 // Get information about the output vector.
1611 const PackedType *DestTy = cast<PackedType>(I.getType());
1612 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1613 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1614 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1615 DAG.getValueType(EltVT)));
1618 MVT::ValueType SrcVT = N.getValueType();
1619 if (SrcVT == MVT::Vector) {
1620 // This is a cast from a vctor to something else.
1621 // Get information about the input vector.
1622 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1626 // BitCast assures us that source and destination are the same size so this
1627 // is either a BIT_CONVERT or a no-op.
1628 if (DestVT != N.getValueType())
1629 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1631 setValue(&I, N); // noop cast.
1634 void SelectionDAGLowering::visitInsertElement(User &I) {
1635 SDOperand InVec = getValue(I.getOperand(0));
1636 SDOperand InVal = getValue(I.getOperand(1));
1637 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1638 getValue(I.getOperand(2)));
1640 SDOperand Num = *(InVec.Val->op_end()-2);
1641 SDOperand Typ = *(InVec.Val->op_end()-1);
1642 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1643 InVec, InVal, InIdx, Num, Typ));
1646 void SelectionDAGLowering::visitExtractElement(User &I) {
1647 SDOperand InVec = getValue(I.getOperand(0));
1648 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1649 getValue(I.getOperand(1)));
1650 SDOperand Typ = *(InVec.Val->op_end()-1);
1651 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1652 TLI.getValueType(I.getType()), InVec, InIdx));
1655 void SelectionDAGLowering::visitShuffleVector(User &I) {
1656 SDOperand V1 = getValue(I.getOperand(0));
1657 SDOperand V2 = getValue(I.getOperand(1));
1658 SDOperand Mask = getValue(I.getOperand(2));
1660 SDOperand Num = *(V1.Val->op_end()-2);
1661 SDOperand Typ = *(V2.Val->op_end()-1);
1662 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1663 V1, V2, Mask, Num, Typ));
1667 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1668 SDOperand N = getValue(I.getOperand(0));
1669 const Type *Ty = I.getOperand(0)->getType();
1671 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1674 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1675 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
1678 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1679 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1680 getIntPtrConstant(Offset));
1682 Ty = StTy->getElementType(Field);
1684 Ty = cast<SequentialType>(Ty)->getElementType();
1686 // If this is a constant subscript, handle it quickly.
1687 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1688 if (CI->getZExtValue() == 0) continue;
1690 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
1691 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1695 // N = N + Idx * ElementSize;
1696 uint64_t ElementSize = TD->getTypeSize(Ty);
1697 SDOperand IdxN = getValue(Idx);
1699 // If the index is smaller or larger than intptr_t, truncate or extend
1701 if (IdxN.getValueType() < N.getValueType()) {
1702 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1703 } else if (IdxN.getValueType() > N.getValueType())
1704 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1706 // If this is a multiply by a power of two, turn it into a shl
1707 // immediately. This is a very common case.
1708 if (isPowerOf2_64(ElementSize)) {
1709 unsigned Amt = Log2_64(ElementSize);
1710 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1711 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1712 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1716 SDOperand Scale = getIntPtrConstant(ElementSize);
1717 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1718 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1724 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1725 // If this is a fixed sized alloca in the entry block of the function,
1726 // allocate it statically on the stack.
1727 if (FuncInfo.StaticAllocaMap.count(&I))
1728 return; // getValue will auto-populate this.
1730 const Type *Ty = I.getAllocatedType();
1731 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1733 std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
1736 SDOperand AllocSize = getValue(I.getArraySize());
1737 MVT::ValueType IntPtr = TLI.getPointerTy();
1738 if (IntPtr < AllocSize.getValueType())
1739 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1740 else if (IntPtr > AllocSize.getValueType())
1741 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1743 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1744 getIntPtrConstant(TySize));
1746 // Handle alignment. If the requested alignment is less than or equal to the
1747 // stack alignment, ignore it and round the size of the allocation up to the
1748 // stack alignment size. If the size is greater than the stack alignment, we
1749 // note this in the DYNAMIC_STACKALLOC node.
1750 unsigned StackAlign =
1751 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1752 if (Align <= StackAlign) {
1754 // Add SA-1 to the size.
1755 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1756 getIntPtrConstant(StackAlign-1));
1757 // Mask out the low bits for alignment purposes.
1758 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1759 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1762 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
1763 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1765 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
1766 DAG.setRoot(setValue(&I, DSA).getValue(1));
1768 // Inform the Frame Information that we have just allocated a variable-sized
1770 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1773 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1774 SDOperand Ptr = getValue(I.getOperand(0));
1780 // Do not serialize non-volatile loads against each other.
1781 Root = DAG.getRoot();
1784 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
1785 Root, I.isVolatile()));
1788 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1789 const Value *SV, SDOperand Root,
1792 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1793 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1794 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1795 DAG.getSrcValue(SV));
1797 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
1801 DAG.setRoot(L.getValue(1));
1803 PendingLoads.push_back(L.getValue(1));
1809 void SelectionDAGLowering::visitStore(StoreInst &I) {
1810 Value *SrcV = I.getOperand(0);
1811 SDOperand Src = getValue(SrcV);
1812 SDOperand Ptr = getValue(I.getOperand(1));
1813 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
1817 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1818 /// access memory and has no other side effects at all.
1819 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1820 #define GET_NO_MEMORY_INTRINSICS
1821 #include "llvm/Intrinsics.gen"
1822 #undef GET_NO_MEMORY_INTRINSICS
1826 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1827 // have any side-effects or if it only reads memory.
1828 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1829 #define GET_SIDE_EFFECT_INFO
1830 #include "llvm/Intrinsics.gen"
1831 #undef GET_SIDE_EFFECT_INFO
1835 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1837 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1838 unsigned Intrinsic) {
1839 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1840 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1842 // Build the operand list.
1843 SmallVector<SDOperand, 8> Ops;
1844 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1846 // We don't need to serialize loads against other loads.
1847 Ops.push_back(DAG.getRoot());
1849 Ops.push_back(getRoot());
1853 // Add the intrinsic ID as an integer operand.
1854 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1856 // Add all operands of the call to the operand list.
1857 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1858 SDOperand Op = getValue(I.getOperand(i));
1860 // If this is a vector type, force it to the right packed type.
1861 if (Op.getValueType() == MVT::Vector) {
1862 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1863 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1865 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1866 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1867 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1870 assert(TLI.isTypeLegal(Op.getValueType()) &&
1871 "Intrinsic uses a non-legal type?");
1875 std::vector<MVT::ValueType> VTs;
1876 if (I.getType() != Type::VoidTy) {
1877 MVT::ValueType VT = TLI.getValueType(I.getType());
1878 if (VT == MVT::Vector) {
1879 const PackedType *DestTy = cast<PackedType>(I.getType());
1880 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1882 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1883 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1886 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1890 VTs.push_back(MVT::Other);
1892 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1897 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1898 &Ops[0], Ops.size());
1899 else if (I.getType() != Type::VoidTy)
1900 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1901 &Ops[0], Ops.size());
1903 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1904 &Ops[0], Ops.size());
1907 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1909 PendingLoads.push_back(Chain);
1913 if (I.getType() != Type::VoidTy) {
1914 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1915 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1916 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1917 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1918 DAG.getValueType(EVT));
1920 setValue(&I, Result);
1924 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1925 /// we want to emit this as a call to a named external function, return the name
1926 /// otherwise lower it and return null.
1928 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1929 switch (Intrinsic) {
1931 // By default, turn this into a target intrinsic node.
1932 visitTargetIntrinsic(I, Intrinsic);
1934 case Intrinsic::vastart: visitVAStart(I); return 0;
1935 case Intrinsic::vaend: visitVAEnd(I); return 0;
1936 case Intrinsic::vacopy: visitVACopy(I); return 0;
1937 case Intrinsic::returnaddress:
1938 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
1939 getValue(I.getOperand(1))));
1941 case Intrinsic::frameaddress:
1942 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
1943 getValue(I.getOperand(1))));
1945 case Intrinsic::setjmp:
1946 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
1948 case Intrinsic::longjmp:
1949 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
1951 case Intrinsic::memcpy_i32:
1952 case Intrinsic::memcpy_i64:
1953 visitMemIntrinsic(I, ISD::MEMCPY);
1955 case Intrinsic::memset_i32:
1956 case Intrinsic::memset_i64:
1957 visitMemIntrinsic(I, ISD::MEMSET);
1959 case Intrinsic::memmove_i32:
1960 case Intrinsic::memmove_i64:
1961 visitMemIntrinsic(I, ISD::MEMMOVE);
1964 case Intrinsic::dbg_stoppoint: {
1965 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1966 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1967 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
1971 Ops[1] = getValue(SPI.getLineValue());
1972 Ops[2] = getValue(SPI.getColumnValue());
1974 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
1975 assert(DD && "Not a debug information descriptor");
1976 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1978 Ops[3] = DAG.getString(CompileUnit->getFileName());
1979 Ops[4] = DAG.getString(CompileUnit->getDirectory());
1981 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
1986 case Intrinsic::dbg_region_start: {
1987 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1988 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1989 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
1990 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
1991 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1992 DAG.getConstant(LabelID, MVT::i32)));
1997 case Intrinsic::dbg_region_end: {
1998 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1999 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2000 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2001 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2002 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2003 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2008 case Intrinsic::dbg_func_start: {
2009 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2010 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2011 if (MMI && FSI.getSubprogram() &&
2012 MMI->Verify(FSI.getSubprogram())) {
2013 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
2014 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2015 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2020 case Intrinsic::dbg_declare: {
2021 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2022 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2023 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
2024 SDOperand AddressOp = getValue(DI.getAddress());
2025 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2026 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
2032 case Intrinsic::sqrt_f32:
2033 case Intrinsic::sqrt_f64:
2034 setValue(&I, DAG.getNode(ISD::FSQRT,
2035 getValue(I.getOperand(1)).getValueType(),
2036 getValue(I.getOperand(1))));
2038 case Intrinsic::powi_f32:
2039 case Intrinsic::powi_f64:
2040 setValue(&I, DAG.getNode(ISD::FPOWI,
2041 getValue(I.getOperand(1)).getValueType(),
2042 getValue(I.getOperand(1)),
2043 getValue(I.getOperand(2))));
2045 case Intrinsic::pcmarker: {
2046 SDOperand Tmp = getValue(I.getOperand(1));
2047 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2050 case Intrinsic::readcyclecounter: {
2051 SDOperand Op = getRoot();
2052 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2053 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2056 DAG.setRoot(Tmp.getValue(1));
2059 case Intrinsic::bswap_i16:
2060 case Intrinsic::bswap_i32:
2061 case Intrinsic::bswap_i64:
2062 setValue(&I, DAG.getNode(ISD::BSWAP,
2063 getValue(I.getOperand(1)).getValueType(),
2064 getValue(I.getOperand(1))));
2066 case Intrinsic::cttz_i8:
2067 case Intrinsic::cttz_i16:
2068 case Intrinsic::cttz_i32:
2069 case Intrinsic::cttz_i64:
2070 setValue(&I, DAG.getNode(ISD::CTTZ,
2071 getValue(I.getOperand(1)).getValueType(),
2072 getValue(I.getOperand(1))));
2074 case Intrinsic::ctlz_i8:
2075 case Intrinsic::ctlz_i16:
2076 case Intrinsic::ctlz_i32:
2077 case Intrinsic::ctlz_i64:
2078 setValue(&I, DAG.getNode(ISD::CTLZ,
2079 getValue(I.getOperand(1)).getValueType(),
2080 getValue(I.getOperand(1))));
2082 case Intrinsic::ctpop_i8:
2083 case Intrinsic::ctpop_i16:
2084 case Intrinsic::ctpop_i32:
2085 case Intrinsic::ctpop_i64:
2086 setValue(&I, DAG.getNode(ISD::CTPOP,
2087 getValue(I.getOperand(1)).getValueType(),
2088 getValue(I.getOperand(1))));
2090 case Intrinsic::stacksave: {
2091 SDOperand Op = getRoot();
2092 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2093 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2095 DAG.setRoot(Tmp.getValue(1));
2098 case Intrinsic::stackrestore: {
2099 SDOperand Tmp = getValue(I.getOperand(1));
2100 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2103 case Intrinsic::prefetch:
2104 // FIXME: Currently discarding prefetches.
2110 void SelectionDAGLowering::visitCall(CallInst &I) {
2111 const char *RenameFn = 0;
2112 if (Function *F = I.getCalledFunction()) {
2113 if (F->isDeclaration())
2114 if (unsigned IID = F->getIntrinsicID()) {
2115 RenameFn = visitIntrinsicCall(I, IID);
2118 } else { // Not an LLVM intrinsic.
2119 const std::string &Name = F->getName();
2120 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2121 if (I.getNumOperands() == 3 && // Basic sanity checks.
2122 I.getOperand(1)->getType()->isFloatingPoint() &&
2123 I.getType() == I.getOperand(1)->getType() &&
2124 I.getType() == I.getOperand(2)->getType()) {
2125 SDOperand LHS = getValue(I.getOperand(1));
2126 SDOperand RHS = getValue(I.getOperand(2));
2127 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2131 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2132 if (I.getNumOperands() == 2 && // Basic sanity checks.
2133 I.getOperand(1)->getType()->isFloatingPoint() &&
2134 I.getType() == I.getOperand(1)->getType()) {
2135 SDOperand Tmp = getValue(I.getOperand(1));
2136 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2139 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2140 if (I.getNumOperands() == 2 && // Basic sanity checks.
2141 I.getOperand(1)->getType()->isFloatingPoint() &&
2142 I.getType() == I.getOperand(1)->getType()) {
2143 SDOperand Tmp = getValue(I.getOperand(1));
2144 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2147 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2148 if (I.getNumOperands() == 2 && // Basic sanity checks.
2149 I.getOperand(1)->getType()->isFloatingPoint() &&
2150 I.getType() == I.getOperand(1)->getType()) {
2151 SDOperand Tmp = getValue(I.getOperand(1));
2152 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2157 } else if (isa<InlineAsm>(I.getOperand(0))) {
2162 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2163 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2167 Callee = getValue(I.getOperand(0));
2169 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2170 TargetLowering::ArgListTy Args;
2171 TargetLowering::ArgListEntry Entry;
2172 Args.reserve(I.getNumOperands());
2173 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2174 Value *Arg = I.getOperand(i);
2175 SDOperand ArgNode = getValue(Arg);
2176 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2177 Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2178 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2179 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2180 Args.push_back(Entry);
2183 std::pair<SDOperand,SDOperand> Result =
2184 TLI.LowerCallTo(getRoot(), I.getType(),
2185 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
2186 FTy->isVarArg(), I.getCallingConv(), I.isTailCall(),
2188 if (I.getType() != Type::VoidTy)
2189 setValue(&I, Result.first);
2190 DAG.setRoot(Result.second);
2193 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2194 SDOperand &Chain, SDOperand &Flag)const{
2195 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2196 Chain = Val.getValue(1);
2197 Flag = Val.getValue(2);
2199 // If the result was expanded, copy from the top part.
2200 if (Regs.size() > 1) {
2201 assert(Regs.size() == 2 &&
2202 "Cannot expand to more than 2 elts yet!");
2203 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2204 Chain = Hi.getValue(1);
2205 Flag = Hi.getValue(2);
2206 if (DAG.getTargetLoweringInfo().isLittleEndian())
2207 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2209 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2212 // Otherwise, if the return value was promoted or extended, truncate it to the
2213 // appropriate type.
2214 if (RegVT == ValueVT)
2217 if (MVT::isInteger(RegVT)) {
2218 if (ValueVT < RegVT)
2219 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2221 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2223 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2227 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2228 /// specified value into the registers specified by this object. This uses
2229 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2230 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2231 SDOperand &Chain, SDOperand &Flag,
2232 MVT::ValueType PtrVT) const {
2233 if (Regs.size() == 1) {
2234 // If there is a single register and the types differ, this must be
2236 if (RegVT != ValueVT) {
2237 if (MVT::isInteger(RegVT)) {
2238 if (RegVT < ValueVT)
2239 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2241 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2243 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2245 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2246 Flag = Chain.getValue(1);
2248 std::vector<unsigned> R(Regs);
2249 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2250 std::reverse(R.begin(), R.end());
2252 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2253 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2254 DAG.getConstant(i, PtrVT));
2255 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2256 Flag = Chain.getValue(1);
2261 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2262 /// operand list. This adds the code marker and includes the number of
2263 /// values added into it.
2264 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2265 std::vector<SDOperand> &Ops) const {
2266 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2267 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2268 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2271 /// isAllocatableRegister - If the specified register is safe to allocate,
2272 /// i.e. it isn't a stack pointer or some other special register, return the
2273 /// register class for the register. Otherwise, return null.
2274 static const TargetRegisterClass *
2275 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2276 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2277 MVT::ValueType FoundVT = MVT::Other;
2278 const TargetRegisterClass *FoundRC = 0;
2279 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2280 E = MRI->regclass_end(); RCI != E; ++RCI) {
2281 MVT::ValueType ThisVT = MVT::Other;
2283 const TargetRegisterClass *RC = *RCI;
2284 // If none of the the value types for this register class are valid, we
2285 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2286 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2288 if (TLI.isTypeLegal(*I)) {
2289 // If we have already found this register in a different register class,
2290 // choose the one with the largest VT specified. For example, on
2291 // PowerPC, we favor f64 register classes over f32.
2292 if (FoundVT == MVT::Other ||
2293 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2300 if (ThisVT == MVT::Other) continue;
2302 // NOTE: This isn't ideal. In particular, this might allocate the
2303 // frame pointer in functions that need it (due to them not being taken
2304 // out of allocation, because a variable sized allocation hasn't been seen
2305 // yet). This is a slight code pessimization, but should still work.
2306 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2307 E = RC->allocation_order_end(MF); I != E; ++I)
2309 // We found a matching register class. Keep looking at others in case
2310 // we find one with larger registers that this physreg is also in.
2319 RegsForValue SelectionDAGLowering::
2320 GetRegistersForValue(const std::string &ConstrCode,
2321 MVT::ValueType VT, bool isOutReg, bool isInReg,
2322 std::set<unsigned> &OutputRegs,
2323 std::set<unsigned> &InputRegs) {
2324 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2325 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2326 std::vector<unsigned> Regs;
2328 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2329 MVT::ValueType RegVT;
2330 MVT::ValueType ValueVT = VT;
2332 // If this is a constraint for a specific physical register, like {r17},
2334 if (PhysReg.first) {
2335 if (VT == MVT::Other)
2336 ValueVT = *PhysReg.second->vt_begin();
2338 // Get the actual register value type. This is important, because the user
2339 // may have asked for (e.g.) the AX register in i32 type. We need to
2340 // remember that AX is actually i16 to get the right extension.
2341 RegVT = *PhysReg.second->vt_begin();
2343 // This is a explicit reference to a physical register.
2344 Regs.push_back(PhysReg.first);
2346 // If this is an expanded reference, add the rest of the regs to Regs.
2348 TargetRegisterClass::iterator I = PhysReg.second->begin();
2349 TargetRegisterClass::iterator E = PhysReg.second->end();
2350 for (; *I != PhysReg.first; ++I)
2351 assert(I != E && "Didn't find reg!");
2353 // Already added the first reg.
2355 for (; NumRegs; --NumRegs, ++I) {
2356 assert(I != E && "Ran out of registers to allocate!");
2360 return RegsForValue(Regs, RegVT, ValueVT);
2363 // Otherwise, if this was a reference to an LLVM register class, create vregs
2364 // for this reference.
2365 std::vector<unsigned> RegClassRegs;
2366 if (PhysReg.second) {
2367 // If this is an early clobber or tied register, our regalloc doesn't know
2368 // how to maintain the constraint. If it isn't, go ahead and create vreg
2369 // and let the regalloc do the right thing.
2370 if (!isOutReg || !isInReg) {
2371 if (VT == MVT::Other)
2372 ValueVT = *PhysReg.second->vt_begin();
2373 RegVT = *PhysReg.second->vt_begin();
2375 // Create the appropriate number of virtual registers.
2376 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2377 for (; NumRegs; --NumRegs)
2378 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2380 return RegsForValue(Regs, RegVT, ValueVT);
2383 // Otherwise, we can't allocate it. Let the code below figure out how to
2384 // maintain these constraints.
2385 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2388 // This is a reference to a register class that doesn't directly correspond
2389 // to an LLVM register class. Allocate NumRegs consecutive, available,
2390 // registers from the class.
2391 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2394 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2395 MachineFunction &MF = *CurMBB->getParent();
2396 unsigned NumAllocated = 0;
2397 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2398 unsigned Reg = RegClassRegs[i];
2399 // See if this register is available.
2400 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2401 (isInReg && InputRegs.count(Reg))) { // Already used.
2402 // Make sure we find consecutive registers.
2407 // Check to see if this register is allocatable (i.e. don't give out the
2409 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
2411 // Make sure we find consecutive registers.
2416 // Okay, this register is good, we can use it.
2419 // If we allocated enough consecutive
2420 if (NumAllocated == NumRegs) {
2421 unsigned RegStart = (i-NumAllocated)+1;
2422 unsigned RegEnd = i+1;
2423 // Mark all of the allocated registers used.
2424 for (unsigned i = RegStart; i != RegEnd; ++i) {
2425 unsigned Reg = RegClassRegs[i];
2426 Regs.push_back(Reg);
2427 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2428 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2431 return RegsForValue(Regs, *RC->vt_begin(), VT);
2435 // Otherwise, we couldn't allocate enough registers for this.
2436 return RegsForValue();
2439 /// getConstraintGenerality - Return an integer indicating how general CT is.
2440 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2442 default: assert(0 && "Unknown constraint type!");
2443 case TargetLowering::C_Other:
2444 case TargetLowering::C_Unknown:
2446 case TargetLowering::C_Register:
2448 case TargetLowering::C_RegisterClass:
2450 case TargetLowering::C_Memory:
2455 static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2456 const TargetLowering &TLI) {
2457 assert(!C.empty() && "Must have at least one constraint");
2458 if (C.size() == 1) return C[0];
2460 std::string *Current = &C[0];
2461 // If we have multiple constraints, try to pick the most general one ahead
2462 // of time. This isn't a wonderful solution, but handles common cases.
2463 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0][0]);
2464 for (unsigned j = 1, e = C.size(); j != e; ++j) {
2465 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j][0]);
2466 if (getConstraintGenerality(ThisFlavor) >
2467 getConstraintGenerality(Flavor)) {
2468 // This constraint letter is more general than the previous one,
2470 Flavor = ThisFlavor;
2478 /// visitInlineAsm - Handle a call to an InlineAsm object.
2480 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2481 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2483 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2486 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
2487 std::vector<MVT::ValueType> ConstraintVTs;
2489 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2490 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2491 /// if it is a def of that register.
2492 std::vector<SDOperand> AsmNodeOperands;
2493 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2494 AsmNodeOperands.push_back(AsmStr);
2496 SDOperand Chain = getRoot();
2499 // We fully assign registers here at isel time. This is not optimal, but
2500 // should work. For register classes that correspond to LLVM classes, we
2501 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2502 // over the constraints, collecting fixed registers that we know we can't use.
2503 std::set<unsigned> OutputRegs, InputRegs;
2505 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2506 std::string ConstraintCode =
2507 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
2509 MVT::ValueType OpVT;
2511 // Compute the value type for each operand and add it to ConstraintVTs.
2512 switch (Constraints[i].Type) {
2513 case InlineAsm::isOutput:
2514 if (!Constraints[i].isIndirectOutput) {
2515 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2516 OpVT = TLI.getValueType(I.getType());
2518 const Type *OpTy = I.getOperand(OpNum)->getType();
2519 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2520 OpNum++; // Consumes a call operand.
2523 case InlineAsm::isInput:
2524 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2525 OpNum++; // Consumes a call operand.
2527 case InlineAsm::isClobber:
2532 ConstraintVTs.push_back(OpVT);
2534 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2535 continue; // Not assigned a fixed reg.
2537 // Build a list of regs that this operand uses. This always has a single
2538 // element for promoted/expanded operands.
2539 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2541 OutputRegs, InputRegs);
2543 switch (Constraints[i].Type) {
2544 case InlineAsm::isOutput:
2545 // We can't assign any other output to this register.
2546 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2547 // If this is an early-clobber output, it cannot be assigned to the same
2548 // value as the input reg.
2549 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2550 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2552 case InlineAsm::isInput:
2553 // We can't assign any other input to this register.
2554 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2556 case InlineAsm::isClobber:
2557 // Clobbered regs cannot be used as inputs or outputs.
2558 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2559 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2564 // Loop over all of the inputs, copying the operand values into the
2565 // appropriate registers and processing the output regs.
2566 RegsForValue RetValRegs;
2567 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2570 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2571 std::string ConstraintCode =
2572 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
2574 switch (Constraints[i].Type) {
2575 case InlineAsm::isOutput: {
2576 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2577 if (ConstraintCode.size() == 1) // not a physreg name.
2578 CTy = TLI.getConstraintType(ConstraintCode[0]);
2580 if (CTy == TargetLowering::C_Memory) {
2582 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2584 // Check that the operand (the address to store to) isn't a float.
2585 if (!MVT::isInteger(InOperandVal.getValueType()))
2586 assert(0 && "MATCH FAIL!");
2588 if (!Constraints[i].isIndirectOutput)
2589 assert(0 && "MATCH FAIL!");
2591 OpNum++; // Consumes a call operand.
2593 // Extend/truncate to the right pointer type if needed.
2594 MVT::ValueType PtrType = TLI.getPointerTy();
2595 if (InOperandVal.getValueType() < PtrType)
2596 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2597 else if (InOperandVal.getValueType() > PtrType)
2598 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2600 // Add information to the INLINEASM node to know about this output.
2601 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2602 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2603 AsmNodeOperands.push_back(InOperandVal);
2607 // Otherwise, this is a register output.
2608 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2610 // If this is an early-clobber output, or if there is an input
2611 // constraint that matches this, we need to reserve the input register
2612 // so no other inputs allocate to it.
2613 bool UsesInputRegister = false;
2614 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2615 UsesInputRegister = true;
2617 // Copy the output from the appropriate register. Find a register that
2620 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2621 true, UsesInputRegister,
2622 OutputRegs, InputRegs);
2623 if (Regs.Regs.empty()) {
2624 cerr << "Couldn't allocate output reg for contraint '"
2625 << ConstraintCode << "'!\n";
2629 if (!Constraints[i].isIndirectOutput) {
2630 assert(RetValRegs.Regs.empty() &&
2631 "Cannot have multiple output constraints yet!");
2632 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2635 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2636 I.getOperand(OpNum)));
2637 OpNum++; // Consumes a call operand.
2640 // Add information to the INLINEASM node to know that this register is
2642 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2645 case InlineAsm::isInput: {
2646 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2647 OpNum++; // Consumes a call operand.
2649 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2650 // If this is required to match an output register we have already set,
2651 // just use its register.
2652 unsigned OperandNo = atoi(ConstraintCode.c_str());
2654 // Scan until we find the definition we already emitted of this operand.
2655 // When we find it, create a RegsForValue operand.
2656 unsigned CurOp = 2; // The first operand.
2657 for (; OperandNo; --OperandNo) {
2658 // Advance to the next operand.
2660 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2661 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2662 (NumOps & 7) == 4 /*MEM*/) &&
2663 "Skipped past definitions?");
2664 CurOp += (NumOps>>3)+1;
2668 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2669 if ((NumOps & 7) == 2 /*REGDEF*/) {
2670 // Add NumOps>>3 registers to MatchedRegs.
2671 RegsForValue MatchedRegs;
2672 MatchedRegs.ValueVT = InOperandVal.getValueType();
2673 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2674 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2676 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2677 MatchedRegs.Regs.push_back(Reg);
2680 // Use the produced MatchedRegs object to
2681 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2682 TLI.getPointerTy());
2683 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2686 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
2687 assert(0 && "matching constraints for memory operands unimp");
2691 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2692 if (ConstraintCode.size() == 1) // not a physreg name.
2693 CTy = TLI.getConstraintType(ConstraintCode[0]);
2695 if (CTy == TargetLowering::C_Other) {
2696 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2697 ConstraintCode[0], DAG);
2698 if (!InOperandVal.Val) {
2699 cerr << "Invalid operand for inline asm constraint '"
2700 << ConstraintCode << "'!\n";
2704 // Add information to the INLINEASM node to know about this input.
2705 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2706 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2707 AsmNodeOperands.push_back(InOperandVal);
2709 } else if (CTy == TargetLowering::C_Memory) {
2712 // Check that the operand isn't a float.
2713 if (!MVT::isInteger(InOperandVal.getValueType()))
2714 assert(0 && "MATCH FAIL!");
2716 // Extend/truncate to the right pointer type if needed.
2717 MVT::ValueType PtrType = TLI.getPointerTy();
2718 if (InOperandVal.getValueType() < PtrType)
2719 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2720 else if (InOperandVal.getValueType() > PtrType)
2721 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2723 // Add information to the INLINEASM node to know about this input.
2724 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2725 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2726 AsmNodeOperands.push_back(InOperandVal);
2730 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2732 // Copy the input into the appropriate registers.
2733 RegsForValue InRegs =
2734 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2735 false, true, OutputRegs, InputRegs);
2736 // FIXME: should be match fail.
2737 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2739 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2741 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2744 case InlineAsm::isClobber: {
2745 RegsForValue ClobberedRegs =
2746 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2747 OutputRegs, InputRegs);
2748 // Add the clobbered value to the operand list, so that the register
2749 // allocator is aware that the physreg got clobbered.
2750 if (!ClobberedRegs.Regs.empty())
2751 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2757 // Finish up input operands.
2758 AsmNodeOperands[0] = Chain;
2759 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2761 Chain = DAG.getNode(ISD::INLINEASM,
2762 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
2763 &AsmNodeOperands[0], AsmNodeOperands.size());
2764 Flag = Chain.getValue(1);
2766 // If this asm returns a register value, copy the result from that register
2767 // and set it as the value of the call.
2768 if (!RetValRegs.Regs.empty())
2769 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2771 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2773 // Process indirect outputs, first output all of the flagged copies out of
2775 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2776 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2777 Value *Ptr = IndirectStoresToEmit[i].second;
2778 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2779 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2782 // Emit the non-flagged stores from the physregs.
2783 SmallVector<SDOperand, 8> OutChains;
2784 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2785 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
2786 getValue(StoresToEmit[i].second),
2787 StoresToEmit[i].second, 0));
2788 if (!OutChains.empty())
2789 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2790 &OutChains[0], OutChains.size());
2795 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2796 SDOperand Src = getValue(I.getOperand(0));
2798 MVT::ValueType IntPtr = TLI.getPointerTy();
2800 if (IntPtr < Src.getValueType())
2801 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2802 else if (IntPtr > Src.getValueType())
2803 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2805 // Scale the source by the type size.
2806 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2807 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2808 Src, getIntPtrConstant(ElementSize));
2810 TargetLowering::ArgListTy Args;
2811 TargetLowering::ArgListEntry Entry;
2813 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2814 Entry.isSigned = false;
2815 Entry.isInReg = false;
2816 Entry.isSRet = false;
2817 Args.push_back(Entry);
2819 std::pair<SDOperand,SDOperand> Result =
2820 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
2821 DAG.getExternalSymbol("malloc", IntPtr),
2823 setValue(&I, Result.first); // Pointers always fit in registers
2824 DAG.setRoot(Result.second);
2827 void SelectionDAGLowering::visitFree(FreeInst &I) {
2828 TargetLowering::ArgListTy Args;
2829 TargetLowering::ArgListEntry Entry;
2830 Entry.Node = getValue(I.getOperand(0));
2831 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2832 Entry.isSigned = false;
2833 Entry.isInReg = false;
2834 Entry.isSRet = false;
2835 Args.push_back(Entry);
2836 MVT::ValueType IntPtr = TLI.getPointerTy();
2837 std::pair<SDOperand,SDOperand> Result =
2838 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
2839 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2840 DAG.setRoot(Result.second);
2843 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2844 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2845 // instructions are special in various ways, which require special support to
2846 // insert. The specified MachineInstr is created but not inserted into any
2847 // basic blocks, and the scheduler passes ownership of it to this method.
2848 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2849 MachineBasicBlock *MBB) {
2850 cerr << "If a target marks an instruction with "
2851 << "'usesCustomDAGSchedInserter', it must implement "
2852 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
2857 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2858 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2859 getValue(I.getOperand(1)),
2860 DAG.getSrcValue(I.getOperand(1))));
2863 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2864 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2865 getValue(I.getOperand(0)),
2866 DAG.getSrcValue(I.getOperand(0)));
2868 DAG.setRoot(V.getValue(1));
2871 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2872 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2873 getValue(I.getOperand(1)),
2874 DAG.getSrcValue(I.getOperand(1))));
2877 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2878 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2879 getValue(I.getOperand(1)),
2880 getValue(I.getOperand(2)),
2881 DAG.getSrcValue(I.getOperand(1)),
2882 DAG.getSrcValue(I.getOperand(2))));
2885 /// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
2886 /// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
2887 static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
2888 unsigned &i, SelectionDAG &DAG,
2889 TargetLowering &TLI) {
2890 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
2891 return SDOperand(Arg, i++);
2893 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2894 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2896 return DAG.getNode(ISD::BIT_CONVERT, VT,
2897 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
2898 } else if (NumVals == 2) {
2899 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2900 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2901 if (!TLI.isLittleEndian())
2903 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
2905 // Value scalarized into many values. Unimp for now.
2906 assert(0 && "Cannot expand i64 -> i16 yet!");
2911 /// TargetLowering::LowerArguments - This is the default LowerArguments
2912 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
2913 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2914 /// integrated into SDISel.
2915 std::vector<SDOperand>
2916 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2917 const FunctionType *FTy = F.getFunctionType();
2918 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2919 std::vector<SDOperand> Ops;
2920 Ops.push_back(DAG.getRoot());
2921 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2922 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2924 // Add one result value for each formal argument.
2925 std::vector<MVT::ValueType> RetVals;
2927 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
2929 MVT::ValueType VT = getValueType(I->getType());
2930 bool isInReg = FTy->paramHasAttr(j, FunctionType::InRegAttribute);
2931 bool isSRet = FTy->paramHasAttr(j, FunctionType::StructRetAttribute);
2932 unsigned Flags = (isInReg << 1) | (isSRet << 2);
2934 switch (getTypeAction(VT)) {
2935 default: assert(0 && "Unknown type action!");
2937 RetVals.push_back(VT);
2938 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
2941 RetVals.push_back(getTypeToTransformTo(VT));
2942 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
2945 if (VT != MVT::Vector) {
2946 // If this is a large integer, it needs to be broken up into small
2947 // integers. Figure out what the destination type is and how many small
2948 // integers it turns into.
2949 MVT::ValueType NVT = getTypeToExpandTo(VT);
2950 unsigned NumVals = getNumElements(VT);
2951 for (unsigned i = 0; i != NumVals; ++i) {
2952 RetVals.push_back(NVT);
2953 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
2956 // Otherwise, this is a vector type. We only support legal vectors
2958 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2959 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2961 // Figure out if there is a Packed type corresponding to this Vector
2962 // type. If so, convert to the packed type.
2963 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2964 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2965 RetVals.push_back(TVT);
2966 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
2968 assert(0 && "Don't support illegal by-val vector arguments yet!");
2975 RetVals.push_back(MVT::Other);
2978 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2979 DAG.getNodeValueTypes(RetVals), RetVals.size(),
2980 &Ops[0], Ops.size()).Val;
2982 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
2984 // Set up the return result vector.
2988 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
2990 MVT::ValueType VT = getValueType(I->getType());
2992 switch (getTypeAction(VT)) {
2993 default: assert(0 && "Unknown type action!");
2995 Ops.push_back(SDOperand(Result, i++));
2998 SDOperand Op(Result, i++);
2999 if (MVT::isInteger(VT)) {
3000 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3001 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3002 DAG.getValueType(VT));
3003 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3004 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3005 DAG.getValueType(VT));
3006 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3008 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3009 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3015 if (VT != MVT::Vector) {
3016 // If this is a large integer or a floating point node that needs to be
3017 // expanded, it needs to be reassembled from small integers. Figure out
3018 // what the source elt type is and how many small integers it is.
3019 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
3021 // Otherwise, this is a vector type. We only support legal vectors
3023 const PackedType *PTy = cast<PackedType>(I->getType());
3024 unsigned NumElems = PTy->getNumElements();
3025 const Type *EltTy = PTy->getElementType();
3027 // Figure out if there is a Packed type corresponding to this Vector
3028 // type. If so, convert to the packed type.
3029 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3030 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3031 SDOperand N = SDOperand(Result, i++);
3032 // Handle copies from generic vectors to registers.
3033 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3034 DAG.getConstant(NumElems, MVT::i32),
3035 DAG.getValueType(getValueType(EltTy)));
3038 assert(0 && "Don't support illegal by-val vector arguments yet!");
3049 /// ExpandScalarCallArgs - Recursively expand call argument node by
3050 /// bit_converting it or extract a pair of elements from the larger node.
3051 static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3053 SmallVector<SDOperand, 32> &Ops,
3055 TargetLowering &TLI) {
3056 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3058 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3062 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3063 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3065 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3066 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI);
3067 } else if (NumVals == 2) {
3068 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3069 DAG.getConstant(0, TLI.getPointerTy()));
3070 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3071 DAG.getConstant(1, TLI.getPointerTy()));
3072 if (!TLI.isLittleEndian())
3074 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI);
3075 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI);
3077 // Value scalarized into many values. Unimp for now.
3078 assert(0 && "Cannot expand i64 -> i16 yet!");
3082 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
3083 /// implementation, which just inserts an ISD::CALL node, which is later custom
3084 /// lowered by the target to something concrete. FIXME: When all targets are
3085 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3086 std::pair<SDOperand, SDOperand>
3087 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3088 bool RetTyIsSigned, bool isVarArg,
3089 unsigned CallingConv, bool isTailCall,
3091 ArgListTy &Args, SelectionDAG &DAG) {
3092 SmallVector<SDOperand, 32> Ops;
3093 Ops.push_back(Chain); // Op#0 - Chain
3094 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3095 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3096 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3097 Ops.push_back(Callee);
3099 // Handle all of the outgoing arguments.
3100 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3101 MVT::ValueType VT = getValueType(Args[i].Ty);
3102 SDOperand Op = Args[i].Node;
3103 bool isSigned = Args[i].isSigned;
3104 bool isInReg = Args[i].isInReg;
3105 bool isSRet = Args[i].isSRet;
3106 unsigned Flags = (isSRet << 2) | (isInReg << 1) | isSigned;
3107 switch (getTypeAction(VT)) {
3108 default: assert(0 && "Unknown type action!");
3111 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3114 if (MVT::isInteger(VT)) {
3115 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3116 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3118 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3119 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3122 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3125 if (VT != MVT::Vector) {
3126 // If this is a large integer, it needs to be broken down into small
3127 // integers. Figure out what the source elt type is and how many small
3129 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
3131 // Otherwise, this is a vector type. We only support legal vectors
3133 const PackedType *PTy = cast<PackedType>(Args[i].Ty);
3134 unsigned NumElems = PTy->getNumElements();
3135 const Type *EltTy = PTy->getElementType();
3137 // Figure out if there is a Packed type corresponding to this Vector
3138 // type. If so, convert to the packed type.
3139 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3140 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3141 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3142 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3144 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3146 assert(0 && "Don't support illegal by-val vector call args yet!");
3154 // Figure out the result value types.
3155 SmallVector<MVT::ValueType, 4> RetTys;
3157 if (RetTy != Type::VoidTy) {
3158 MVT::ValueType VT = getValueType(RetTy);
3159 switch (getTypeAction(VT)) {
3160 default: assert(0 && "Unknown type action!");
3162 RetTys.push_back(VT);
3165 RetTys.push_back(getTypeToTransformTo(VT));
3168 if (VT != MVT::Vector) {
3169 // If this is a large integer, it needs to be reassembled from small
3170 // integers. Figure out what the source elt type is and how many small
3172 MVT::ValueType NVT = getTypeToExpandTo(VT);
3173 unsigned NumVals = getNumElements(VT);
3174 for (unsigned i = 0; i != NumVals; ++i)
3175 RetTys.push_back(NVT);
3177 // Otherwise, this is a vector type. We only support legal vectors
3179 const PackedType *PTy = cast<PackedType>(RetTy);
3180 unsigned NumElems = PTy->getNumElements();
3181 const Type *EltTy = PTy->getElementType();
3183 // Figure out if there is a Packed type corresponding to this Vector
3184 // type. If so, convert to the packed type.
3185 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3186 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3187 RetTys.push_back(TVT);
3189 assert(0 && "Don't support illegal by-val vector call results yet!");
3196 RetTys.push_back(MVT::Other); // Always has a chain.
3198 // Finally, create the CALL node.
3199 SDOperand Res = DAG.getNode(ISD::CALL,
3200 DAG.getVTList(&RetTys[0], RetTys.size()),
3201 &Ops[0], Ops.size());
3203 // This returns a pair of operands. The first element is the
3204 // return value for the function (if RetTy is not VoidTy). The second
3205 // element is the outgoing token chain.
3207 if (RetTys.size() != 1) {
3208 MVT::ValueType VT = getValueType(RetTy);
3209 if (RetTys.size() == 2) {
3212 // If this value was promoted, truncate it down.
3213 if (ResVal.getValueType() != VT) {
3214 if (VT == MVT::Vector) {
3215 // Insert a VBITCONVERT to convert from the packed result type to the
3216 // MVT::Vector type.
3217 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3218 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3220 // Figure out if there is a Packed type corresponding to this Vector
3221 // type. If so, convert to the packed type.
3222 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
3223 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3224 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3225 // "N x PTyElementVT" MVT::Vector type.
3226 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
3227 DAG.getConstant(NumElems, MVT::i32),
3228 DAG.getValueType(getValueType(EltTy)));
3232 } else if (MVT::isInteger(VT)) {
3233 unsigned AssertOp = ISD::AssertSext;
3235 AssertOp = ISD::AssertZext;
3236 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3237 DAG.getValueType(VT));
3238 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3240 assert(MVT::isFloatingPoint(VT));
3241 if (getTypeAction(VT) == Expand)
3242 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3244 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3247 } else if (RetTys.size() == 3) {
3248 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3249 Res.getValue(0), Res.getValue(1));
3252 assert(0 && "Case not handled yet!");
3256 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3259 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3260 assert(0 && "LowerOperation not implemented for this target!");
3265 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3266 SelectionDAG &DAG) {
3267 assert(0 && "CustomPromoteOperation not implemented for this target!");
3272 /// getMemsetValue - Vectorized representation of the memset value
3274 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
3275 SelectionDAG &DAG) {
3276 MVT::ValueType CurVT = VT;
3277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3278 uint64_t Val = C->getValue() & 255;
3280 while (CurVT != MVT::i8) {
3281 Val = (Val << Shift) | Val;
3283 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3285 return DAG.getConstant(Val, VT);
3287 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3289 while (CurVT != MVT::i8) {
3291 DAG.getNode(ISD::OR, VT,
3292 DAG.getNode(ISD::SHL, VT, Value,
3293 DAG.getConstant(Shift, MVT::i8)), Value);
3295 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3302 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3303 /// used when a memcpy is turned into a memset when the source is a constant
3305 static SDOperand getMemsetStringVal(MVT::ValueType VT,
3306 SelectionDAG &DAG, TargetLowering &TLI,
3307 std::string &Str, unsigned Offset) {
3309 unsigned MSB = getSizeInBits(VT) / 8;
3310 if (TLI.isLittleEndian())
3311 Offset = Offset + MSB - 1;
3312 for (unsigned i = 0; i != MSB; ++i) {
3313 Val = (Val << 8) | (unsigned char)Str[Offset];
3314 Offset += TLI.isLittleEndian() ? -1 : 1;
3316 return DAG.getConstant(Val, VT);
3319 /// getMemBasePlusOffset - Returns base and offset node for the
3320 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3321 SelectionDAG &DAG, TargetLowering &TLI) {
3322 MVT::ValueType VT = Base.getValueType();
3323 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3326 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3327 /// to replace the memset / memcpy is below the threshold. It also returns the
3328 /// types of the sequence of memory ops to perform memset / memcpy.
3329 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3330 unsigned Limit, uint64_t Size,
3331 unsigned Align, TargetLowering &TLI) {
3334 if (TLI.allowsUnalignedMemoryAccesses()) {
3337 switch (Align & 7) {
3353 MVT::ValueType LVT = MVT::i64;
3354 while (!TLI.isTypeLegal(LVT))
3355 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3356 assert(MVT::isInteger(LVT));
3361 unsigned NumMemOps = 0;
3363 unsigned VTSize = getSizeInBits(VT) / 8;
3364 while (VTSize > Size) {
3365 VT = (MVT::ValueType)((unsigned)VT - 1);
3368 assert(MVT::isInteger(VT));
3370 if (++NumMemOps > Limit)
3372 MemOps.push_back(VT);
3379 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
3380 SDOperand Op1 = getValue(I.getOperand(1));
3381 SDOperand Op2 = getValue(I.getOperand(2));
3382 SDOperand Op3 = getValue(I.getOperand(3));
3383 SDOperand Op4 = getValue(I.getOperand(4));
3384 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3385 if (Align == 0) Align = 1;
3387 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3388 std::vector<MVT::ValueType> MemOps;
3390 // Expand memset / memcpy to a series of load / store ops
3391 // if the size operand falls below a certain threshold.
3392 SmallVector<SDOperand, 8> OutChains;
3394 default: break; // Do nothing for now.
3396 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3397 Size->getValue(), Align, TLI)) {
3398 unsigned NumMemOps = MemOps.size();
3399 unsigned Offset = 0;
3400 for (unsigned i = 0; i < NumMemOps; i++) {
3401 MVT::ValueType VT = MemOps[i];
3402 unsigned VTSize = getSizeInBits(VT) / 8;
3403 SDOperand Value = getMemsetValue(Op2, VT, DAG);
3404 SDOperand Store = DAG.getStore(getRoot(), Value,
3405 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
3406 I.getOperand(1), Offset);
3407 OutChains.push_back(Store);
3414 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3415 Size->getValue(), Align, TLI)) {
3416 unsigned NumMemOps = MemOps.size();
3417 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
3418 GlobalAddressSDNode *G = NULL;
3420 bool CopyFromStr = false;
3422 if (Op2.getOpcode() == ISD::GlobalAddress)
3423 G = cast<GlobalAddressSDNode>(Op2);
3424 else if (Op2.getOpcode() == ISD::ADD &&
3425 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3426 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3427 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
3428 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
3431 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3432 if (GV && GV->isConstant()) {
3433 Str = GV->getStringValue(false);
3441 for (unsigned i = 0; i < NumMemOps; i++) {
3442 MVT::ValueType VT = MemOps[i];
3443 unsigned VTSize = getSizeInBits(VT) / 8;
3444 SDOperand Value, Chain, Store;
3447 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3450 DAG.getStore(Chain, Value,
3451 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3452 I.getOperand(1), DstOff);
3454 Value = DAG.getLoad(VT, getRoot(),
3455 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
3456 I.getOperand(2), SrcOff);
3457 Chain = Value.getValue(1);
3459 DAG.getStore(Chain, Value,
3460 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3461 I.getOperand(1), DstOff);
3463 OutChains.push_back(Store);
3472 if (!OutChains.empty()) {
3473 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3474 &OutChains[0], OutChains.size()));
3479 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
3482 //===----------------------------------------------------------------------===//
3483 // SelectionDAGISel code
3484 //===----------------------------------------------------------------------===//
3486 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3487 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3490 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
3491 // FIXME: we only modify the CFG to split critical edges. This
3492 // updates dom and loop info.
3493 AU.addRequired<AliasAnalysis>();
3497 /// OptimizeNoopCopyExpression - We have determined that the specified cast
3498 /// instruction is a noop copy (e.g. it's casting from one pointer type to
3499 /// another, int->uint, or int->sbyte on PPC.
3501 /// Return true if any changes are made.
3502 static bool OptimizeNoopCopyExpression(CastInst *CI) {
3503 BasicBlock *DefBB = CI->getParent();
3505 /// InsertedCasts - Only insert a cast in each block once.
3506 std::map<BasicBlock*, CastInst*> InsertedCasts;
3508 bool MadeChange = false;
3509 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3511 Use &TheUse = UI.getUse();
3512 Instruction *User = cast<Instruction>(*UI);
3514 // Figure out which BB this cast is used in. For PHI's this is the
3515 // appropriate predecessor block.
3516 BasicBlock *UserBB = User->getParent();
3517 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3518 unsigned OpVal = UI.getOperandNo()/2;
3519 UserBB = PN->getIncomingBlock(OpVal);
3522 // Preincrement use iterator so we don't invalidate it.
3525 // If this user is in the same block as the cast, don't change the cast.
3526 if (UserBB == DefBB) continue;
3528 // If we have already inserted a cast into this block, use it.
3529 CastInst *&InsertedCast = InsertedCasts[UserBB];
3531 if (!InsertedCast) {
3532 BasicBlock::iterator InsertPt = UserBB->begin();
3533 while (isa<PHINode>(InsertPt)) ++InsertPt;
3536 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3541 // Replace a use of the cast with a use of the new casat.
3542 TheUse = InsertedCast;
3545 // If we removed all uses, nuke the cast.
3546 if (CI->use_empty())
3547 CI->eraseFromParent();
3552 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3553 /// casting to the type of GEPI.
3554 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3555 Instruction *GEPI, Value *Ptr,
3557 if (V) return V; // Already computed.
3559 // Figure out the insertion point
3560 BasicBlock::iterator InsertPt;
3561 if (BB == GEPI->getParent()) {
3562 // If GEP is already inserted into BB, insert right after the GEP.
3566 // Otherwise, insert at the top of BB, after any PHI nodes
3567 InsertPt = BB->begin();
3568 while (isa<PHINode>(InsertPt)) ++InsertPt;
3571 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3572 // BB so that there is only one value live across basic blocks (the cast
3574 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3575 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3576 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3579 // Add the offset, cast it to the right type.
3580 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3581 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3582 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3586 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3587 /// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3588 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3589 /// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3590 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
3591 /// the constant add into a load or store instruction. Additionally, if a user
3592 /// is a pointer-pointer cast, we look through it to find its users.
3593 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3594 Constant *PtrOffset, BasicBlock *DefBB,
3595 GetElementPtrInst *GEPI,
3596 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3597 while (!RepPtr->use_empty()) {
3598 Instruction *User = cast<Instruction>(RepPtr->use_back());
3600 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3601 // used for a Pointer-Pointer cast.
3602 if (isa<BitCastInst>(User)) {
3603 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3605 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3606 // could invalidate an iterator.
3607 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3611 // If this is a load of the pointer, or a store through the pointer, emit
3612 // the increment into the load/store block.
3613 Instruction *NewVal;
3614 if (isa<LoadInst>(User) ||
3615 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3616 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3617 User->getParent(), GEPI,
3620 // If this use is not foldable into the addressing mode, use a version
3621 // emitted in the GEP block.
3622 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3626 if (GEPI->getType() != RepPtr->getType()) {
3627 BasicBlock::iterator IP = NewVal;
3629 // NewVal must be a GEP which must be pointer type, so BitCast
3630 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
3632 User->replaceUsesOfWith(RepPtr, NewVal);
3637 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3638 /// selection, we want to be a bit careful about some things. In particular, if
3639 /// we have a GEP instruction that is used in a different block than it is
3640 /// defined, the addressing expression of the GEP cannot be folded into loads or
3641 /// stores that use it. In this case, decompose the GEP and move constant
3642 /// indices into blocks that use it.
3643 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3644 const TargetData *TD) {
3645 // If this GEP is only used inside the block it is defined in, there is no
3646 // need to rewrite it.
3647 bool isUsedOutsideDefBB = false;
3648 BasicBlock *DefBB = GEPI->getParent();
3649 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3651 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3652 isUsedOutsideDefBB = true;
3656 if (!isUsedOutsideDefBB) return false;
3658 // If this GEP has no non-zero constant indices, there is nothing we can do,
3660 bool hasConstantIndex = false;
3661 bool hasVariableIndex = false;
3662 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3663 E = GEPI->op_end(); OI != E; ++OI) {
3664 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3665 if (CI->getZExtValue()) {
3666 hasConstantIndex = true;
3670 hasVariableIndex = true;
3674 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3675 if (!hasConstantIndex && !hasVariableIndex) {
3676 /// The GEP operand must be a pointer, so must its result -> BitCast
3677 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3678 GEPI->getName(), GEPI);
3679 GEPI->replaceAllUsesWith(NC);
3680 GEPI->eraseFromParent();
3684 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3685 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3688 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3689 // constant offset (which we now know is non-zero) and deal with it later.
3690 uint64_t ConstantOffset = 0;
3691 const Type *UIntPtrTy = TD->getIntPtrType();
3692 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3693 const Type *Ty = GEPI->getOperand(0)->getType();
3695 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3696 E = GEPI->op_end(); OI != E; ++OI) {
3698 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3699 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3701 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
3702 Ty = StTy->getElementType(Field);
3704 Ty = cast<SequentialType>(Ty)->getElementType();
3706 // Handle constant subscripts.
3707 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3708 if (CI->getZExtValue() == 0) continue;
3709 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
3713 // Ptr = Ptr + Idx * ElementSize;
3715 // Cast Idx to UIntPtrTy if needed.
3716 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
3718 uint64_t ElementSize = TD->getTypeSize(Ty);
3719 // Mask off bits that should not be set.
3720 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3721 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
3723 // Multiply by the element size and add to the base.
3724 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3725 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3729 // Make sure that the offset fits in uintptr_t.
3730 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3731 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
3733 // Okay, we have now emitted all of the variable index parts to the BB that
3734 // the GEP is defined in. Loop over all of the using instructions, inserting
3735 // an "add Ptr, ConstantOffset" into each block that uses it and update the
3736 // instruction to use the newly computed value, making GEPI dead. When the
3737 // user is a load or store instruction address, we emit the add into the user
3738 // block, otherwise we use a canonical version right next to the gep (these
3739 // won't be foldable as addresses, so we might as well share the computation).
3741 std::map<BasicBlock*,Instruction*> InsertedExprs;
3742 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3744 // Finally, the GEP is dead, remove it.
3745 GEPI->eraseFromParent();
3751 /// SplitEdgeNicely - Split the critical edge from TI to it's specified
3752 /// successor if it will improve codegen. We only do this if the successor has
3753 /// phi nodes (otherwise critical edges are ok). If there is already another
3754 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
3755 /// instead of introducing a new block.
3756 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3757 BasicBlock *TIBB = TI->getParent();
3758 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3759 assert(isa<PHINode>(Dest->begin()) &&
3760 "This should only be called if Dest has a PHI!");
3762 /// TIPHIValues - This array is lazily computed to determine the values of
3763 /// PHIs in Dest that TI would provide.
3764 std::vector<Value*> TIPHIValues;
3766 // Check to see if Dest has any blocks that can be used as a split edge for
3768 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3769 BasicBlock *Pred = *PI;
3770 // To be usable, the pred has to end with an uncond branch to the dest.
3771 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3772 if (!PredBr || !PredBr->isUnconditional() ||
3773 // Must be empty other than the branch.
3774 &Pred->front() != PredBr)
3777 // Finally, since we know that Dest has phi nodes in it, we have to make
3778 // sure that jumping to Pred will have the same affect as going to Dest in
3779 // terms of PHI values.
3782 bool FoundMatch = true;
3783 for (BasicBlock::iterator I = Dest->begin();
3784 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3785 if (PHINo == TIPHIValues.size())
3786 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3788 // If the PHI entry doesn't work, we can't use this pred.
3789 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3795 // If we found a workable predecessor, change TI to branch to Succ.
3797 Dest->removePredecessor(TIBB);
3798 TI->setSuccessor(SuccNum, Pred);
3803 SplitCriticalEdge(TI, SuccNum, P, true);
3807 bool SelectionDAGISel::runOnFunction(Function &Fn) {
3808 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3809 RegMap = MF.getSSARegMap();
3810 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
3812 // First, split all critical edges.
3814 // In this pass we also look for GEP and cast instructions that are used
3815 // across basic blocks and rewrite them to improve basic-block-at-a-time
3818 bool MadeChange = true;
3819 while (MadeChange) {
3821 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3822 // Split all critical edges where the dest block has a PHI.
3823 TerminatorInst *BBTI = BB->getTerminator();
3824 if (BBTI->getNumSuccessors() > 1) {
3825 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
3826 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3827 isCriticalEdge(BBTI, i, true))
3828 SplitEdgeNicely(BBTI, i, this);
3832 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3833 Instruction *I = BBI++;
3835 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3836 // If we found an inline asm expession, and if the target knows how to
3837 // lower it to normal LLVM code, do so now.
3838 if (isa<InlineAsm>(CI->getCalledValue()))
3839 if (const TargetAsmInfo *TAI =
3840 TLI.getTargetMachine().getTargetAsmInfo()) {
3841 if (TAI->ExpandInlineAsm(CI))
3844 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3845 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3846 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3847 // If the source of the cast is a constant, then this should have
3848 // already been constant folded. The only reason NOT to constant fold
3849 // it is if something (e.g. LSR) was careful to place the constant
3850 // evaluation in a block other than then one that uses it (e.g. to hoist
3851 // the address of globals out of a loop). If this is the case, we don't
3852 // want to forward-subst the cast.
3853 if (isa<Constant>(CI->getOperand(0)))
3856 // If this is a noop copy, sink it into user blocks to reduce the number
3857 // of virtual registers that must be created and coallesced.
3858 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3859 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3861 // This is an fp<->int conversion?
3862 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3865 // If this is an extension, it will be a zero or sign extension, which
3867 if (SrcVT < DstVT) continue;
3869 // If these values will be promoted, find out what they will be promoted
3870 // to. This helps us consider truncates on PPC as noop copies when they
3872 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3873 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3874 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3875 DstVT = TLI.getTypeToTransformTo(DstVT);
3877 // If, after promotion, these are the same types, this is a noop copy.
3879 MadeChange |= OptimizeNoopCopyExpression(CI);
3885 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3887 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3888 SelectBasicBlock(I, MF, FuncInfo);
3893 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3895 SDOperand Op = getValue(V);
3896 assert((Op.getOpcode() != ISD::CopyFromReg ||
3897 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3898 "Copy from a reg to the same reg!");
3900 // If this type is not legal, we must make sure to not create an invalid
3902 MVT::ValueType SrcVT = Op.getValueType();
3903 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3904 if (SrcVT == DestVT) {
3905 return DAG.getCopyToReg(getRoot(), Reg, Op);
3906 } else if (SrcVT == MVT::Vector) {
3907 // Handle copies from generic vectors to registers.
3908 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3909 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3910 PTyElementVT, PTyLegalElementVT);
3912 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3913 // MVT::Vector type.
3914 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3915 DAG.getConstant(NE, MVT::i32),
3916 DAG.getValueType(PTyElementVT));
3918 // Loop over all of the elements of the resultant vector,
3919 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3920 // copying them into output registers.
3921 SmallVector<SDOperand, 8> OutChains;
3922 SDOperand Root = getRoot();
3923 for (unsigned i = 0; i != NE; ++i) {
3924 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3925 Op, DAG.getConstant(i, TLI.getPointerTy()));
3926 if (PTyElementVT == PTyLegalElementVT) {
3927 // Elements are legal.
3928 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3929 } else if (PTyLegalElementVT > PTyElementVT) {
3930 // Elements are promoted.
3931 if (MVT::isFloatingPoint(PTyLegalElementVT))
3932 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3934 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3935 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3937 // Elements are expanded.
3938 // The src value is expanded into multiple registers.
3939 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3940 Elt, DAG.getConstant(0, TLI.getPointerTy()));
3941 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3942 Elt, DAG.getConstant(1, TLI.getPointerTy()));
3943 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3944 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3947 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3948 &OutChains[0], OutChains.size());
3949 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
3950 // The src value is promoted to the register.
3951 if (MVT::isFloatingPoint(SrcVT))
3952 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3954 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3955 return DAG.getCopyToReg(getRoot(), Reg, Op);
3957 DestVT = TLI.getTypeToExpandTo(SrcVT);
3958 unsigned NumVals = TLI.getNumElements(SrcVT);
3960 return DAG.getCopyToReg(getRoot(), Reg,
3961 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
3962 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
3963 // The src value is expanded into multiple registers.
3964 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3965 Op, DAG.getConstant(0, TLI.getPointerTy()));
3966 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3967 Op, DAG.getConstant(1, TLI.getPointerTy()));
3968 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
3969 return DAG.getCopyToReg(Op, Reg+1, Hi);
3973 void SelectionDAGISel::
3974 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3975 std::vector<SDOperand> &UnorderedChains) {
3976 // If this is the entry block, emit arguments.
3977 Function &F = *BB->getParent();
3978 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3979 SDOperand OldRoot = SDL.DAG.getRoot();
3980 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3983 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3985 if (!AI->use_empty()) {
3986 SDL.setValue(AI, Args[a]);
3988 // If this argument is live outside of the entry block, insert a copy from
3989 // whereever we got it to the vreg that other BB's will reference it as.
3990 if (FuncInfo.ValueMap.count(AI)) {
3992 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
3993 UnorderedChains.push_back(Copy);
3997 // Finally, if the target has anything special to do, allow it to do so.
3998 // FIXME: this should insert code into the DAG!
3999 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4002 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4003 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4004 FunctionLoweringInfo &FuncInfo) {
4005 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
4007 std::vector<SDOperand> UnorderedChains;
4009 // Lower any arguments needed in this block if this is the entry block.
4010 if (LLVMBB == &LLVMBB->getParent()->front())
4011 LowerArguments(LLVMBB, SDL, UnorderedChains);
4013 BB = FuncInfo.MBBMap[LLVMBB];
4014 SDL.setCurrentBasicBlock(BB);
4016 // Lower all of the non-terminator instructions.
4017 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4021 // Ensure that all instructions which are used outside of their defining
4022 // blocks are available as virtual registers.
4023 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4024 if (!I->use_empty() && !isa<PHINode>(I)) {
4025 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4026 if (VMI != FuncInfo.ValueMap.end())
4027 UnorderedChains.push_back(
4028 SDL.CopyValueToVirtualRegister(I, VMI->second));
4031 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4032 // ensure constants are generated when needed. Remember the virtual registers
4033 // that need to be added to the Machine PHI nodes as input. We cannot just
4034 // directly add them, because expansion might result in multiple MBB's for one
4035 // BB. As such, the start of the BB might correspond to a different MBB than
4038 TerminatorInst *TI = LLVMBB->getTerminator();
4040 // Emit constants only once even if used by multiple PHI nodes.
4041 std::map<Constant*, unsigned> ConstantsOut;
4043 // Vector bool would be better, but vector<bool> is really slow.
4044 std::vector<unsigned char> SuccsHandled;
4045 if (TI->getNumSuccessors())
4046 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4048 // Check successor nodes PHI nodes that expect a constant to be available from
4050 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4051 BasicBlock *SuccBB = TI->getSuccessor(succ);
4052 if (!isa<PHINode>(SuccBB->begin())) continue;
4053 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4055 // If this terminator has multiple identical successors (common for
4056 // switches), only handle each succ once.
4057 unsigned SuccMBBNo = SuccMBB->getNumber();
4058 if (SuccsHandled[SuccMBBNo]) continue;
4059 SuccsHandled[SuccMBBNo] = true;
4061 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4064 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4065 // nodes and Machine PHI nodes, but the incoming operands have not been
4067 for (BasicBlock::iterator I = SuccBB->begin();
4068 (PN = dyn_cast<PHINode>(I)); ++I) {
4069 // Ignore dead phi's.
4070 if (PN->use_empty()) continue;
4073 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4075 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4076 unsigned &RegOut = ConstantsOut[C];
4078 RegOut = FuncInfo.CreateRegForValue(C);
4079 UnorderedChains.push_back(
4080 SDL.CopyValueToVirtualRegister(C, RegOut));
4084 Reg = FuncInfo.ValueMap[PHIOp];
4086 assert(isa<AllocaInst>(PHIOp) &&
4087 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4088 "Didn't codegen value into a register!??");
4089 Reg = FuncInfo.CreateRegForValue(PHIOp);
4090 UnorderedChains.push_back(
4091 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4095 // Remember that this register needs to added to the machine PHI node as
4096 // the input for this MBB.
4097 MVT::ValueType VT = TLI.getValueType(PN->getType());
4098 unsigned NumElements;
4099 if (VT != MVT::Vector)
4100 NumElements = TLI.getNumElements(VT);
4102 MVT::ValueType VT1,VT2;
4104 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4107 for (unsigned i = 0, e = NumElements; i != e; ++i)
4108 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4111 ConstantsOut.clear();
4113 // Turn all of the unordered chains into one factored node.
4114 if (!UnorderedChains.empty()) {
4115 SDOperand Root = SDL.getRoot();
4116 if (Root.getOpcode() != ISD::EntryToken) {
4117 unsigned i = 0, e = UnorderedChains.size();
4118 for (; i != e; ++i) {
4119 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4120 if (UnorderedChains[i].Val->getOperand(0) == Root)
4121 break; // Don't add the root if we already indirectly depend on it.
4125 UnorderedChains.push_back(Root);
4127 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4128 &UnorderedChains[0], UnorderedChains.size()));
4131 // Lower the terminator after the copies are emitted.
4132 SDL.visit(*LLVMBB->getTerminator());
4134 // Copy over any CaseBlock records that may now exist due to SwitchInst
4135 // lowering, as well as any jump table information.
4136 SwitchCases.clear();
4137 SwitchCases = SDL.SwitchCases;
4140 // Make sure the root of the DAG is up-to-date.
4141 DAG.setRoot(SDL.getRoot());
4144 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4145 // Get alias analysis for load/store combining.
4146 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4148 // Run the DAG combiner in pre-legalize mode.
4149 DAG.Combine(false, AA);
4151 DOUT << "Lowered selection DAG:\n";
4154 // Second step, hack on the DAG until it only uses operations and types that
4155 // the target supports.
4158 DOUT << "Legalized selection DAG:\n";
4161 // Run the DAG combiner in post-legalize mode.
4162 DAG.Combine(true, AA);
4164 if (ViewISelDAGs) DAG.viewGraph();
4166 // Third, instruction select all of the operations to machine code, adding the
4167 // code to the MachineBasicBlock.
4168 InstructionSelectBasicBlock(DAG);
4170 DOUT << "Selected machine code:\n";
4174 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4175 FunctionLoweringInfo &FuncInfo) {
4176 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4178 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4181 // First step, lower LLVM code to some DAG. This DAG may use operations and
4182 // types that are not supported by the target.
4183 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4185 // Second step, emit the lowered DAG as machine code.
4186 CodeGenAndEmitDAG(DAG);
4189 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4190 // PHI nodes in successors.
4191 if (SwitchCases.empty() && JT.Reg == 0) {
4192 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4193 MachineInstr *PHI = PHINodesToUpdate[i].first;
4194 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4195 "This is not a machine PHI node that we are updating!");
4196 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4197 PHI->addMachineBasicBlockOperand(BB);
4202 // If the JumpTable record is filled in, then we need to emit a jump table.
4203 // Updating the PHI nodes is tricky in this case, since we need to determine
4204 // whether the PHI is a successor of the range check MBB or the jump table MBB
4206 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4207 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4209 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4210 MachineBasicBlock *RangeBB = BB;
4211 // Set the current basic block to the mbb we wish to insert the code into
4213 SDL.setCurrentBasicBlock(BB);
4215 SDL.visitJumpTable(JT);
4216 SDAG.setRoot(SDL.getRoot());
4217 CodeGenAndEmitDAG(SDAG);
4219 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4220 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4221 MachineBasicBlock *PHIBB = PHI->getParent();
4222 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4223 "This is not a machine PHI node that we are updating!");
4224 if (PHIBB == JT.Default) {
4225 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4226 PHI->addMachineBasicBlockOperand(RangeBB);
4228 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4229 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4230 PHI->addMachineBasicBlockOperand(BB);
4236 // If the switch block involved a branch to one of the actual successors, we
4237 // need to update PHI nodes in that block.
4238 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4239 MachineInstr *PHI = PHINodesToUpdate[i].first;
4240 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4241 "This is not a machine PHI node that we are updating!");
4242 if (BB->isSuccessor(PHI->getParent())) {
4243 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4244 PHI->addMachineBasicBlockOperand(BB);
4248 // If we generated any switch lowering information, build and codegen any
4249 // additional DAGs necessary.
4250 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4251 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4253 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4255 // Set the current basic block to the mbb we wish to insert the code into
4256 BB = SwitchCases[i].ThisBB;
4257 SDL.setCurrentBasicBlock(BB);
4260 SDL.visitSwitchCase(SwitchCases[i]);
4261 SDAG.setRoot(SDL.getRoot());
4262 CodeGenAndEmitDAG(SDAG);
4264 // Handle any PHI nodes in successors of this chunk, as if we were coming
4265 // from the original BB before switch expansion. Note that PHI nodes can
4266 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4267 // handle them the right number of times.
4268 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4269 for (MachineBasicBlock::iterator Phi = BB->begin();
4270 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4271 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4272 for (unsigned pn = 0; ; ++pn) {
4273 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4274 if (PHINodesToUpdate[pn].first == Phi) {
4275 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4276 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4282 // Don't process RHS if same block as LHS.
4283 if (BB == SwitchCases[i].FalseBB)
4284 SwitchCases[i].FalseBB = 0;
4286 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4287 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4288 SwitchCases[i].FalseBB = 0;
4290 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4295 //===----------------------------------------------------------------------===//
4296 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4297 /// target node in the graph.
4298 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4299 if (ViewSchedDAGs) DAG.viewGraph();
4301 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4305 RegisterScheduler::setDefault(Ctor);
4308 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4314 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4315 return new HazardRecognizer();
4318 //===----------------------------------------------------------------------===//
4319 // Helper functions used by the generated instruction selector.
4320 //===----------------------------------------------------------------------===//
4321 // Calls to these methods are generated by tblgen.
4323 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4324 /// the dag combiner simplified the 255, we still want to match. RHS is the
4325 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4326 /// specified in the .td file (e.g. 255).
4327 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4328 int64_t DesiredMaskS) {
4329 uint64_t ActualMask = RHS->getValue();
4330 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4332 // If the actual mask exactly matches, success!
4333 if (ActualMask == DesiredMask)
4336 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4337 if (ActualMask & ~DesiredMask)
4340 // Otherwise, the DAG Combiner may have proven that the value coming in is
4341 // either already zero or is not demanded. Check for known zero input bits.
4342 uint64_t NeededMask = DesiredMask & ~ActualMask;
4343 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4346 // TODO: check to see if missing bits are just not demanded.
4348 // Otherwise, this pattern doesn't match.
4352 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4353 /// the dag combiner simplified the 255, we still want to match. RHS is the
4354 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4355 /// specified in the .td file (e.g. 255).
4356 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4357 int64_t DesiredMaskS) {
4358 uint64_t ActualMask = RHS->getValue();
4359 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4361 // If the actual mask exactly matches, success!
4362 if (ActualMask == DesiredMask)
4365 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4366 if (ActualMask & ~DesiredMask)
4369 // Otherwise, the DAG Combiner may have proven that the value coming in is
4370 // either already zero or is not demanded. Check for known zero input bits.
4371 uint64_t NeededMask = DesiredMask & ~ActualMask;
4373 uint64_t KnownZero, KnownOne;
4374 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4376 // If all the missing bits in the or are already known to be set, match!
4377 if ((NeededMask & KnownOne) == NeededMask)
4380 // TODO: check to see if missing bits are just not demanded.
4382 // Otherwise, this pattern doesn't match.
4387 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4388 /// by tblgen. Others should not call it.
4389 void SelectionDAGISel::
4390 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4391 std::vector<SDOperand> InOps;
4392 std::swap(InOps, Ops);
4394 Ops.push_back(InOps[0]); // input chain.
4395 Ops.push_back(InOps[1]); // input asm string.
4397 unsigned i = 2, e = InOps.size();
4398 if (InOps[e-1].getValueType() == MVT::Flag)
4399 --e; // Don't process a flag operand if it is here.
4402 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4403 if ((Flags & 7) != 4 /*MEM*/) {
4404 // Just skip over this operand, copying the operands verbatim.
4405 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4406 i += (Flags >> 3) + 1;
4408 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4409 // Otherwise, this is a memory operand. Ask the target to select it.
4410 std::vector<SDOperand> SelOps;
4411 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4412 cerr << "Could not match memory address. Inline asm failure!\n";
4416 // Add this to the output node.
4417 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4419 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4424 // Add the flag input back if present.
4425 if (e != InOps.size())
4426 Ops.push_back(InOps.back());