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/MachineDebugInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SchedulerRegistry.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/CodeGen/SSARegMap.h"
35 #include "llvm/Target/MRegisterInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetFrameInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Debug.h"
45 #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()->getTypeAlignment(Ty),
250 // If the alignment of the value is smaller than the size of the
251 // value, and if the size of the value is particularly small
252 // (<= 8 bytes), round up to the size of the value for potentially
253 // better performance.
255 // FIXME: This could be made better with a preferred alignment hook in
256 // TargetData. It serves primarily to 8-byte align doubles for X86.
257 if (Align < TySize && TySize <= 8) Align = TySize;
258 TySize *= CUI->getZExtValue(); // Get total allocated size.
259 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
260 StaticAllocaMap[AI] =
261 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
264 for (; BB != EB; ++BB)
265 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
266 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
267 if (!isa<AllocaInst>(I) ||
268 !StaticAllocaMap.count(cast<AllocaInst>(I)))
269 InitializeRegForValue(I);
271 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
272 // also creates the initial PHI MachineInstrs, though none of the input
273 // operands are populated.
274 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
275 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
277 MF.getBasicBlockList().push_back(MBB);
279 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
282 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
283 if (PN->use_empty()) continue;
285 MVT::ValueType VT = TLI.getValueType(PN->getType());
286 unsigned NumElements;
287 if (VT != MVT::Vector)
288 NumElements = TLI.getNumElements(VT);
290 MVT::ValueType VT1,VT2;
292 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
295 unsigned PHIReg = ValueMap[PN];
296 assert(PHIReg && "PHI node does not have an assigned virtual register!");
297 for (unsigned i = 0; i != NumElements; ++i)
298 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
303 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
304 /// the correctly promoted or expanded types. Assign these registers
305 /// consecutive vreg numbers and return the first assigned number.
306 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
307 MVT::ValueType VT = TLI.getValueType(V->getType());
309 // The number of multiples of registers that we need, to, e.g., split up
310 // a <2 x int64> -> 4 x i32 registers.
311 unsigned NumVectorRegs = 1;
313 // If this is a packed type, figure out what type it will decompose into
314 // and how many of the elements it will use.
315 if (VT == MVT::Vector) {
316 const PackedType *PTy = cast<PackedType>(V->getType());
317 unsigned NumElts = PTy->getNumElements();
318 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
320 // Divide the input until we get to a supported size. This will always
321 // end with a scalar if the target doesn't support vectors.
322 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
329 VT = getVectorType(EltTy, NumElts);
332 // The common case is that we will only create one register for this
333 // value. If we have that case, create and return the virtual register.
334 unsigned NV = TLI.getNumElements(VT);
336 // If we are promoting this value, pick the next largest supported type.
337 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
338 unsigned Reg = MakeReg(PromotedType);
339 // If this is a vector of supported or promoted types (e.g. 4 x i16),
340 // create all of the registers.
341 for (unsigned i = 1; i != NumVectorRegs; ++i)
342 MakeReg(PromotedType);
346 // If this value is represented with multiple target registers, make sure
347 // to create enough consecutive registers of the right (smaller) type.
348 unsigned NT = VT-1; // Find the type to use.
349 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
352 unsigned R = MakeReg((MVT::ValueType)NT);
353 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
354 MakeReg((MVT::ValueType)NT);
358 //===----------------------------------------------------------------------===//
359 /// SelectionDAGLowering - This is the common target-independent lowering
360 /// implementation that is parameterized by a TargetLowering object.
361 /// Also, targets can overload any lowering method.
364 class SelectionDAGLowering {
365 MachineBasicBlock *CurMBB;
367 std::map<const Value*, SDOperand> NodeMap;
369 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
370 /// them up and then emit token factor nodes when possible. This allows us to
371 /// get simple disambiguation between loads without worrying about alias
373 std::vector<SDOperand> PendingLoads;
375 /// Case - A pair of values to record the Value for a switch case, and the
376 /// case's target basic block.
377 typedef std::pair<Constant*, MachineBasicBlock*> Case;
378 typedef std::vector<Case>::iterator CaseItr;
379 typedef std::pair<CaseItr, CaseItr> CaseRange;
381 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
382 /// of conditional branches.
384 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
385 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
387 /// CaseBB - The MBB in which to emit the compare and branch
388 MachineBasicBlock *CaseBB;
389 /// LT, GE - If nonzero, we know the current case value must be less-than or
390 /// greater-than-or-equal-to these Constants.
393 /// Range - A pair of iterators representing the range of case values to be
394 /// processed at this point in the binary search tree.
398 /// The comparison function for sorting Case values.
400 bool operator () (const Case& C1, const Case& C2) {
401 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
402 if (I1->getType()->isUnsigned())
403 return I1->getZExtValue() <
404 cast<const ConstantInt>(C2.first)->getZExtValue();
406 return cast<const ConstantInt>(C1.first)->getSExtValue() <
407 cast<const ConstantInt>(C2.first)->getSExtValue();
412 // TLI - This is information that describes the available target features we
413 // need for lowering. This indicates when operations are unavailable,
414 // implemented with a libcall, etc.
417 const TargetData *TD;
419 /// SwitchCases - Vector of CaseBlock structures used to communicate
420 /// SwitchInst code generation information.
421 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
422 SelectionDAGISel::JumpTable JT;
424 /// FuncInfo - Information about the function as a whole.
426 FunctionLoweringInfo &FuncInfo;
428 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
429 FunctionLoweringInfo &funcinfo)
430 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
431 JT(0,0,0,0), FuncInfo(funcinfo) {
434 /// getRoot - Return the current virtual root of the Selection DAG.
436 SDOperand getRoot() {
437 if (PendingLoads.empty())
438 return DAG.getRoot();
440 if (PendingLoads.size() == 1) {
441 SDOperand Root = PendingLoads[0];
443 PendingLoads.clear();
447 // Otherwise, we have to make a token factor node.
448 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
449 &PendingLoads[0], PendingLoads.size());
450 PendingLoads.clear();
455 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
457 void visit(Instruction &I) { visit(I.getOpcode(), I); }
459 void visit(unsigned Opcode, User &I) {
460 // Note: this doesn't use InstVisitor, because it has to work with
461 // ConstantExpr's in addition to instructions.
463 default: assert(0 && "Unknown instruction type encountered!");
465 // Build the switch statement using the Instruction.def file.
466 #define HANDLE_INST(NUM, OPCODE, CLASS) \
467 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
468 #include "llvm/Instruction.def"
472 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
474 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
475 const Value *SV, SDOperand Root,
478 SDOperand getIntPtrConstant(uint64_t Val) {
479 return DAG.getConstant(Val, TLI.getPointerTy());
482 SDOperand getValue(const Value *V);
484 const SDOperand &setValue(const Value *V, SDOperand NewN) {
485 SDOperand &N = NodeMap[V];
486 assert(N.Val == 0 && "Already set a value for this node!");
490 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
492 bool OutReg, bool InReg,
493 std::set<unsigned> &OutputRegs,
494 std::set<unsigned> &InputRegs);
496 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
497 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
499 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
500 void ExportFromCurrentBlock(Value *V);
502 // Terminator instructions.
503 void visitRet(ReturnInst &I);
504 void visitBr(BranchInst &I);
505 void visitSwitch(SwitchInst &I);
506 void visitUnreachable(UnreachableInst &I) { /* noop */ }
508 // Helper for visitSwitch
509 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
510 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
512 // These all get lowered before this pass.
513 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
514 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
516 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
517 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
518 void visitShift(User &I, unsigned Opcode);
519 void visitAdd(User &I) {
520 if (I.getType()->isFloatingPoint())
521 visitFPBinary(I, ISD::FADD, ISD::VADD);
523 visitIntBinary(I, ISD::ADD, ISD::VADD);
525 void visitSub(User &I);
526 void visitMul(User &I) {
527 if (I.getType()->isFloatingPoint())
528 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
530 visitIntBinary(I, ISD::MUL, ISD::VMUL);
532 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
533 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
534 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
535 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
536 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
537 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
538 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
539 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
540 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
541 void visitShl(User &I) { visitShift(I, ISD::SHL); }
542 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
543 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
544 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
545 ISD::CondCode FPOpc);
546 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
548 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
550 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
552 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
554 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
556 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
559 void visitExtractElement(User &I);
560 void visitInsertElement(User &I);
561 void visitShuffleVector(User &I);
563 void visitGetElementPtr(User &I);
564 void visitCast(User &I);
565 void visitSelect(User &I);
567 void visitMalloc(MallocInst &I);
568 void visitFree(FreeInst &I);
569 void visitAlloca(AllocaInst &I);
570 void visitLoad(LoadInst &I);
571 void visitStore(StoreInst &I);
572 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
573 void visitCall(CallInst &I);
574 void visitInlineAsm(CallInst &I);
575 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
576 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
578 void visitVAStart(CallInst &I);
579 void visitVAArg(VAArgInst &I);
580 void visitVAEnd(CallInst &I);
581 void visitVACopy(CallInst &I);
582 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
584 void visitMemIntrinsic(CallInst &I, unsigned Op);
586 void visitUserOp1(Instruction &I) {
587 assert(0 && "UserOp1 should not exist at instruction selection time!");
590 void visitUserOp2(Instruction &I) {
591 assert(0 && "UserOp2 should not exist at instruction selection time!");
595 } // end namespace llvm
597 SDOperand SelectionDAGLowering::getValue(const Value *V) {
598 SDOperand &N = NodeMap[V];
601 const Type *VTy = V->getType();
602 MVT::ValueType VT = TLI.getValueType(VTy);
603 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
604 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
605 visit(CE->getOpcode(), *CE);
606 assert(N.Val && "visit didn't populate the ValueMap!");
608 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
609 return N = DAG.getGlobalAddress(GV, VT);
610 } else if (isa<ConstantPointerNull>(C)) {
611 return N = DAG.getConstant(0, TLI.getPointerTy());
612 } else if (isa<UndefValue>(C)) {
613 if (!isa<PackedType>(VTy))
614 return N = DAG.getNode(ISD::UNDEF, VT);
616 // Create a VBUILD_VECTOR of undef nodes.
617 const PackedType *PTy = cast<PackedType>(VTy);
618 unsigned NumElements = PTy->getNumElements();
619 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
621 SmallVector<SDOperand, 8> Ops;
622 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
624 // Create a VConstant node with generic Vector type.
625 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
626 Ops.push_back(DAG.getValueType(PVT));
627 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
628 &Ops[0], Ops.size());
629 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
630 return N = DAG.getConstantFP(CFP->getValue(), VT);
631 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
632 unsigned NumElements = PTy->getNumElements();
633 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
635 // Now that we know the number and type of the elements, push a
636 // Constant or ConstantFP node onto the ops list for each element of
637 // the packed constant.
638 SmallVector<SDOperand, 8> Ops;
639 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
640 for (unsigned i = 0; i != NumElements; ++i)
641 Ops.push_back(getValue(CP->getOperand(i)));
643 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
645 if (MVT::isFloatingPoint(PVT))
646 Op = DAG.getConstantFP(0, PVT);
648 Op = DAG.getConstant(0, PVT);
649 Ops.assign(NumElements, Op);
652 // Create a VBUILD_VECTOR node with generic Vector type.
653 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
654 Ops.push_back(DAG.getValueType(PVT));
655 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
657 // Canonicalize all constant ints to be unsigned.
658 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
662 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
663 std::map<const AllocaInst*, int>::iterator SI =
664 FuncInfo.StaticAllocaMap.find(AI);
665 if (SI != FuncInfo.StaticAllocaMap.end())
666 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
669 std::map<const Value*, unsigned>::const_iterator VMI =
670 FuncInfo.ValueMap.find(V);
671 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
673 unsigned InReg = VMI->second;
675 // If this type is not legal, make it so now.
676 if (VT != MVT::Vector) {
677 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
679 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
681 // Source must be expanded. This input value is actually coming from the
682 // register pair VMI->second and VMI->second+1.
683 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
684 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
685 } else if (DestVT > VT) { // Promotion case
686 if (MVT::isFloatingPoint(VT))
687 N = DAG.getNode(ISD::FP_ROUND, VT, N);
689 N = DAG.getNode(ISD::TRUNCATE, VT, N);
692 // Otherwise, if this is a vector, make it available as a generic vector
694 MVT::ValueType PTyElementVT, PTyLegalElementVT;
695 const PackedType *PTy = cast<PackedType>(VTy);
696 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
699 // Build a VBUILD_VECTOR with the input registers.
700 SmallVector<SDOperand, 8> Ops;
701 if (PTyElementVT == PTyLegalElementVT) {
702 // If the value types are legal, just VBUILD the CopyFromReg nodes.
703 for (unsigned i = 0; i != NE; ++i)
704 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
706 } else if (PTyElementVT < PTyLegalElementVT) {
707 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
708 for (unsigned i = 0; i != NE; ++i) {
709 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
711 if (MVT::isFloatingPoint(PTyElementVT))
712 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
714 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
718 // If the register was expanded, use BUILD_PAIR.
719 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
720 for (unsigned i = 0; i != NE/2; ++i) {
721 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
723 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
725 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
729 Ops.push_back(DAG.getConstant(NE, MVT::i32));
730 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
731 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
733 // Finally, use a VBIT_CONVERT to make this available as the appropriate
735 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
736 DAG.getConstant(PTy->getNumElements(),
738 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
745 void SelectionDAGLowering::visitRet(ReturnInst &I) {
746 if (I.getNumOperands() == 0) {
747 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
750 SmallVector<SDOperand, 8> NewValues;
751 NewValues.push_back(getRoot());
752 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
753 SDOperand RetOp = getValue(I.getOperand(i));
754 bool isSigned = I.getOperand(i)->getType()->isSigned();
756 // If this is an integer return value, we need to promote it ourselves to
757 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
759 // FIXME: C calling convention requires the return type to be promoted to
760 // at least 32-bit. But this is not necessary for non-C calling conventions.
761 if (MVT::isInteger(RetOp.getValueType()) &&
762 RetOp.getValueType() < MVT::i64) {
763 MVT::ValueType TmpVT;
764 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
765 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
770 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
772 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
774 NewValues.push_back(RetOp);
775 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
777 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
778 &NewValues[0], NewValues.size()));
781 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
782 /// the current basic block, add it to ValueMap now so that we'll get a
784 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
785 // No need to export constants.
786 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
789 if (FuncInfo.isExportedInst(V)) return;
791 unsigned Reg = FuncInfo.InitializeRegForValue(V);
792 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
795 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
796 const BasicBlock *FromBB) {
797 // The operands of the setcc have to be in this block. We don't know
798 // how to export them from some other block.
799 if (Instruction *VI = dyn_cast<Instruction>(V)) {
800 // Can export from current BB.
801 if (VI->getParent() == FromBB)
804 // Is already exported, noop.
805 return FuncInfo.isExportedInst(V);
808 // If this is an argument, we can export it if the BB is the entry block or
809 // if it is already exported.
810 if (isa<Argument>(V)) {
811 if (FromBB == &FromBB->getParent()->getEntryBlock())
814 // Otherwise, can only export this if it is already exported.
815 return FuncInfo.isExportedInst(V);
818 // Otherwise, constants can always be exported.
822 static bool InBlock(const Value *V, const BasicBlock *BB) {
823 if (const Instruction *I = dyn_cast<Instruction>(V))
824 return I->getParent() == BB;
828 /// FindMergedConditions - If Cond is an expression like
829 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
830 MachineBasicBlock *TBB,
831 MachineBasicBlock *FBB,
832 MachineBasicBlock *CurBB,
834 // If this node is not part of the or/and tree, emit it as a branch.
835 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
837 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
838 BOp->getParent() != CurBB->getBasicBlock() ||
839 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
840 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
841 const BasicBlock *BB = CurBB->getBasicBlock();
843 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
844 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
845 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
846 // The operands of the setcc have to be in this block. We don't know
847 // how to export them from some other block. If this is the first
848 // block of the sequence, no exporting is needed.
850 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
851 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
852 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
853 II->getOperand(2), TBB, FBB, CurBB);
854 SwitchCases.push_back(CB);
859 // If the leaf of the tree is a setcond inst, merge the condition into the
861 if (BOp && isa<SetCondInst>(BOp) &&
862 // The operands of the setcc have to be in this block. We don't know
863 // how to export them from some other block. If this is the first block
864 // of the sequence, no exporting is needed.
866 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
867 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
868 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
869 switch (BOp->getOpcode()) {
870 default: assert(0 && "Unknown setcc opcode!");
871 case Instruction::SetEQ:
872 SignCond = ISD::SETEQ;
873 UnsCond = ISD::SETEQ;
874 FPCond = ISD::SETOEQ;
876 case Instruction::SetNE:
877 SignCond = ISD::SETNE;
878 UnsCond = ISD::SETNE;
879 FPCond = ISD::SETUNE;
881 case Instruction::SetLE:
882 SignCond = ISD::SETLE;
883 UnsCond = ISD::SETULE;
884 FPCond = ISD::SETOLE;
886 case Instruction::SetGE:
887 SignCond = ISD::SETGE;
888 UnsCond = ISD::SETUGE;
889 FPCond = ISD::SETOGE;
891 case Instruction::SetLT:
892 SignCond = ISD::SETLT;
893 UnsCond = ISD::SETULT;
894 FPCond = ISD::SETOLT;
896 case Instruction::SetGT:
897 SignCond = ISD::SETGT;
898 UnsCond = ISD::SETUGT;
899 FPCond = ISD::SETOGT;
903 const Type *OpType = BOp->getOperand(0)->getType();
904 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
905 OpType = PTy->getElementType();
907 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
909 else if (OpType->isUnsigned())
912 Condition = SignCond;
914 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
915 BOp->getOperand(1), TBB, FBB, CurBB);
916 SwitchCases.push_back(CB);
920 // Create a CaseBlock record representing this branch.
921 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
923 SwitchCases.push_back(CB);
928 // Create TmpBB after CurBB.
929 MachineFunction::iterator BBI = CurBB;
930 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
931 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
933 if (Opc == Instruction::Or) {
942 // Emit the LHS condition.
943 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
945 // Emit the RHS condition into TmpBB.
946 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
948 assert(Opc == Instruction::And && "Unknown merge op!");
956 // This requires creation of TmpBB after CurBB.
958 // Emit the LHS condition.
959 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
961 // Emit the RHS condition into TmpBB.
962 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
966 /// If the set of cases should be emitted as a series of branches, return true.
967 /// If we should emit this as a bunch of and/or'd together conditions, return
970 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
971 if (Cases.size() != 2) return true;
973 // If this is two comparisons of the same values or'd or and'd together, they
974 // will get folded into a single comparison, so don't emit two blocks.
975 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
976 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
977 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
978 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
985 void SelectionDAGLowering::visitBr(BranchInst &I) {
986 // Update machine-CFG edges.
987 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
989 // Figure out which block is immediately after the current one.
990 MachineBasicBlock *NextBlock = 0;
991 MachineFunction::iterator BBI = CurMBB;
992 if (++BBI != CurMBB->getParent()->end())
995 if (I.isUnconditional()) {
996 // If this is not a fall-through branch, emit the branch.
997 if (Succ0MBB != NextBlock)
998 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
999 DAG.getBasicBlock(Succ0MBB)));
1001 // Update machine-CFG edges.
1002 CurMBB->addSuccessor(Succ0MBB);
1007 // If this condition is one of the special cases we handle, do special stuff
1009 Value *CondVal = I.getCondition();
1010 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1012 // If this is a series of conditions that are or'd or and'd together, emit
1013 // this as a sequence of branches instead of setcc's with and/or operations.
1014 // For example, instead of something like:
1027 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1028 if (BOp->hasOneUse() &&
1029 (BOp->getOpcode() == Instruction::And ||
1030 BOp->getOpcode() == Instruction::Or)) {
1031 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1032 // If the compares in later blocks need to use values not currently
1033 // exported from this block, export them now. This block should always
1034 // be the first entry.
1035 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1037 // Allow some cases to be rejected.
1038 if (ShouldEmitAsBranches(SwitchCases)) {
1039 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1040 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1041 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1044 // Emit the branch for this block.
1045 visitSwitchCase(SwitchCases[0]);
1046 SwitchCases.erase(SwitchCases.begin());
1050 // Okay, we decided not to do this, remove any inserted MBB's and clear
1052 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1053 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1055 SwitchCases.clear();
1059 // Create a CaseBlock record representing this branch.
1060 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
1061 Succ0MBB, Succ1MBB, CurMBB);
1062 // Use visitSwitchCase to actually insert the fast branch sequence for this
1064 visitSwitchCase(CB);
1067 /// visitSwitchCase - Emits the necessary code to represent a single node in
1068 /// the binary search tree resulting from lowering a switch instruction.
1069 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1071 SDOperand CondLHS = getValue(CB.CmpLHS);
1073 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1074 // handle common cases produced by branch lowering.
1075 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
1077 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1078 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1079 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1081 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1083 // Set NextBlock to be the MBB immediately after the current one, if any.
1084 // This is used to avoid emitting unnecessary branches to the next block.
1085 MachineBasicBlock *NextBlock = 0;
1086 MachineFunction::iterator BBI = CurMBB;
1087 if (++BBI != CurMBB->getParent()->end())
1090 // If the lhs block is the next block, invert the condition so that we can
1091 // fall through to the lhs instead of the rhs block.
1092 if (CB.TrueBB == NextBlock) {
1093 std::swap(CB.TrueBB, CB.FalseBB);
1094 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1095 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1097 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1098 DAG.getBasicBlock(CB.TrueBB));
1099 if (CB.FalseBB == NextBlock)
1100 DAG.setRoot(BrCond);
1102 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1103 DAG.getBasicBlock(CB.FalseBB)));
1104 // Update successor info
1105 CurMBB->addSuccessor(CB.TrueBB);
1106 CurMBB->addSuccessor(CB.FalseBB);
1109 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1110 // Emit the code for the jump table
1111 MVT::ValueType PTy = TLI.getPointerTy();
1112 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1113 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1114 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1119 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1120 // Figure out which block is immediately after the current one.
1121 MachineBasicBlock *NextBlock = 0;
1122 MachineFunction::iterator BBI = CurMBB;
1124 if (++BBI != CurMBB->getParent()->end())
1127 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1129 // If there is only the default destination, branch to it if it is not the
1130 // next basic block. Otherwise, just fall through.
1131 if (I.getNumOperands() == 2) {
1132 // Update machine-CFG edges.
1134 // If this is not a fall-through branch, emit the branch.
1135 if (Default != NextBlock)
1136 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1137 DAG.getBasicBlock(Default)));
1139 CurMBB->addSuccessor(Default);
1143 // If there are any non-default case statements, create a vector of Cases
1144 // representing each one, and sort the vector so that we can efficiently
1145 // create a binary search tree from them.
1146 std::vector<Case> Cases;
1148 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1149 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1150 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1153 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1155 // Get the Value to be switched on and default basic blocks, which will be
1156 // inserted into CaseBlock records, representing basic blocks in the binary
1158 Value *SV = I.getOperand(0);
1160 // Get the MachineFunction which holds the current MBB. This is used during
1161 // emission of jump tables, and when inserting any additional MBBs necessary
1162 // to represent the switch.
1163 MachineFunction *CurMF = CurMBB->getParent();
1164 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
1166 // If the switch has few cases (two or less) emit a series of specific
1168 if (Cases.size() < 3) {
1169 // TODO: If any two of the cases has the same destination, and if one value
1170 // is the same as the other, but has one bit unset that the other has set,
1171 // use bit manipulation to do two compares at once. For example:
1172 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1174 // Rearrange the case blocks so that the last one falls through if possible.
1175 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1176 // The last case block won't fall through into 'NextBlock' if we emit the
1177 // branches in this order. See if rearranging a case value would help.
1178 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1179 if (Cases[i].second == NextBlock) {
1180 std::swap(Cases[i], Cases.back());
1186 // Create a CaseBlock record representing a conditional branch to
1187 // the Case's target mbb if the value being switched on SV is equal
1189 MachineBasicBlock *CurBlock = CurMBB;
1190 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1191 MachineBasicBlock *FallThrough;
1193 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1194 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1196 // If the last case doesn't match, go to the default block.
1197 FallThrough = Default;
1200 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1201 Cases[i].second, FallThrough, CurBlock);
1203 // If emitting the first comparison, just call visitSwitchCase to emit the
1204 // code into the current block. Otherwise, push the CaseBlock onto the
1205 // vector to be later processed by SDISel, and insert the node's MBB
1206 // before the next MBB.
1207 if (CurBlock == CurMBB)
1208 visitSwitchCase(CB);
1210 SwitchCases.push_back(CB);
1212 CurBlock = FallThrough;
1217 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1218 // target supports indirect branches, then emit a jump table rather than
1219 // lowering the switch to a binary tree of conditional branches.
1220 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1221 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
1223 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1224 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
1225 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1227 if (Density >= 0.3125) {
1228 // Create a new basic block to hold the code for loading the address
1229 // of the jump table, and jumping to it. Update successor information;
1230 // we will either branch to the default case for the switch, or the jump
1232 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1233 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1234 CurMBB->addSuccessor(Default);
1235 CurMBB->addSuccessor(JumpTableBB);
1237 // Subtract the lowest switch case value from the value being switched on
1238 // and conditional branch to default mbb if the result is greater than the
1239 // difference between smallest and largest cases.
1240 SDOperand SwitchOp = getValue(SV);
1241 MVT::ValueType VT = SwitchOp.getValueType();
1242 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1243 DAG.getConstant(First, VT));
1245 // The SDNode we just created, which holds the value being switched on
1246 // minus the the smallest case value, needs to be copied to a virtual
1247 // register so it can be used as an index into the jump table in a
1248 // subsequent basic block. This value may be smaller or larger than the
1249 // target's pointer type, and therefore require extension or truncating.
1250 if (VT > TLI.getPointerTy())
1251 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1253 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1255 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1256 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1258 // Emit the range check for the jump table, and branch to the default
1259 // block for the switch statement if the value being switched on exceeds
1260 // the largest case in the switch.
1261 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1262 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1263 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1264 DAG.getBasicBlock(Default)));
1266 // Build a vector of destination BBs, corresponding to each target
1267 // of the jump table. If the value of the jump table slot corresponds to
1268 // a case statement, push the case's BB onto the vector, otherwise, push
1270 std::vector<MachineBasicBlock*> DestBBs;
1271 uint64_t TEI = First;
1272 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
1273 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
1274 DestBBs.push_back(ii->second);
1277 DestBBs.push_back(Default);
1280 // Update successor info. Add one edge to each unique successor.
1281 // Vector bool would be better, but vector<bool> is really slow.
1282 std::vector<unsigned char> SuccsHandled;
1283 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1285 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1286 E = DestBBs.end(); I != E; ++I) {
1287 if (!SuccsHandled[(*I)->getNumber()]) {
1288 SuccsHandled[(*I)->getNumber()] = true;
1289 JumpTableBB->addSuccessor(*I);
1293 // Create a jump table index for this jump table, or return an existing
1295 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1297 // Set the jump table information so that we can codegen it as a second
1298 // MachineBasicBlock
1299 JT.Reg = JumpTableReg;
1301 JT.MBB = JumpTableBB;
1302 JT.Default = Default;
1307 // Push the initial CaseRec onto the worklist
1308 std::vector<CaseRec> CaseVec;
1309 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1311 while (!CaseVec.empty()) {
1312 // Grab a record representing a case range to process off the worklist
1313 CaseRec CR = CaseVec.back();
1316 // Size is the number of Cases represented by this range. If Size is 1,
1317 // then we are processing a leaf of the binary search tree. Otherwise,
1318 // we need to pick a pivot, and push left and right ranges onto the
1320 unsigned Size = CR.Range.second - CR.Range.first;
1323 // Create a CaseBlock record representing a conditional branch to
1324 // the Case's target mbb if the value being switched on SV is equal
1325 // to C. Otherwise, branch to default.
1326 Constant *C = CR.Range.first->first;
1327 MachineBasicBlock *Target = CR.Range.first->second;
1328 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1331 // If the MBB representing the leaf node is the current MBB, then just
1332 // call visitSwitchCase to emit the code into the current block.
1333 // Otherwise, push the CaseBlock onto the vector to be later processed
1334 // by SDISel, and insert the node's MBB before the next MBB.
1335 if (CR.CaseBB == CurMBB)
1336 visitSwitchCase(CB);
1338 SwitchCases.push_back(CB);
1340 // split case range at pivot
1341 CaseItr Pivot = CR.Range.first + (Size / 2);
1342 CaseRange LHSR(CR.Range.first, Pivot);
1343 CaseRange RHSR(Pivot, CR.Range.second);
1344 Constant *C = Pivot->first;
1345 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1347 // We know that we branch to the LHS if the Value being switched on is
1348 // less than the Pivot value, C. We use this to optimize our binary
1349 // tree a bit, by recognizing that if SV is greater than or equal to the
1350 // LHS's Case Value, and that Case Value is exactly one less than the
1351 // Pivot's Value, then we can branch directly to the LHS's Target,
1352 // rather than creating a leaf node for it.
1353 if ((LHSR.second - LHSR.first) == 1 &&
1354 LHSR.first->first == CR.GE &&
1355 cast<ConstantIntegral>(C)->getZExtValue() ==
1356 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
1357 TrueBB = LHSR.first->second;
1359 TrueBB = new MachineBasicBlock(LLVMBB);
1360 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1361 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1364 // Similar to the optimization above, if the Value being switched on is
1365 // known to be less than the Constant CR.LT, and the current Case Value
1366 // is CR.LT - 1, then we can branch directly to the target block for
1367 // the current Case Value, rather than emitting a RHS leaf node for it.
1368 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1369 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1370 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
1371 FalseBB = RHSR.first->second;
1373 FalseBB = new MachineBasicBlock(LLVMBB);
1374 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1375 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1378 // Create a CaseBlock record representing a conditional branch to
1379 // the LHS node if the value being switched on SV is less than C.
1380 // Otherwise, branch to LHS.
1381 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1382 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
1384 if (CR.CaseBB == CurMBB)
1385 visitSwitchCase(CB);
1387 SwitchCases.push_back(CB);
1392 void SelectionDAGLowering::visitSub(User &I) {
1393 // -0.0 - X --> fneg
1394 if (I.getType()->isFloatingPoint()) {
1395 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1396 if (CFP->isExactlyValue(-0.0)) {
1397 SDOperand Op2 = getValue(I.getOperand(1));
1398 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1401 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1403 visitIntBinary(I, ISD::SUB, ISD::VSUB);
1407 SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
1408 const Type *Ty = I.getType();
1409 SDOperand Op1 = getValue(I.getOperand(0));
1410 SDOperand Op2 = getValue(I.getOperand(1));
1412 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1413 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1414 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1415 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1417 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1422 SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1423 const Type *Ty = I.getType();
1424 SDOperand Op1 = getValue(I.getOperand(0));
1425 SDOperand Op2 = getValue(I.getOperand(1));
1427 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1428 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1429 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1430 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1432 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1436 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1437 SDOperand Op1 = getValue(I.getOperand(0));
1438 SDOperand Op2 = getValue(I.getOperand(1));
1440 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1442 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1445 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
1446 ISD::CondCode UnsignedOpcode,
1447 ISD::CondCode FPOpcode) {
1448 SDOperand Op1 = getValue(I.getOperand(0));
1449 SDOperand Op2 = getValue(I.getOperand(1));
1450 ISD::CondCode Opcode = SignedOpcode;
1451 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
1453 else if (I.getOperand(0)->getType()->isUnsigned())
1454 Opcode = UnsignedOpcode;
1455 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1458 void SelectionDAGLowering::visitSelect(User &I) {
1459 SDOperand Cond = getValue(I.getOperand(0));
1460 SDOperand TrueVal = getValue(I.getOperand(1));
1461 SDOperand FalseVal = getValue(I.getOperand(2));
1462 if (!isa<PackedType>(I.getType())) {
1463 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1464 TrueVal, FalseVal));
1466 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1467 *(TrueVal.Val->op_end()-2),
1468 *(TrueVal.Val->op_end()-1)));
1472 void SelectionDAGLowering::visitCast(User &I) {
1473 SDOperand N = getValue(I.getOperand(0));
1474 MVT::ValueType SrcVT = N.getValueType();
1475 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1477 if (DestVT == MVT::Vector) {
1478 // This is a cast to a vector from something else. This is always a bit
1479 // convert. Get information about the input vector.
1480 const PackedType *DestTy = cast<PackedType>(I.getType());
1481 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1482 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1483 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1484 DAG.getValueType(EltVT)));
1485 } else if (SrcVT == DestVT) {
1486 setValue(&I, N); // noop cast.
1487 } else if (DestVT == MVT::i1) {
1488 // Cast to bool is a comparison against zero, not truncation to zero.
1489 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1490 DAG.getConstantFP(0.0, N.getValueType());
1491 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1492 } else if (isInteger(SrcVT)) {
1493 if (isInteger(DestVT)) { // Int -> Int cast
1494 if (DestVT < SrcVT) // Truncating cast?
1495 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1496 else if (I.getOperand(0)->getType()->isSigned())
1497 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1499 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1500 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
1501 if (I.getOperand(0)->getType()->isSigned())
1502 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1504 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1506 assert(0 && "Unknown cast!");
1508 } else if (isFloatingPoint(SrcVT)) {
1509 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1510 if (DestVT < SrcVT) // Rounding cast?
1511 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1513 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1514 } else if (isInteger(DestVT)) { // FP -> Int cast.
1515 if (I.getType()->isSigned())
1516 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1518 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1520 assert(0 && "Unknown cast!");
1523 assert(SrcVT == MVT::Vector && "Unknown cast!");
1524 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1525 // This is a cast from a vector to something else. This is always a bit
1526 // convert. Get information about the input vector.
1527 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1531 void SelectionDAGLowering::visitInsertElement(User &I) {
1532 SDOperand InVec = getValue(I.getOperand(0));
1533 SDOperand InVal = getValue(I.getOperand(1));
1534 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1535 getValue(I.getOperand(2)));
1537 SDOperand Num = *(InVec.Val->op_end()-2);
1538 SDOperand Typ = *(InVec.Val->op_end()-1);
1539 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1540 InVec, InVal, InIdx, Num, Typ));
1543 void SelectionDAGLowering::visitExtractElement(User &I) {
1544 SDOperand InVec = getValue(I.getOperand(0));
1545 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1546 getValue(I.getOperand(1)));
1547 SDOperand Typ = *(InVec.Val->op_end()-1);
1548 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1549 TLI.getValueType(I.getType()), InVec, InIdx));
1552 void SelectionDAGLowering::visitShuffleVector(User &I) {
1553 SDOperand V1 = getValue(I.getOperand(0));
1554 SDOperand V2 = getValue(I.getOperand(1));
1555 SDOperand Mask = getValue(I.getOperand(2));
1557 SDOperand Num = *(V1.Val->op_end()-2);
1558 SDOperand Typ = *(V2.Val->op_end()-1);
1559 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1560 V1, V2, Mask, Num, Typ));
1564 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1565 SDOperand N = getValue(I.getOperand(0));
1566 const Type *Ty = I.getOperand(0)->getType();
1568 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1571 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1572 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
1575 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1576 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1577 getIntPtrConstant(Offset));
1579 Ty = StTy->getElementType(Field);
1581 Ty = cast<SequentialType>(Ty)->getElementType();
1583 // If this is a constant subscript, handle it quickly.
1584 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1585 if (CI->getZExtValue() == 0) continue;
1587 if (CI->getType()->isSigned())
1589 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
1592 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
1593 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1597 // N = N + Idx * ElementSize;
1598 uint64_t ElementSize = TD->getTypeSize(Ty);
1599 SDOperand IdxN = getValue(Idx);
1601 // If the index is smaller or larger than intptr_t, truncate or extend
1603 if (IdxN.getValueType() < N.getValueType()) {
1604 if (Idx->getType()->isSigned())
1605 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1607 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1608 } else if (IdxN.getValueType() > N.getValueType())
1609 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1611 // If this is a multiply by a power of two, turn it into a shl
1612 // immediately. This is a very common case.
1613 if (isPowerOf2_64(ElementSize)) {
1614 unsigned Amt = Log2_64(ElementSize);
1615 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1616 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1617 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1621 SDOperand Scale = getIntPtrConstant(ElementSize);
1622 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1623 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1629 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1630 // If this is a fixed sized alloca in the entry block of the function,
1631 // allocate it statically on the stack.
1632 if (FuncInfo.StaticAllocaMap.count(&I))
1633 return; // getValue will auto-populate this.
1635 const Type *Ty = I.getAllocatedType();
1636 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1637 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
1640 SDOperand AllocSize = getValue(I.getArraySize());
1641 MVT::ValueType IntPtr = TLI.getPointerTy();
1642 if (IntPtr < AllocSize.getValueType())
1643 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1644 else if (IntPtr > AllocSize.getValueType())
1645 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1647 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1648 getIntPtrConstant(TySize));
1650 // Handle alignment. If the requested alignment is less than or equal to the
1651 // stack alignment, ignore it and round the size of the allocation up to the
1652 // stack alignment size. If the size is greater than the stack alignment, we
1653 // note this in the DYNAMIC_STACKALLOC node.
1654 unsigned StackAlign =
1655 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1656 if (Align <= StackAlign) {
1658 // Add SA-1 to the size.
1659 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1660 getIntPtrConstant(StackAlign-1));
1661 // Mask out the low bits for alignment purposes.
1662 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1663 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1666 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
1667 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1669 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
1670 DAG.setRoot(setValue(&I, DSA).getValue(1));
1672 // Inform the Frame Information that we have just allocated a variable-sized
1674 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1677 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1678 SDOperand Ptr = getValue(I.getOperand(0));
1684 // Do not serialize non-volatile loads against each other.
1685 Root = DAG.getRoot();
1688 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
1689 Root, I.isVolatile()));
1692 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1693 const Value *SV, SDOperand Root,
1696 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1697 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1698 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1699 DAG.getSrcValue(SV));
1701 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
1705 DAG.setRoot(L.getValue(1));
1707 PendingLoads.push_back(L.getValue(1));
1713 void SelectionDAGLowering::visitStore(StoreInst &I) {
1714 Value *SrcV = I.getOperand(0);
1715 SDOperand Src = getValue(SrcV);
1716 SDOperand Ptr = getValue(I.getOperand(1));
1717 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1721 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1722 /// access memory and has no other side effects at all.
1723 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1724 #define GET_NO_MEMORY_INTRINSICS
1725 #include "llvm/Intrinsics.gen"
1726 #undef GET_NO_MEMORY_INTRINSICS
1730 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1731 // have any side-effects or if it only reads memory.
1732 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1733 #define GET_SIDE_EFFECT_INFO
1734 #include "llvm/Intrinsics.gen"
1735 #undef GET_SIDE_EFFECT_INFO
1739 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1741 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1742 unsigned Intrinsic) {
1743 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1744 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1746 // Build the operand list.
1747 SmallVector<SDOperand, 8> Ops;
1748 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1750 // We don't need to serialize loads against other loads.
1751 Ops.push_back(DAG.getRoot());
1753 Ops.push_back(getRoot());
1757 // Add the intrinsic ID as an integer operand.
1758 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1760 // Add all operands of the call to the operand list.
1761 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1762 SDOperand Op = getValue(I.getOperand(i));
1764 // If this is a vector type, force it to the right packed type.
1765 if (Op.getValueType() == MVT::Vector) {
1766 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1767 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1769 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1770 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1771 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1774 assert(TLI.isTypeLegal(Op.getValueType()) &&
1775 "Intrinsic uses a non-legal type?");
1779 std::vector<MVT::ValueType> VTs;
1780 if (I.getType() != Type::VoidTy) {
1781 MVT::ValueType VT = TLI.getValueType(I.getType());
1782 if (VT == MVT::Vector) {
1783 const PackedType *DestTy = cast<PackedType>(I.getType());
1784 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1786 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1787 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1790 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1794 VTs.push_back(MVT::Other);
1796 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1801 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1802 &Ops[0], Ops.size());
1803 else if (I.getType() != Type::VoidTy)
1804 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1805 &Ops[0], Ops.size());
1807 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1808 &Ops[0], Ops.size());
1811 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1813 PendingLoads.push_back(Chain);
1817 if (I.getType() != Type::VoidTy) {
1818 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1819 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1820 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1821 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1822 DAG.getValueType(EVT));
1824 setValue(&I, Result);
1828 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1829 /// we want to emit this as a call to a named external function, return the name
1830 /// otherwise lower it and return null.
1832 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1833 switch (Intrinsic) {
1835 // By default, turn this into a target intrinsic node.
1836 visitTargetIntrinsic(I, Intrinsic);
1838 case Intrinsic::vastart: visitVAStart(I); return 0;
1839 case Intrinsic::vaend: visitVAEnd(I); return 0;
1840 case Intrinsic::vacopy: visitVACopy(I); return 0;
1841 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1842 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1843 case Intrinsic::setjmp:
1844 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1846 case Intrinsic::longjmp:
1847 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1849 case Intrinsic::memcpy_i32:
1850 case Intrinsic::memcpy_i64:
1851 visitMemIntrinsic(I, ISD::MEMCPY);
1853 case Intrinsic::memset_i32:
1854 case Intrinsic::memset_i64:
1855 visitMemIntrinsic(I, ISD::MEMSET);
1857 case Intrinsic::memmove_i32:
1858 case Intrinsic::memmove_i64:
1859 visitMemIntrinsic(I, ISD::MEMMOVE);
1862 case Intrinsic::dbg_stoppoint: {
1863 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1864 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1865 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1869 Ops[1] = getValue(SPI.getLineValue());
1870 Ops[2] = getValue(SPI.getColumnValue());
1872 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1873 assert(DD && "Not a debug information descriptor");
1874 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1876 Ops[3] = DAG.getString(CompileUnit->getFileName());
1877 Ops[4] = DAG.getString(CompileUnit->getDirectory());
1879 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
1884 case Intrinsic::dbg_region_start: {
1885 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1886 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1887 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1888 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1889 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1890 DAG.getConstant(LabelID, MVT::i32)));
1895 case Intrinsic::dbg_region_end: {
1896 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1897 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1898 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1899 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1900 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1901 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
1906 case Intrinsic::dbg_func_start: {
1907 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1908 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1909 if (DebugInfo && FSI.getSubprogram() &&
1910 DebugInfo->Verify(FSI.getSubprogram())) {
1911 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1912 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1913 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
1918 case Intrinsic::dbg_declare: {
1919 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1920 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1921 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1922 SDOperand AddressOp = getValue(DI.getAddress());
1923 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
1924 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1930 case Intrinsic::isunordered_f32:
1931 case Intrinsic::isunordered_f64:
1932 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1933 getValue(I.getOperand(2)), ISD::SETUO));
1936 case Intrinsic::sqrt_f32:
1937 case Intrinsic::sqrt_f64:
1938 setValue(&I, DAG.getNode(ISD::FSQRT,
1939 getValue(I.getOperand(1)).getValueType(),
1940 getValue(I.getOperand(1))));
1942 case Intrinsic::powi_f32:
1943 case Intrinsic::powi_f64:
1944 setValue(&I, DAG.getNode(ISD::FPOWI,
1945 getValue(I.getOperand(1)).getValueType(),
1946 getValue(I.getOperand(1)),
1947 getValue(I.getOperand(2))));
1949 case Intrinsic::pcmarker: {
1950 SDOperand Tmp = getValue(I.getOperand(1));
1951 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1954 case Intrinsic::readcyclecounter: {
1955 SDOperand Op = getRoot();
1956 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1957 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1960 DAG.setRoot(Tmp.getValue(1));
1963 case Intrinsic::bswap_i16:
1964 case Intrinsic::bswap_i32:
1965 case Intrinsic::bswap_i64:
1966 setValue(&I, DAG.getNode(ISD::BSWAP,
1967 getValue(I.getOperand(1)).getValueType(),
1968 getValue(I.getOperand(1))));
1970 case Intrinsic::cttz_i8:
1971 case Intrinsic::cttz_i16:
1972 case Intrinsic::cttz_i32:
1973 case Intrinsic::cttz_i64:
1974 setValue(&I, DAG.getNode(ISD::CTTZ,
1975 getValue(I.getOperand(1)).getValueType(),
1976 getValue(I.getOperand(1))));
1978 case Intrinsic::ctlz_i8:
1979 case Intrinsic::ctlz_i16:
1980 case Intrinsic::ctlz_i32:
1981 case Intrinsic::ctlz_i64:
1982 setValue(&I, DAG.getNode(ISD::CTLZ,
1983 getValue(I.getOperand(1)).getValueType(),
1984 getValue(I.getOperand(1))));
1986 case Intrinsic::ctpop_i8:
1987 case Intrinsic::ctpop_i16:
1988 case Intrinsic::ctpop_i32:
1989 case Intrinsic::ctpop_i64:
1990 setValue(&I, DAG.getNode(ISD::CTPOP,
1991 getValue(I.getOperand(1)).getValueType(),
1992 getValue(I.getOperand(1))));
1994 case Intrinsic::stacksave: {
1995 SDOperand Op = getRoot();
1996 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1997 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
1999 DAG.setRoot(Tmp.getValue(1));
2002 case Intrinsic::stackrestore: {
2003 SDOperand Tmp = getValue(I.getOperand(1));
2004 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2007 case Intrinsic::prefetch:
2008 // FIXME: Currently discarding prefetches.
2014 void SelectionDAGLowering::visitCall(CallInst &I) {
2015 const char *RenameFn = 0;
2016 if (Function *F = I.getCalledFunction()) {
2017 if (F->isExternal())
2018 if (unsigned IID = F->getIntrinsicID()) {
2019 RenameFn = visitIntrinsicCall(I, IID);
2022 } else { // Not an LLVM intrinsic.
2023 const std::string &Name = F->getName();
2024 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2025 if (I.getNumOperands() == 3 && // Basic sanity checks.
2026 I.getOperand(1)->getType()->isFloatingPoint() &&
2027 I.getType() == I.getOperand(1)->getType() &&
2028 I.getType() == I.getOperand(2)->getType()) {
2029 SDOperand LHS = getValue(I.getOperand(1));
2030 SDOperand RHS = getValue(I.getOperand(2));
2031 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2035 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2036 if (I.getNumOperands() == 2 && // Basic sanity checks.
2037 I.getOperand(1)->getType()->isFloatingPoint() &&
2038 I.getType() == I.getOperand(1)->getType()) {
2039 SDOperand Tmp = getValue(I.getOperand(1));
2040 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2043 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2044 if (I.getNumOperands() == 2 && // Basic sanity checks.
2045 I.getOperand(1)->getType()->isFloatingPoint() &&
2046 I.getType() == I.getOperand(1)->getType()) {
2047 SDOperand Tmp = getValue(I.getOperand(1));
2048 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2051 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2052 if (I.getNumOperands() == 2 && // Basic sanity checks.
2053 I.getOperand(1)->getType()->isFloatingPoint() &&
2054 I.getType() == I.getOperand(1)->getType()) {
2055 SDOperand Tmp = getValue(I.getOperand(1));
2056 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2061 } else if (isa<InlineAsm>(I.getOperand(0))) {
2068 Callee = getValue(I.getOperand(0));
2070 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2071 std::vector<std::pair<SDOperand, const Type*> > Args;
2072 Args.reserve(I.getNumOperands());
2073 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2074 Value *Arg = I.getOperand(i);
2075 SDOperand ArgNode = getValue(Arg);
2076 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2079 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2080 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2082 std::pair<SDOperand,SDOperand> Result =
2083 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
2084 I.isTailCall(), Callee, Args, DAG);
2085 if (I.getType() != Type::VoidTy)
2086 setValue(&I, Result.first);
2087 DAG.setRoot(Result.second);
2090 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2091 SDOperand &Chain, SDOperand &Flag)const{
2092 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2093 Chain = Val.getValue(1);
2094 Flag = Val.getValue(2);
2096 // If the result was expanded, copy from the top part.
2097 if (Regs.size() > 1) {
2098 assert(Regs.size() == 2 &&
2099 "Cannot expand to more than 2 elts yet!");
2100 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2101 Chain = Hi.getValue(1);
2102 Flag = Hi.getValue(2);
2103 if (DAG.getTargetLoweringInfo().isLittleEndian())
2104 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2106 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2109 // Otherwise, if the return value was promoted or extended, truncate it to the
2110 // appropriate type.
2111 if (RegVT == ValueVT)
2114 if (MVT::isInteger(RegVT)) {
2115 if (ValueVT < RegVT)
2116 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2118 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2120 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2124 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2125 /// specified value into the registers specified by this object. This uses
2126 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2127 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2128 SDOperand &Chain, SDOperand &Flag,
2129 MVT::ValueType PtrVT) const {
2130 if (Regs.size() == 1) {
2131 // If there is a single register and the types differ, this must be
2133 if (RegVT != ValueVT) {
2134 if (MVT::isInteger(RegVT)) {
2135 if (RegVT < ValueVT)
2136 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2138 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2140 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2142 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2143 Flag = Chain.getValue(1);
2145 std::vector<unsigned> R(Regs);
2146 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2147 std::reverse(R.begin(), R.end());
2149 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2150 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2151 DAG.getConstant(i, PtrVT));
2152 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2153 Flag = Chain.getValue(1);
2158 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2159 /// operand list. This adds the code marker and includes the number of
2160 /// values added into it.
2161 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2162 std::vector<SDOperand> &Ops) const {
2163 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2164 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2165 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2168 /// isAllocatableRegister - If the specified register is safe to allocate,
2169 /// i.e. it isn't a stack pointer or some other special register, return the
2170 /// register class for the register. Otherwise, return null.
2171 static const TargetRegisterClass *
2172 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2173 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2174 MVT::ValueType FoundVT = MVT::Other;
2175 const TargetRegisterClass *FoundRC = 0;
2176 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2177 E = MRI->regclass_end(); RCI != E; ++RCI) {
2178 MVT::ValueType ThisVT = MVT::Other;
2180 const TargetRegisterClass *RC = *RCI;
2181 // If none of the the value types for this register class are valid, we
2182 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2183 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2185 if (TLI.isTypeLegal(*I)) {
2186 // If we have already found this register in a different register class,
2187 // choose the one with the largest VT specified. For example, on
2188 // PowerPC, we favor f64 register classes over f32.
2189 if (FoundVT == MVT::Other ||
2190 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2197 if (ThisVT == MVT::Other) continue;
2199 // NOTE: This isn't ideal. In particular, this might allocate the
2200 // frame pointer in functions that need it (due to them not being taken
2201 // out of allocation, because a variable sized allocation hasn't been seen
2202 // yet). This is a slight code pessimization, but should still work.
2203 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2204 E = RC->allocation_order_end(MF); I != E; ++I)
2206 // We found a matching register class. Keep looking at others in case
2207 // we find one with larger registers that this physreg is also in.
2216 RegsForValue SelectionDAGLowering::
2217 GetRegistersForValue(const std::string &ConstrCode,
2218 MVT::ValueType VT, bool isOutReg, bool isInReg,
2219 std::set<unsigned> &OutputRegs,
2220 std::set<unsigned> &InputRegs) {
2221 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2222 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2223 std::vector<unsigned> Regs;
2225 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2226 MVT::ValueType RegVT;
2227 MVT::ValueType ValueVT = VT;
2229 // If this is a constraint for a specific physical register, like {r17},
2231 if (PhysReg.first) {
2232 if (VT == MVT::Other)
2233 ValueVT = *PhysReg.second->vt_begin();
2235 // Get the actual register value type. This is important, because the user
2236 // may have asked for (e.g.) the AX register in i32 type. We need to
2237 // remember that AX is actually i16 to get the right extension.
2238 RegVT = *PhysReg.second->vt_begin();
2240 // This is a explicit reference to a physical register.
2241 Regs.push_back(PhysReg.first);
2243 // If this is an expanded reference, add the rest of the regs to Regs.
2245 TargetRegisterClass::iterator I = PhysReg.second->begin();
2246 TargetRegisterClass::iterator E = PhysReg.second->end();
2247 for (; *I != PhysReg.first; ++I)
2248 assert(I != E && "Didn't find reg!");
2250 // Already added the first reg.
2252 for (; NumRegs; --NumRegs, ++I) {
2253 assert(I != E && "Ran out of registers to allocate!");
2257 return RegsForValue(Regs, RegVT, ValueVT);
2260 // Otherwise, if this was a reference to an LLVM register class, create vregs
2261 // for this reference.
2262 std::vector<unsigned> RegClassRegs;
2263 if (PhysReg.second) {
2264 // If this is an early clobber or tied register, our regalloc doesn't know
2265 // how to maintain the constraint. If it isn't, go ahead and create vreg
2266 // and let the regalloc do the right thing.
2267 if (!isOutReg || !isInReg) {
2268 if (VT == MVT::Other)
2269 ValueVT = *PhysReg.second->vt_begin();
2270 RegVT = *PhysReg.second->vt_begin();
2272 // Create the appropriate number of virtual registers.
2273 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2274 for (; NumRegs; --NumRegs)
2275 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2277 return RegsForValue(Regs, RegVT, ValueVT);
2280 // Otherwise, we can't allocate it. Let the code below figure out how to
2281 // maintain these constraints.
2282 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2285 // This is a reference to a register class that doesn't directly correspond
2286 // to an LLVM register class. Allocate NumRegs consecutive, available,
2287 // registers from the class.
2288 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2291 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2292 MachineFunction &MF = *CurMBB->getParent();
2293 unsigned NumAllocated = 0;
2294 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2295 unsigned Reg = RegClassRegs[i];
2296 // See if this register is available.
2297 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2298 (isInReg && InputRegs.count(Reg))) { // Already used.
2299 // Make sure we find consecutive registers.
2304 // Check to see if this register is allocatable (i.e. don't give out the
2306 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
2308 // Make sure we find consecutive registers.
2313 // Okay, this register is good, we can use it.
2316 // If we allocated enough consecutive
2317 if (NumAllocated == NumRegs) {
2318 unsigned RegStart = (i-NumAllocated)+1;
2319 unsigned RegEnd = i+1;
2320 // Mark all of the allocated registers used.
2321 for (unsigned i = RegStart; i != RegEnd; ++i) {
2322 unsigned Reg = RegClassRegs[i];
2323 Regs.push_back(Reg);
2324 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2325 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2328 return RegsForValue(Regs, *RC->vt_begin(), VT);
2332 // Otherwise, we couldn't allocate enough registers for this.
2333 return RegsForValue();
2337 /// visitInlineAsm - Handle a call to an InlineAsm object.
2339 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2340 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2342 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2345 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
2346 std::vector<MVT::ValueType> ConstraintVTs;
2348 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2349 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2350 /// if it is a def of that register.
2351 std::vector<SDOperand> AsmNodeOperands;
2352 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2353 AsmNodeOperands.push_back(AsmStr);
2355 SDOperand Chain = getRoot();
2358 // We fully assign registers here at isel time. This is not optimal, but
2359 // should work. For register classes that correspond to LLVM classes, we
2360 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2361 // over the constraints, collecting fixed registers that we know we can't use.
2362 std::set<unsigned> OutputRegs, InputRegs;
2364 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2365 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2366 std::string &ConstraintCode = Constraints[i].Codes[0];
2368 MVT::ValueType OpVT;
2370 // Compute the value type for each operand and add it to ConstraintVTs.
2371 switch (Constraints[i].Type) {
2372 case InlineAsm::isOutput:
2373 if (!Constraints[i].isIndirectOutput) {
2374 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2375 OpVT = TLI.getValueType(I.getType());
2377 const Type *OpTy = I.getOperand(OpNum)->getType();
2378 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2379 OpNum++; // Consumes a call operand.
2382 case InlineAsm::isInput:
2383 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2384 OpNum++; // Consumes a call operand.
2386 case InlineAsm::isClobber:
2391 ConstraintVTs.push_back(OpVT);
2393 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2394 continue; // Not assigned a fixed reg.
2396 // Build a list of regs that this operand uses. This always has a single
2397 // element for promoted/expanded operands.
2398 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2400 OutputRegs, InputRegs);
2402 switch (Constraints[i].Type) {
2403 case InlineAsm::isOutput:
2404 // We can't assign any other output to this register.
2405 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2406 // If this is an early-clobber output, it cannot be assigned to the same
2407 // value as the input reg.
2408 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2409 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2411 case InlineAsm::isInput:
2412 // We can't assign any other input to this register.
2413 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2415 case InlineAsm::isClobber:
2416 // Clobbered regs cannot be used as inputs or outputs.
2417 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2418 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2423 // Loop over all of the inputs, copying the operand values into the
2424 // appropriate registers and processing the output regs.
2425 RegsForValue RetValRegs;
2426 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2429 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2430 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2431 std::string &ConstraintCode = Constraints[i].Codes[0];
2433 switch (Constraints[i].Type) {
2434 case InlineAsm::isOutput: {
2435 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2436 if (ConstraintCode.size() == 1) // not a physreg name.
2437 CTy = TLI.getConstraintType(ConstraintCode[0]);
2439 if (CTy == TargetLowering::C_Memory) {
2441 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2443 // Check that the operand (the address to store to) isn't a float.
2444 if (!MVT::isInteger(InOperandVal.getValueType()))
2445 assert(0 && "MATCH FAIL!");
2447 if (!Constraints[i].isIndirectOutput)
2448 assert(0 && "MATCH FAIL!");
2450 OpNum++; // Consumes a call operand.
2452 // Extend/truncate to the right pointer type if needed.
2453 MVT::ValueType PtrType = TLI.getPointerTy();
2454 if (InOperandVal.getValueType() < PtrType)
2455 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2456 else if (InOperandVal.getValueType() > PtrType)
2457 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2459 // Add information to the INLINEASM node to know about this output.
2460 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2461 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2462 AsmNodeOperands.push_back(InOperandVal);
2466 // Otherwise, this is a register output.
2467 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2469 // If this is an early-clobber output, or if there is an input
2470 // constraint that matches this, we need to reserve the input register
2471 // so no other inputs allocate to it.
2472 bool UsesInputRegister = false;
2473 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2474 UsesInputRegister = true;
2476 // Copy the output from the appropriate register. Find a register that
2479 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2480 true, UsesInputRegister,
2481 OutputRegs, InputRegs);
2482 if (Regs.Regs.empty()) {
2483 std::cerr << "Couldn't allocate output reg for contraint '"
2484 << ConstraintCode << "'!\n";
2488 if (!Constraints[i].isIndirectOutput) {
2489 assert(RetValRegs.Regs.empty() &&
2490 "Cannot have multiple output constraints yet!");
2491 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2494 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2495 I.getOperand(OpNum)));
2496 OpNum++; // Consumes a call operand.
2499 // Add information to the INLINEASM node to know that this register is
2501 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2504 case InlineAsm::isInput: {
2505 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2506 OpNum++; // Consumes a call operand.
2508 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2509 // If this is required to match an output register we have already set,
2510 // just use its register.
2511 unsigned OperandNo = atoi(ConstraintCode.c_str());
2513 // Scan until we find the definition we already emitted of this operand.
2514 // When we find it, create a RegsForValue operand.
2515 unsigned CurOp = 2; // The first operand.
2516 for (; OperandNo; --OperandNo) {
2517 // Advance to the next operand.
2519 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2520 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2521 (NumOps & 7) == 4 /*MEM*/) &&
2522 "Skipped past definitions?");
2523 CurOp += (NumOps>>3)+1;
2527 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2528 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2529 "Skipped past definitions?");
2531 // Add NumOps>>3 registers to MatchedRegs.
2532 RegsForValue MatchedRegs;
2533 MatchedRegs.ValueVT = InOperandVal.getValueType();
2534 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2535 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2536 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2537 MatchedRegs.Regs.push_back(Reg);
2540 // Use the produced MatchedRegs object to
2541 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2542 TLI.getPointerTy());
2543 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2547 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2548 if (ConstraintCode.size() == 1) // not a physreg name.
2549 CTy = TLI.getConstraintType(ConstraintCode[0]);
2551 if (CTy == TargetLowering::C_Other) {
2552 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2553 ConstraintCode[0], DAG);
2554 if (!InOperandVal.Val) {
2555 std::cerr << "Invalid operand for inline asm constraint '"
2556 << ConstraintCode << "'!\n";
2560 // Add information to the INLINEASM node to know about this input.
2561 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2562 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2563 AsmNodeOperands.push_back(InOperandVal);
2565 } else if (CTy == TargetLowering::C_Memory) {
2568 // Check that the operand isn't a float.
2569 if (!MVT::isInteger(InOperandVal.getValueType()))
2570 assert(0 && "MATCH FAIL!");
2572 // Extend/truncate to the right pointer type if needed.
2573 MVT::ValueType PtrType = TLI.getPointerTy();
2574 if (InOperandVal.getValueType() < PtrType)
2575 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2576 else if (InOperandVal.getValueType() > PtrType)
2577 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2579 // Add information to the INLINEASM node to know about this input.
2580 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2581 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2582 AsmNodeOperands.push_back(InOperandVal);
2586 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2588 // Copy the input into the appropriate registers.
2589 RegsForValue InRegs =
2590 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2591 false, true, OutputRegs, InputRegs);
2592 // FIXME: should be match fail.
2593 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2595 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2597 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2600 case InlineAsm::isClobber: {
2601 RegsForValue ClobberedRegs =
2602 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2603 OutputRegs, InputRegs);
2604 // Add the clobbered value to the operand list, so that the register
2605 // allocator is aware that the physreg got clobbered.
2606 if (!ClobberedRegs.Regs.empty())
2607 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2613 // Finish up input operands.
2614 AsmNodeOperands[0] = Chain;
2615 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2617 Chain = DAG.getNode(ISD::INLINEASM,
2618 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
2619 &AsmNodeOperands[0], AsmNodeOperands.size());
2620 Flag = Chain.getValue(1);
2622 // If this asm returns a register value, copy the result from that register
2623 // and set it as the value of the call.
2624 if (!RetValRegs.Regs.empty())
2625 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2627 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2629 // Process indirect outputs, first output all of the flagged copies out of
2631 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2632 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2633 Value *Ptr = IndirectStoresToEmit[i].second;
2634 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2635 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2638 // Emit the non-flagged stores from the physregs.
2639 SmallVector<SDOperand, 8> OutChains;
2640 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2641 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
2642 getValue(StoresToEmit[i].second),
2643 StoresToEmit[i].second, 0));
2644 if (!OutChains.empty())
2645 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2646 &OutChains[0], OutChains.size());
2651 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2652 SDOperand Src = getValue(I.getOperand(0));
2654 MVT::ValueType IntPtr = TLI.getPointerTy();
2656 if (IntPtr < Src.getValueType())
2657 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2658 else if (IntPtr > Src.getValueType())
2659 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2661 // Scale the source by the type size.
2662 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2663 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2664 Src, getIntPtrConstant(ElementSize));
2666 std::vector<std::pair<SDOperand, const Type*> > Args;
2667 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
2669 std::pair<SDOperand,SDOperand> Result =
2670 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2671 DAG.getExternalSymbol("malloc", IntPtr),
2673 setValue(&I, Result.first); // Pointers always fit in registers
2674 DAG.setRoot(Result.second);
2677 void SelectionDAGLowering::visitFree(FreeInst &I) {
2678 std::vector<std::pair<SDOperand, const Type*> > Args;
2679 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2680 TLI.getTargetData()->getIntPtrType()));
2681 MVT::ValueType IntPtr = TLI.getPointerTy();
2682 std::pair<SDOperand,SDOperand> Result =
2683 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2684 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2685 DAG.setRoot(Result.second);
2688 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2689 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2690 // instructions are special in various ways, which require special support to
2691 // insert. The specified MachineInstr is created but not inserted into any
2692 // basic blocks, and the scheduler passes ownership of it to this method.
2693 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2694 MachineBasicBlock *MBB) {
2695 std::cerr << "If a target marks an instruction with "
2696 "'usesCustomDAGSchedInserter', it must implement "
2697 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2702 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2703 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2704 getValue(I.getOperand(1)),
2705 DAG.getSrcValue(I.getOperand(1))));
2708 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2709 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2710 getValue(I.getOperand(0)),
2711 DAG.getSrcValue(I.getOperand(0)));
2713 DAG.setRoot(V.getValue(1));
2716 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2717 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2718 getValue(I.getOperand(1)),
2719 DAG.getSrcValue(I.getOperand(1))));
2722 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2723 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2724 getValue(I.getOperand(1)),
2725 getValue(I.getOperand(2)),
2726 DAG.getSrcValue(I.getOperand(1)),
2727 DAG.getSrcValue(I.getOperand(2))));
2730 /// TargetLowering::LowerArguments - This is the default LowerArguments
2731 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
2732 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2733 /// integrated into SDISel.
2734 std::vector<SDOperand>
2735 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2736 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2737 std::vector<SDOperand> Ops;
2738 Ops.push_back(DAG.getRoot());
2739 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2740 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2742 // Add one result value for each formal argument.
2743 std::vector<MVT::ValueType> RetVals;
2744 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2745 MVT::ValueType VT = getValueType(I->getType());
2747 switch (getTypeAction(VT)) {
2748 default: assert(0 && "Unknown type action!");
2750 RetVals.push_back(VT);
2753 RetVals.push_back(getTypeToTransformTo(VT));
2756 if (VT != MVT::Vector) {
2757 // If this is a large integer, it needs to be broken up into small
2758 // integers. Figure out what the destination type is and how many small
2759 // integers it turns into.
2760 MVT::ValueType NVT = getTypeToTransformTo(VT);
2761 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2762 for (unsigned i = 0; i != NumVals; ++i)
2763 RetVals.push_back(NVT);
2765 // Otherwise, this is a vector type. We only support legal vectors
2767 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2768 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2770 // Figure out if there is a Packed type corresponding to this Vector
2771 // type. If so, convert to the packed type.
2772 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2773 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2774 RetVals.push_back(TVT);
2776 assert(0 && "Don't support illegal by-val vector arguments yet!");
2783 RetVals.push_back(MVT::Other);
2786 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2787 DAG.getNodeValueTypes(RetVals), RetVals.size(),
2788 &Ops[0], Ops.size()).Val;
2790 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
2792 // Set up the return result vector.
2795 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2796 MVT::ValueType VT = getValueType(I->getType());
2798 switch (getTypeAction(VT)) {
2799 default: assert(0 && "Unknown type action!");
2801 Ops.push_back(SDOperand(Result, i++));
2804 SDOperand Op(Result, i++);
2805 if (MVT::isInteger(VT)) {
2806 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2808 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2809 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2811 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2812 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2818 if (VT != MVT::Vector) {
2819 // If this is a large integer, it needs to be reassembled from small
2820 // integers. Figure out what the source elt type is and how many small
2822 MVT::ValueType NVT = getTypeToTransformTo(VT);
2823 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2825 SDOperand Lo = SDOperand(Result, i++);
2826 SDOperand Hi = SDOperand(Result, i++);
2828 if (!isLittleEndian())
2831 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2833 // Value scalarized into many values. Unimp for now.
2834 assert(0 && "Cannot expand i64 -> i16 yet!");
2837 // Otherwise, this is a vector type. We only support legal vectors
2839 const PackedType *PTy = cast<PackedType>(I->getType());
2840 unsigned NumElems = PTy->getNumElements();
2841 const Type *EltTy = PTy->getElementType();
2843 // Figure out if there is a Packed type corresponding to this Vector
2844 // type. If so, convert to the packed type.
2845 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2846 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2847 SDOperand N = SDOperand(Result, i++);
2848 // Handle copies from generic vectors to registers.
2849 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2850 DAG.getConstant(NumElems, MVT::i32),
2851 DAG.getValueType(getValueType(EltTy)));
2854 assert(0 && "Don't support illegal by-val vector arguments yet!");
2865 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
2866 /// implementation, which just inserts an ISD::CALL node, which is later custom
2867 /// lowered by the target to something concrete. FIXME: When all targets are
2868 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2869 std::pair<SDOperand, SDOperand>
2870 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2871 unsigned CallingConv, bool isTailCall,
2873 ArgListTy &Args, SelectionDAG &DAG) {
2874 SmallVector<SDOperand, 32> Ops;
2875 Ops.push_back(Chain); // Op#0 - Chain
2876 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2877 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2878 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2879 Ops.push_back(Callee);
2881 // Handle all of the outgoing arguments.
2882 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2883 MVT::ValueType VT = getValueType(Args[i].second);
2884 SDOperand Op = Args[i].first;
2885 bool isSigned = Args[i].second->isSigned();
2886 switch (getTypeAction(VT)) {
2887 default: assert(0 && "Unknown type action!");
2890 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2893 if (MVT::isInteger(VT)) {
2894 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2895 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2897 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2898 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2901 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2904 if (VT != MVT::Vector) {
2905 // If this is a large integer, it needs to be broken down into small
2906 // integers. Figure out what the source elt type is and how many small
2908 MVT::ValueType NVT = getTypeToTransformTo(VT);
2909 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2911 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2912 DAG.getConstant(0, getPointerTy()));
2913 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2914 DAG.getConstant(1, getPointerTy()));
2915 if (!isLittleEndian())
2919 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2921 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2923 // Value scalarized into many values. Unimp for now.
2924 assert(0 && "Cannot expand i64 -> i16 yet!");
2927 // Otherwise, this is a vector type. We only support legal vectors
2929 const PackedType *PTy = cast<PackedType>(Args[i].second);
2930 unsigned NumElems = PTy->getNumElements();
2931 const Type *EltTy = PTy->getElementType();
2933 // Figure out if there is a Packed type corresponding to this Vector
2934 // type. If so, convert to the packed type.
2935 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2936 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2937 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2938 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2940 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2942 assert(0 && "Don't support illegal by-val vector call args yet!");
2950 // Figure out the result value types.
2951 SmallVector<MVT::ValueType, 4> RetTys;
2953 if (RetTy != Type::VoidTy) {
2954 MVT::ValueType VT = getValueType(RetTy);
2955 switch (getTypeAction(VT)) {
2956 default: assert(0 && "Unknown type action!");
2958 RetTys.push_back(VT);
2961 RetTys.push_back(getTypeToTransformTo(VT));
2964 if (VT != MVT::Vector) {
2965 // If this is a large integer, it needs to be reassembled from small
2966 // integers. Figure out what the source elt type is and how many small
2968 MVT::ValueType NVT = getTypeToTransformTo(VT);
2969 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2970 for (unsigned i = 0; i != NumVals; ++i)
2971 RetTys.push_back(NVT);
2973 // Otherwise, this is a vector type. We only support legal vectors
2975 const PackedType *PTy = cast<PackedType>(RetTy);
2976 unsigned NumElems = PTy->getNumElements();
2977 const Type *EltTy = PTy->getElementType();
2979 // Figure out if there is a Packed type corresponding to this Vector
2980 // type. If so, convert to the packed type.
2981 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2982 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2983 RetTys.push_back(TVT);
2985 assert(0 && "Don't support illegal by-val vector call results yet!");
2992 RetTys.push_back(MVT::Other); // Always has a chain.
2994 // Finally, create the CALL node.
2995 SDOperand Res = DAG.getNode(ISD::CALL,
2996 DAG.getVTList(&RetTys[0], RetTys.size()),
2997 &Ops[0], Ops.size());
2999 // This returns a pair of operands. The first element is the
3000 // return value for the function (if RetTy is not VoidTy). The second
3001 // element is the outgoing token chain.
3003 if (RetTys.size() != 1) {
3004 MVT::ValueType VT = getValueType(RetTy);
3005 if (RetTys.size() == 2) {
3008 // If this value was promoted, truncate it down.
3009 if (ResVal.getValueType() != VT) {
3010 if (VT == MVT::Vector) {
3011 // Insert a VBITCONVERT to convert from the packed result type to the
3012 // MVT::Vector type.
3013 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3014 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3016 // Figure out if there is a Packed type corresponding to this Vector
3017 // type. If so, convert to the packed type.
3018 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3019 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3020 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3021 // "N x PTyElementVT" MVT::Vector type.
3022 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
3023 DAG.getConstant(NumElems, MVT::i32),
3024 DAG.getValueType(getValueType(EltTy)));
3028 } else if (MVT::isInteger(VT)) {
3029 unsigned AssertOp = RetTy->isSigned() ?
3030 ISD::AssertSext : ISD::AssertZext;
3031 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3032 DAG.getValueType(VT));
3033 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3035 assert(MVT::isFloatingPoint(VT));
3036 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3039 } else if (RetTys.size() == 3) {
3040 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3041 Res.getValue(0), Res.getValue(1));
3044 assert(0 && "Case not handled yet!");
3048 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3053 // It is always conservatively correct for llvm.returnaddress and
3054 // llvm.frameaddress to return 0.
3056 // FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3057 // expanded to 0 if the target wants.
3058 std::pair<SDOperand, SDOperand>
3059 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3060 unsigned Depth, SelectionDAG &DAG) {
3061 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
3064 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3065 assert(0 && "LowerOperation not implemented for this target!");
3070 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3071 SelectionDAG &DAG) {
3072 assert(0 && "CustomPromoteOperation not implemented for this target!");
3077 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
3078 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
3079 std::pair<SDOperand,SDOperand> Result =
3080 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
3081 setValue(&I, Result.first);
3082 DAG.setRoot(Result.second);
3085 /// getMemsetValue - Vectorized representation of the memset value
3087 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
3088 SelectionDAG &DAG) {
3089 MVT::ValueType CurVT = VT;
3090 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3091 uint64_t Val = C->getValue() & 255;
3093 while (CurVT != MVT::i8) {
3094 Val = (Val << Shift) | Val;
3096 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3098 return DAG.getConstant(Val, VT);
3100 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3102 while (CurVT != MVT::i8) {
3104 DAG.getNode(ISD::OR, VT,
3105 DAG.getNode(ISD::SHL, VT, Value,
3106 DAG.getConstant(Shift, MVT::i8)), Value);
3108 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3115 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3116 /// used when a memcpy is turned into a memset when the source is a constant
3118 static SDOperand getMemsetStringVal(MVT::ValueType VT,
3119 SelectionDAG &DAG, TargetLowering &TLI,
3120 std::string &Str, unsigned Offset) {
3122 unsigned MSB = getSizeInBits(VT) / 8;
3123 if (TLI.isLittleEndian())
3124 Offset = Offset + MSB - 1;
3125 for (unsigned i = 0; i != MSB; ++i) {
3126 Val = (Val << 8) | Str[Offset];
3127 Offset += TLI.isLittleEndian() ? -1 : 1;
3129 return DAG.getConstant(Val, VT);
3132 /// getMemBasePlusOffset - Returns base and offset node for the
3133 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3134 SelectionDAG &DAG, TargetLowering &TLI) {
3135 MVT::ValueType VT = Base.getValueType();
3136 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3139 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3140 /// to replace the memset / memcpy is below the threshold. It also returns the
3141 /// types of the sequence of memory ops to perform memset / memcpy.
3142 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3143 unsigned Limit, uint64_t Size,
3144 unsigned Align, TargetLowering &TLI) {
3147 if (TLI.allowsUnalignedMemoryAccesses()) {
3150 switch (Align & 7) {
3166 MVT::ValueType LVT = MVT::i64;
3167 while (!TLI.isTypeLegal(LVT))
3168 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3169 assert(MVT::isInteger(LVT));
3174 unsigned NumMemOps = 0;
3176 unsigned VTSize = getSizeInBits(VT) / 8;
3177 while (VTSize > Size) {
3178 VT = (MVT::ValueType)((unsigned)VT - 1);
3181 assert(MVT::isInteger(VT));
3183 if (++NumMemOps > Limit)
3185 MemOps.push_back(VT);
3192 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
3193 SDOperand Op1 = getValue(I.getOperand(1));
3194 SDOperand Op2 = getValue(I.getOperand(2));
3195 SDOperand Op3 = getValue(I.getOperand(3));
3196 SDOperand Op4 = getValue(I.getOperand(4));
3197 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3198 if (Align == 0) Align = 1;
3200 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3201 std::vector<MVT::ValueType> MemOps;
3203 // Expand memset / memcpy to a series of load / store ops
3204 // if the size operand falls below a certain threshold.
3205 SmallVector<SDOperand, 8> OutChains;
3207 default: break; // Do nothing for now.
3209 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3210 Size->getValue(), Align, TLI)) {
3211 unsigned NumMemOps = MemOps.size();
3212 unsigned Offset = 0;
3213 for (unsigned i = 0; i < NumMemOps; i++) {
3214 MVT::ValueType VT = MemOps[i];
3215 unsigned VTSize = getSizeInBits(VT) / 8;
3216 SDOperand Value = getMemsetValue(Op2, VT, DAG);
3217 SDOperand Store = DAG.getStore(getRoot(), Value,
3218 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
3219 I.getOperand(1), Offset);
3220 OutChains.push_back(Store);
3227 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3228 Size->getValue(), Align, TLI)) {
3229 unsigned NumMemOps = MemOps.size();
3230 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
3231 GlobalAddressSDNode *G = NULL;
3233 bool CopyFromStr = false;
3235 if (Op2.getOpcode() == ISD::GlobalAddress)
3236 G = cast<GlobalAddressSDNode>(Op2);
3237 else if (Op2.getOpcode() == ISD::ADD &&
3238 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3239 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3240 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
3241 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
3244 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3246 Str = GV->getStringValue(false);
3254 for (unsigned i = 0; i < NumMemOps; i++) {
3255 MVT::ValueType VT = MemOps[i];
3256 unsigned VTSize = getSizeInBits(VT) / 8;
3257 SDOperand Value, Chain, Store;
3260 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3263 DAG.getStore(Chain, Value,
3264 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3265 I.getOperand(1), DstOff);
3267 Value = DAG.getLoad(VT, getRoot(),
3268 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
3269 I.getOperand(2), SrcOff);
3270 Chain = Value.getValue(1);
3272 DAG.getStore(Chain, Value,
3273 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3274 I.getOperand(1), DstOff);
3276 OutChains.push_back(Store);
3285 if (!OutChains.empty()) {
3286 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3287 &OutChains[0], OutChains.size()));
3292 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
3295 //===----------------------------------------------------------------------===//
3296 // SelectionDAGISel code
3297 //===----------------------------------------------------------------------===//
3299 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3300 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3303 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
3304 // FIXME: we only modify the CFG to split critical edges. This
3305 // updates dom and loop info.
3306 AU.addRequired<AliasAnalysis>();
3310 /// OptimizeNoopCopyExpression - We have determined that the specified cast
3311 /// instruction is a noop copy (e.g. it's casting from one pointer type to
3312 /// another, int->uint, or int->sbyte on PPC.
3314 /// Return true if any changes are made.
3315 static bool OptimizeNoopCopyExpression(CastInst *CI) {
3316 BasicBlock *DefBB = CI->getParent();
3318 /// InsertedCasts - Only insert a cast in each block once.
3319 std::map<BasicBlock*, CastInst*> InsertedCasts;
3321 bool MadeChange = false;
3322 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3324 Use &TheUse = UI.getUse();
3325 Instruction *User = cast<Instruction>(*UI);
3327 // Figure out which BB this cast is used in. For PHI's this is the
3328 // appropriate predecessor block.
3329 BasicBlock *UserBB = User->getParent();
3330 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3331 unsigned OpVal = UI.getOperandNo()/2;
3332 UserBB = PN->getIncomingBlock(OpVal);
3335 // Preincrement use iterator so we don't invalidate it.
3338 // If this user is in the same block as the cast, don't change the cast.
3339 if (UserBB == DefBB) continue;
3341 // If we have already inserted a cast into this block, use it.
3342 CastInst *&InsertedCast = InsertedCasts[UserBB];
3344 if (!InsertedCast) {
3345 BasicBlock::iterator InsertPt = UserBB->begin();
3346 while (isa<PHINode>(InsertPt)) ++InsertPt;
3349 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3353 // Replace a use of the cast with a use of the new casat.
3354 TheUse = InsertedCast;
3357 // If we removed all uses, nuke the cast.
3358 if (CI->use_empty())
3359 CI->eraseFromParent();
3364 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3365 /// casting to the type of GEPI.
3366 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3367 Instruction *GEPI, Value *Ptr,
3369 if (V) return V; // Already computed.
3371 BasicBlock::iterator InsertPt;
3372 if (BB == GEPI->getParent()) {
3373 // If insert into the GEP's block, insert right after the GEP.
3377 // Otherwise, insert at the top of BB, after any PHI nodes
3378 InsertPt = BB->begin();
3379 while (isa<PHINode>(InsertPt)) ++InsertPt;
3382 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3383 // BB so that there is only one value live across basic blocks (the cast
3385 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3386 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3387 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3389 // Add the offset, cast it to the right type.
3390 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3391 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
3394 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3395 /// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3396 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3397 /// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3398 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
3399 /// the constant add into a load or store instruction. Additionally, if a user
3400 /// is a pointer-pointer cast, we look through it to find its users.
3401 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3402 Constant *PtrOffset, BasicBlock *DefBB,
3403 GetElementPtrInst *GEPI,
3404 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3405 while (!RepPtr->use_empty()) {
3406 Instruction *User = cast<Instruction>(RepPtr->use_back());
3408 // If the user is a Pointer-Pointer cast, recurse.
3409 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3410 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3412 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3413 // could invalidate an iterator.
3414 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3418 // If this is a load of the pointer, or a store through the pointer, emit
3419 // the increment into the load/store block.
3420 Instruction *NewVal;
3421 if (isa<LoadInst>(User) ||
3422 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3423 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3424 User->getParent(), GEPI,
3427 // If this use is not foldable into the addressing mode, use a version
3428 // emitted in the GEP block.
3429 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3433 if (GEPI->getType() != RepPtr->getType()) {
3434 BasicBlock::iterator IP = NewVal;
3436 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3438 User->replaceUsesOfWith(RepPtr, NewVal);
3443 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3444 /// selection, we want to be a bit careful about some things. In particular, if
3445 /// we have a GEP instruction that is used in a different block than it is
3446 /// defined, the addressing expression of the GEP cannot be folded into loads or
3447 /// stores that use it. In this case, decompose the GEP and move constant
3448 /// indices into blocks that use it.
3449 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3450 const TargetData *TD) {
3451 // If this GEP is only used inside the block it is defined in, there is no
3452 // need to rewrite it.
3453 bool isUsedOutsideDefBB = false;
3454 BasicBlock *DefBB = GEPI->getParent();
3455 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3457 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3458 isUsedOutsideDefBB = true;
3462 if (!isUsedOutsideDefBB) return false;
3464 // If this GEP has no non-zero constant indices, there is nothing we can do,
3466 bool hasConstantIndex = false;
3467 bool hasVariableIndex = false;
3468 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3469 E = GEPI->op_end(); OI != E; ++OI) {
3470 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3471 if (CI->getZExtValue()) {
3472 hasConstantIndex = true;
3476 hasVariableIndex = true;
3480 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3481 if (!hasConstantIndex && !hasVariableIndex) {
3482 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3483 GEPI->getName(), GEPI);
3484 GEPI->replaceAllUsesWith(NC);
3485 GEPI->eraseFromParent();
3489 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3490 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3493 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3494 // constant offset (which we now know is non-zero) and deal with it later.
3495 uint64_t ConstantOffset = 0;
3496 const Type *UIntPtrTy = TD->getIntPtrType();
3497 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3498 const Type *Ty = GEPI->getOperand(0)->getType();
3500 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3501 E = GEPI->op_end(); OI != E; ++OI) {
3503 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3504 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3506 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
3507 Ty = StTy->getElementType(Field);
3509 Ty = cast<SequentialType>(Ty)->getElementType();
3511 // Handle constant subscripts.
3512 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3513 if (CI->getZExtValue() == 0) continue;
3514 if (CI->getType()->isSigned())
3515 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
3517 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
3521 // Ptr = Ptr + Idx * ElementSize;
3523 // Cast Idx to UIntPtrTy if needed.
3524 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3526 uint64_t ElementSize = TD->getTypeSize(Ty);
3527 // Mask off bits that should not be set.
3528 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3529 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
3531 // Multiply by the element size and add to the base.
3532 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3533 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3537 // Make sure that the offset fits in uintptr_t.
3538 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3539 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
3541 // Okay, we have now emitted all of the variable index parts to the BB that
3542 // the GEP is defined in. Loop over all of the using instructions, inserting
3543 // an "add Ptr, ConstantOffset" into each block that uses it and update the
3544 // instruction to use the newly computed value, making GEPI dead. When the
3545 // user is a load or store instruction address, we emit the add into the user
3546 // block, otherwise we use a canonical version right next to the gep (these
3547 // won't be foldable as addresses, so we might as well share the computation).
3549 std::map<BasicBlock*,Instruction*> InsertedExprs;
3550 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3552 // Finally, the GEP is dead, remove it.
3553 GEPI->eraseFromParent();
3559 /// SplitEdgeNicely - Split the critical edge from TI to it's specified
3560 /// successor if it will improve codegen. We only do this if the successor has
3561 /// phi nodes (otherwise critical edges are ok). If there is already another
3562 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
3563 /// instead of introducing a new block.
3564 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3565 BasicBlock *TIBB = TI->getParent();
3566 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3567 assert(isa<PHINode>(Dest->begin()) &&
3568 "This should only be called if Dest has a PHI!");
3570 /// TIPHIValues - This array is lazily computed to determine the values of
3571 /// PHIs in Dest that TI would provide.
3572 std::vector<Value*> TIPHIValues;
3574 // Check to see if Dest has any blocks that can be used as a split edge for
3576 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3577 BasicBlock *Pred = *PI;
3578 // To be usable, the pred has to end with an uncond branch to the dest.
3579 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3580 if (!PredBr || !PredBr->isUnconditional() ||
3581 // Must be empty other than the branch.
3582 &Pred->front() != PredBr)
3585 // Finally, since we know that Dest has phi nodes in it, we have to make
3586 // sure that jumping to Pred will have the same affect as going to Dest in
3587 // terms of PHI values.
3590 bool FoundMatch = true;
3591 for (BasicBlock::iterator I = Dest->begin();
3592 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3593 if (PHINo == TIPHIValues.size())
3594 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3596 // If the PHI entry doesn't work, we can't use this pred.
3597 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3603 // If we found a workable predecessor, change TI to branch to Succ.
3605 Dest->removePredecessor(TIBB);
3606 TI->setSuccessor(SuccNum, Pred);
3611 SplitCriticalEdge(TI, SuccNum, P, true);
3615 bool SelectionDAGISel::runOnFunction(Function &Fn) {
3616 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3617 RegMap = MF.getSSARegMap();
3618 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3620 // First, split all critical edges.
3622 // In this pass we also look for GEP and cast instructions that are used
3623 // across basic blocks and rewrite them to improve basic-block-at-a-time
3626 bool MadeChange = true;
3627 while (MadeChange) {
3629 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3630 // Split all critical edges where the dest block has a PHI.
3631 TerminatorInst *BBTI = BB->getTerminator();
3632 if (BBTI->getNumSuccessors() > 1) {
3633 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
3634 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3635 isCriticalEdge(BBTI, i, true))
3636 SplitEdgeNicely(BBTI, i, this);
3640 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3641 Instruction *I = BBI++;
3642 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3643 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3644 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3645 // If the source of the cast is a constant, then this should have
3646 // already been constant folded. The only reason NOT to constant fold
3647 // it is if something (e.g. LSR) was careful to place the constant
3648 // evaluation in a block other than then one that uses it (e.g. to hoist
3649 // the address of globals out of a loop). If this is the case, we don't
3650 // want to forward-subst the cast.
3651 if (isa<Constant>(CI->getOperand(0)))
3654 // If this is a noop copy, sink it into user blocks to reduce the number
3655 // of virtual registers that must be created and coallesced.
3656 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3657 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3659 // This is an fp<->int conversion?
3660 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3663 // If this is an extension, it will be a zero or sign extension, which
3665 if (SrcVT < DstVT) continue;
3667 // If these values will be promoted, find out what they will be promoted
3668 // to. This helps us consider truncates on PPC as noop copies when they
3670 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3671 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3672 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3673 DstVT = TLI.getTypeToTransformTo(DstVT);
3675 // If, after promotion, these are the same types, this is a noop copy.
3677 MadeChange |= OptimizeNoopCopyExpression(CI);
3683 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3685 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3686 SelectBasicBlock(I, MF, FuncInfo);
3691 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3693 SDOperand Op = getValue(V);
3694 assert((Op.getOpcode() != ISD::CopyFromReg ||
3695 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3696 "Copy from a reg to the same reg!");
3698 // If this type is not legal, we must make sure to not create an invalid
3700 MVT::ValueType SrcVT = Op.getValueType();
3701 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3702 if (SrcVT == DestVT) {
3703 return DAG.getCopyToReg(getRoot(), Reg, Op);
3704 } else if (SrcVT == MVT::Vector) {
3705 // Handle copies from generic vectors to registers.
3706 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3707 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3708 PTyElementVT, PTyLegalElementVT);
3710 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3711 // MVT::Vector type.
3712 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3713 DAG.getConstant(NE, MVT::i32),
3714 DAG.getValueType(PTyElementVT));
3716 // Loop over all of the elements of the resultant vector,
3717 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3718 // copying them into output registers.
3719 SmallVector<SDOperand, 8> OutChains;
3720 SDOperand Root = getRoot();
3721 for (unsigned i = 0; i != NE; ++i) {
3722 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3723 Op, DAG.getConstant(i, TLI.getPointerTy()));
3724 if (PTyElementVT == PTyLegalElementVT) {
3725 // Elements are legal.
3726 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3727 } else if (PTyLegalElementVT > PTyElementVT) {
3728 // Elements are promoted.
3729 if (MVT::isFloatingPoint(PTyLegalElementVT))
3730 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3732 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3733 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3735 // Elements are expanded.
3736 // The src value is expanded into multiple registers.
3737 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3738 Elt, DAG.getConstant(0, TLI.getPointerTy()));
3739 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3740 Elt, DAG.getConstant(1, TLI.getPointerTy()));
3741 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3742 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3745 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3746 &OutChains[0], OutChains.size());
3747 } else if (SrcVT < DestVT) {
3748 // The src value is promoted to the register.
3749 if (MVT::isFloatingPoint(SrcVT))
3750 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3752 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3753 return DAG.getCopyToReg(getRoot(), Reg, Op);
3755 // The src value is expanded into multiple registers.
3756 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3757 Op, DAG.getConstant(0, TLI.getPointerTy()));
3758 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3759 Op, DAG.getConstant(1, TLI.getPointerTy()));
3760 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
3761 return DAG.getCopyToReg(Op, Reg+1, Hi);
3765 void SelectionDAGISel::
3766 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3767 std::vector<SDOperand> &UnorderedChains) {
3768 // If this is the entry block, emit arguments.
3769 Function &F = *BB->getParent();
3770 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3771 SDOperand OldRoot = SDL.DAG.getRoot();
3772 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3775 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3777 if (!AI->use_empty()) {
3778 SDL.setValue(AI, Args[a]);
3780 // If this argument is live outside of the entry block, insert a copy from
3781 // whereever we got it to the vreg that other BB's will reference it as.
3782 if (FuncInfo.ValueMap.count(AI)) {
3784 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
3785 UnorderedChains.push_back(Copy);
3789 // Finally, if the target has anything special to do, allow it to do so.
3790 // FIXME: this should insert code into the DAG!
3791 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3794 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3795 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3796 FunctionLoweringInfo &FuncInfo) {
3797 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3799 std::vector<SDOperand> UnorderedChains;
3801 // Lower any arguments needed in this block if this is the entry block.
3802 if (LLVMBB == &LLVMBB->getParent()->front())
3803 LowerArguments(LLVMBB, SDL, UnorderedChains);
3805 BB = FuncInfo.MBBMap[LLVMBB];
3806 SDL.setCurrentBasicBlock(BB);
3808 // Lower all of the non-terminator instructions.
3809 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3813 // Ensure that all instructions which are used outside of their defining
3814 // blocks are available as virtual registers.
3815 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3816 if (!I->use_empty() && !isa<PHINode>(I)) {
3817 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3818 if (VMI != FuncInfo.ValueMap.end())
3819 UnorderedChains.push_back(
3820 SDL.CopyValueToVirtualRegister(I, VMI->second));
3823 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3824 // ensure constants are generated when needed. Remember the virtual registers
3825 // that need to be added to the Machine PHI nodes as input. We cannot just
3826 // directly add them, because expansion might result in multiple MBB's for one
3827 // BB. As such, the start of the BB might correspond to a different MBB than
3830 TerminatorInst *TI = LLVMBB->getTerminator();
3832 // Emit constants only once even if used by multiple PHI nodes.
3833 std::map<Constant*, unsigned> ConstantsOut;
3835 // Vector bool would be better, but vector<bool> is really slow.
3836 std::vector<unsigned char> SuccsHandled;
3837 if (TI->getNumSuccessors())
3838 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3840 // Check successor nodes PHI nodes that expect a constant to be available from
3842 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3843 BasicBlock *SuccBB = TI->getSuccessor(succ);
3844 if (!isa<PHINode>(SuccBB->begin())) continue;
3845 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
3847 // If this terminator has multiple identical successors (common for
3848 // switches), only handle each succ once.
3849 unsigned SuccMBBNo = SuccMBB->getNumber();
3850 if (SuccsHandled[SuccMBBNo]) continue;
3851 SuccsHandled[SuccMBBNo] = true;
3853 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
3856 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3857 // nodes and Machine PHI nodes, but the incoming operands have not been
3859 for (BasicBlock::iterator I = SuccBB->begin();
3860 (PN = dyn_cast<PHINode>(I)); ++I) {
3861 // Ignore dead phi's.
3862 if (PN->use_empty()) continue;
3865 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3866 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3867 unsigned &RegOut = ConstantsOut[C];
3869 RegOut = FuncInfo.CreateRegForValue(C);
3870 UnorderedChains.push_back(
3871 SDL.CopyValueToVirtualRegister(C, RegOut));
3875 Reg = FuncInfo.ValueMap[PHIOp];
3877 assert(isa<AllocaInst>(PHIOp) &&
3878 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3879 "Didn't codegen value into a register!??");
3880 Reg = FuncInfo.CreateRegForValue(PHIOp);
3881 UnorderedChains.push_back(
3882 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
3886 // Remember that this register needs to added to the machine PHI node as
3887 // the input for this MBB.
3888 MVT::ValueType VT = TLI.getValueType(PN->getType());
3889 unsigned NumElements;
3890 if (VT != MVT::Vector)
3891 NumElements = TLI.getNumElements(VT);
3893 MVT::ValueType VT1,VT2;
3895 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3898 for (unsigned i = 0, e = NumElements; i != e; ++i)
3899 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3902 ConstantsOut.clear();
3904 // Turn all of the unordered chains into one factored node.
3905 if (!UnorderedChains.empty()) {
3906 SDOperand Root = SDL.getRoot();
3907 if (Root.getOpcode() != ISD::EntryToken) {
3908 unsigned i = 0, e = UnorderedChains.size();
3909 for (; i != e; ++i) {
3910 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3911 if (UnorderedChains[i].Val->getOperand(0) == Root)
3912 break; // Don't add the root if we already indirectly depend on it.
3916 UnorderedChains.push_back(Root);
3918 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3919 &UnorderedChains[0], UnorderedChains.size()));
3922 // Lower the terminator after the copies are emitted.
3923 SDL.visit(*LLVMBB->getTerminator());
3925 // Copy over any CaseBlock records that may now exist due to SwitchInst
3926 // lowering, as well as any jump table information.
3927 SwitchCases.clear();
3928 SwitchCases = SDL.SwitchCases;
3931 // Make sure the root of the DAG is up-to-date.
3932 DAG.setRoot(SDL.getRoot());
3935 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
3936 // Get alias analysis for load/store combining.
3937 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3939 // Run the DAG combiner in pre-legalize mode.
3940 DAG.Combine(false, AA);
3942 DEBUG(std::cerr << "Lowered selection DAG:\n");
3945 // Second step, hack on the DAG until it only uses operations and types that
3946 // the target supports.
3949 DEBUG(std::cerr << "Legalized selection DAG:\n");
3952 // Run the DAG combiner in post-legalize mode.
3953 DAG.Combine(true, AA);
3955 if (ViewISelDAGs) DAG.viewGraph();
3957 // Third, instruction select all of the operations to machine code, adding the
3958 // code to the MachineBasicBlock.
3959 InstructionSelectBasicBlock(DAG);
3961 DEBUG(std::cerr << "Selected machine code:\n");
3965 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3966 FunctionLoweringInfo &FuncInfo) {
3967 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3969 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3972 // First step, lower LLVM code to some DAG. This DAG may use operations and
3973 // types that are not supported by the target.
3974 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3976 // Second step, emit the lowered DAG as machine code.
3977 CodeGenAndEmitDAG(DAG);
3980 // Next, now that we know what the last MBB the LLVM BB expanded is, update
3981 // PHI nodes in successors.
3982 if (SwitchCases.empty() && JT.Reg == 0) {
3983 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3984 MachineInstr *PHI = PHINodesToUpdate[i].first;
3985 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3986 "This is not a machine PHI node that we are updating!");
3987 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3988 PHI->addMachineBasicBlockOperand(BB);
3993 // If the JumpTable record is filled in, then we need to emit a jump table.
3994 // Updating the PHI nodes is tricky in this case, since we need to determine
3995 // whether the PHI is a successor of the range check MBB or the jump table MBB
3997 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3998 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4000 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4001 MachineBasicBlock *RangeBB = BB;
4002 // Set the current basic block to the mbb we wish to insert the code into
4004 SDL.setCurrentBasicBlock(BB);
4006 SDL.visitJumpTable(JT);
4007 SDAG.setRoot(SDL.getRoot());
4008 CodeGenAndEmitDAG(SDAG);
4010 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4011 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4012 MachineBasicBlock *PHIBB = PHI->getParent();
4013 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4014 "This is not a machine PHI node that we are updating!");
4015 if (PHIBB == JT.Default) {
4016 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4017 PHI->addMachineBasicBlockOperand(RangeBB);
4019 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4020 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4021 PHI->addMachineBasicBlockOperand(BB);
4027 // If the switch block involved a branch to one of the actual successors, we
4028 // need to update PHI nodes in that block.
4029 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4030 MachineInstr *PHI = PHINodesToUpdate[i].first;
4031 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4032 "This is not a machine PHI node that we are updating!");
4033 if (BB->isSuccessor(PHI->getParent())) {
4034 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4035 PHI->addMachineBasicBlockOperand(BB);
4039 // If we generated any switch lowering information, build and codegen any
4040 // additional DAGs necessary.
4041 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4042 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4044 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4046 // Set the current basic block to the mbb we wish to insert the code into
4047 BB = SwitchCases[i].ThisBB;
4048 SDL.setCurrentBasicBlock(BB);
4051 SDL.visitSwitchCase(SwitchCases[i]);
4052 SDAG.setRoot(SDL.getRoot());
4053 CodeGenAndEmitDAG(SDAG);
4055 // Handle any PHI nodes in successors of this chunk, as if we were coming
4056 // from the original BB before switch expansion. Note that PHI nodes can
4057 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4058 // handle them the right number of times.
4059 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4060 for (MachineBasicBlock::iterator Phi = BB->begin();
4061 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4062 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4063 for (unsigned pn = 0; ; ++pn) {
4064 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4065 if (PHINodesToUpdate[pn].first == Phi) {
4066 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4067 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4073 // Don't process RHS if same block as LHS.
4074 if (BB == SwitchCases[i].FalseBB)
4075 SwitchCases[i].FalseBB = 0;
4077 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4078 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4079 SwitchCases[i].FalseBB = 0;
4081 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4086 //===----------------------------------------------------------------------===//
4087 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4088 /// target node in the graph.
4089 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4090 if (ViewSchedDAGs) DAG.viewGraph();
4092 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4096 RegisterScheduler::setDefault(Ctor);
4099 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4105 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4106 return new HazardRecognizer();
4109 //===----------------------------------------------------------------------===//
4110 // Helper functions used by the generated instruction selector.
4111 //===----------------------------------------------------------------------===//
4112 // Calls to these methods are generated by tblgen.
4114 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4115 /// the dag combiner simplified the 255, we still want to match. RHS is the
4116 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4117 /// specified in the .td file (e.g. 255).
4118 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4119 int64_t DesiredMaskS) {
4120 uint64_t ActualMask = RHS->getValue();
4121 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4123 // If the actual mask exactly matches, success!
4124 if (ActualMask == DesiredMask)
4127 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4128 if (ActualMask & ~DesiredMask)
4131 // Otherwise, the DAG Combiner may have proven that the value coming in is
4132 // either already zero or is not demanded. Check for known zero input bits.
4133 uint64_t NeededMask = DesiredMask & ~ActualMask;
4134 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4137 // TODO: check to see if missing bits are just not demanded.
4139 // Otherwise, this pattern doesn't match.
4143 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4144 /// the dag combiner simplified the 255, we still want to match. RHS is the
4145 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4146 /// specified in the .td file (e.g. 255).
4147 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4148 int64_t DesiredMaskS) {
4149 uint64_t ActualMask = RHS->getValue();
4150 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4152 // If the actual mask exactly matches, success!
4153 if (ActualMask == DesiredMask)
4156 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4157 if (ActualMask & ~DesiredMask)
4160 // Otherwise, the DAG Combiner may have proven that the value coming in is
4161 // either already zero or is not demanded. Check for known zero input bits.
4162 uint64_t NeededMask = DesiredMask & ~ActualMask;
4164 uint64_t KnownZero, KnownOne;
4165 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4167 // If all the missing bits in the or are already known to be set, match!
4168 if ((NeededMask & KnownOne) == NeededMask)
4171 // TODO: check to see if missing bits are just not demanded.
4173 // Otherwise, this pattern doesn't match.
4178 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4179 /// by tblgen. Others should not call it.
4180 void SelectionDAGISel::
4181 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4182 std::vector<SDOperand> InOps;
4183 std::swap(InOps, Ops);
4185 Ops.push_back(InOps[0]); // input chain.
4186 Ops.push_back(InOps[1]); // input asm string.
4188 unsigned i = 2, e = InOps.size();
4189 if (InOps[e-1].getValueType() == MVT::Flag)
4190 --e; // Don't process a flag operand if it is here.
4193 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4194 if ((Flags & 7) != 4 /*MEM*/) {
4195 // Just skip over this operand, copying the operands verbatim.
4196 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4197 i += (Flags >> 3) + 1;
4199 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4200 // Otherwise, this is a memory operand. Ask the target to select it.
4201 std::vector<SDOperand> SelOps;
4202 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4203 std::cerr << "Could not match memory address. Inline asm failure!\n";
4207 // Add this to the output node.
4208 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4209 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4214 // Add the flag input back if present.
4215 if (e != InOps.size())
4216 Ops.push_back(InOps.back());