Avoid emitting redundant materializations of integer constants
[oota-llvm.git] / lib / CodeGen / SelectionDAG / FastISel.cpp
1 ///===-- FastISel.cpp - Implementation of the FastISel class --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the FastISel class.
11 //
12 // "Fast" instruction selection is designed to emit very poor code quickly.
13 // Also, it is not designed to be able to do much lowering, so most illegal
14 // types (e.g. i64 on 32-bit targets) and operations (e.g. calls) are not
15 // supported. It is also not intended to be able to do much optimization,
16 // except in a few cases where doing optimizations reduces overall compile
17 // time (e.g. folding constants into immediate fields, because it's cheap
18 // and it reduces the number of instructions later phases have to examine).
19 //
20 // "Fast" instruction selection is able to fail gracefully and transfer
21 // control to the SelectionDAG selector for operations that it doesn't
22 // support. In many cases, this allows us to avoid duplicating a lot of
23 // the complicated lowering logic that SelectionDAG currently has.
24 //
25 // The intended use for "fast" instruction selection is "-O0" mode
26 // compilation, where the quality of the generated code is irrelevant when
27 // weighed against the speed at which the code can be generated. Also,
28 // at -O0, the LLVM optimizers are not running, and this makes the
29 // compile time of codegen a much higher portion of the overall compile
30 // time. Despite its limitations, "fast" instruction selection is able to
31 // handle enough code on its own to provide noticeable overall speedups
32 // in -O0 compiles.
33 //
34 // Basic operations are supported in a target-independent way, by reading
35 // the same instruction descriptions that the SelectionDAG selector reads,
36 // and identifying simple arithmetic operations that can be directly selected
37 // from simple operators. More complicated operations currently require
38 // target-specific code.
39 //
40 //===----------------------------------------------------------------------===//
41
42 #include "llvm/Function.h"
43 #include "llvm/GlobalVariable.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/IntrinsicInst.h"
46 #include "llvm/CodeGen/FastISel.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineModuleInfo.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/Target/TargetData.h"
51 #include "llvm/Target/TargetInstrInfo.h"
52 #include "llvm/Target/TargetLowering.h"
53 #include "llvm/Target/TargetMachine.h"
54 using namespace llvm;
55
56 unsigned FastISel::getRegForValue(Value *V) {
57   // Look up the value to see if we already have a register for it. We
58   // cache values defined by Instructions across blocks, and other values
59   // only locally. This is because Instructions already have the SSA
60   // def-dominatess-use requirement enforced.
61   if (ValueMap.count(V))
62     return ValueMap[V];
63   unsigned Reg = LocalValueMap[V];
64   if (Reg != 0)
65     return Reg;
66
67   MVT::SimpleValueType VT = TLI.getValueType(V->getType()).getSimpleVT();
68
69   // Ignore illegal types.
70   if (!TLI.isTypeLegal(VT)) {
71     // Promote MVT::i1 to a legal type though, because it's common and easy.
72     if (VT == MVT::i1)
73       VT = TLI.getTypeToTransformTo(VT).getSimpleVT();
74     else
75       return 0;
76   }
77
78   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
79     if (CI->getValue().getActiveBits() <= 64)
80       Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
81   } else if (isa<AllocaInst>(V)) {
82     Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
83   } else if (isa<ConstantPointerNull>(V)) {
84     // Translate this as an integer zero so that it can be
85     // local-CSE'd with actual integer zeros.
86     Reg = getRegForValue(Constant::getNullValue(TD.getIntPtrType()));
87   } else if (ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
88     Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
89
90     if (!Reg) {
91       const APFloat &Flt = CF->getValueAPF();
92       MVT IntVT = TLI.getPointerTy();
93
94       uint64_t x[2];
95       uint32_t IntBitWidth = IntVT.getSizeInBits();
96       if (!Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
97                                 APFloat::rmTowardZero) != APFloat::opOK) {
98         APInt IntVal(IntBitWidth, 2, x);
99
100         unsigned IntegerReg = getRegForValue(ConstantInt::get(IntVal));
101         if (IntegerReg != 0)
102           Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg);
103       }
104     }
105   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
106     if (!SelectOperator(CE, CE->getOpcode())) return 0;
107     Reg = LocalValueMap[CE];
108   } else if (isa<UndefValue>(V)) {
109     Reg = createResultReg(TLI.getRegClassFor(VT));
110     BuildMI(MBB, TII.get(TargetInstrInfo::IMPLICIT_DEF), Reg);
111   }
112   
113   // If target-independent code couldn't handle the value, give target-specific
114   // code a try.
115   if (!Reg && isa<Constant>(V))
116     Reg = TargetMaterializeConstant(cast<Constant>(V));
117   
118   // Don't cache constant materializations in the general ValueMap.
119   // To do so would require tracking what uses they dominate.
120   if (Reg != 0)
121     LocalValueMap[V] = Reg;
122   return Reg;
123 }
124
125 unsigned FastISel::lookUpRegForValue(Value *V) {
126   // Look up the value to see if we already have a register for it. We
127   // cache values defined by Instructions across blocks, and other values
128   // only locally. This is because Instructions already have the SSA
129   // def-dominatess-use requirement enforced.
130   if (ValueMap.count(V))
131     return ValueMap[V];
132   return LocalValueMap[V];
133 }
134
135 /// UpdateValueMap - Update the value map to include the new mapping for this
136 /// instruction, or insert an extra copy to get the result in a previous
137 /// determined register.
138 /// NOTE: This is only necessary because we might select a block that uses
139 /// a value before we select the block that defines the value.  It might be
140 /// possible to fix this by selecting blocks in reverse postorder.
141 void FastISel::UpdateValueMap(Value* I, unsigned Reg) {
142   if (!isa<Instruction>(I)) {
143     LocalValueMap[I] = Reg;
144     return;
145   }
146   if (!ValueMap.count(I))
147     ValueMap[I] = Reg;
148   else
149     TII.copyRegToReg(*MBB, MBB->end(), ValueMap[I],
150                      Reg, MRI.getRegClass(Reg), MRI.getRegClass(Reg));
151 }
152
153 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
154 /// which has an opcode which directly corresponds to the given ISD opcode.
155 ///
156 bool FastISel::SelectBinaryOp(User *I, ISD::NodeType ISDOpcode) {
157   MVT VT = MVT::getMVT(I->getType(), /*HandleUnknown=*/true);
158   if (VT == MVT::Other || !VT.isSimple())
159     // Unhandled type. Halt "fast" selection and bail.
160     return false;
161
162   // We only handle legal types. For example, on x86-32 the instruction
163   // selector contains all of the 64-bit instructions from x86-64,
164   // under the assumption that i64 won't be used if the target doesn't
165   // support it.
166   if (!TLI.isTypeLegal(VT)) {
167     // MVT::i1 is special. Allow AND, OR, or XOR because they
168     // don't require additional zeroing, which makes them easy.
169     if (VT == MVT::i1 &&
170         (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
171          ISDOpcode == ISD::XOR))
172       VT = TLI.getTypeToTransformTo(VT);
173     else
174       return false;
175   }
176
177   unsigned Op0 = getRegForValue(I->getOperand(0));
178   if (Op0 == 0)
179     // Unhandled operand. Halt "fast" selection and bail.
180     return false;
181
182   // Check if the second operand is a constant and handle it appropriately.
183   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
184     unsigned ResultReg = FastEmit_ri(VT.getSimpleVT(), VT.getSimpleVT(),
185                                      ISDOpcode, Op0, CI->getZExtValue());
186     if (ResultReg != 0) {
187       // We successfully emitted code for the given LLVM Instruction.
188       UpdateValueMap(I, ResultReg);
189       return true;
190     }
191   }
192
193   // Check if the second operand is a constant float.
194   if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
195     unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
196                                      ISDOpcode, Op0, CF);
197     if (ResultReg != 0) {
198       // We successfully emitted code for the given LLVM Instruction.
199       UpdateValueMap(I, ResultReg);
200       return true;
201     }
202   }
203
204   unsigned Op1 = getRegForValue(I->getOperand(1));
205   if (Op1 == 0)
206     // Unhandled operand. Halt "fast" selection and bail.
207     return false;
208
209   // Now we have both operands in registers. Emit the instruction.
210   unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
211                                    ISDOpcode, Op0, Op1);
212   if (ResultReg == 0)
213     // Target-specific code wasn't able to find a machine opcode for
214     // the given ISD opcode and type. Halt "fast" selection and bail.
215     return false;
216
217   // We successfully emitted code for the given LLVM Instruction.
218   UpdateValueMap(I, ResultReg);
219   return true;
220 }
221
222 bool FastISel::SelectGetElementPtr(User *I) {
223   unsigned N = getRegForValue(I->getOperand(0));
224   if (N == 0)
225     // Unhandled operand. Halt "fast" selection and bail.
226     return false;
227
228   const Type *Ty = I->getOperand(0)->getType();
229   MVT::SimpleValueType VT = TLI.getPointerTy().getSimpleVT();
230   for (GetElementPtrInst::op_iterator OI = I->op_begin()+1, E = I->op_end();
231        OI != E; ++OI) {
232     Value *Idx = *OI;
233     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
234       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
235       if (Field) {
236         // N = N + Offset
237         uint64_t Offs = TD.getStructLayout(StTy)->getElementOffset(Field);
238         // FIXME: This can be optimized by combining the add with a
239         // subsequent one.
240         N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT);
241         if (N == 0)
242           // Unhandled operand. Halt "fast" selection and bail.
243           return false;
244       }
245       Ty = StTy->getElementType(Field);
246     } else {
247       Ty = cast<SequentialType>(Ty)->getElementType();
248
249       // If this is a constant subscript, handle it quickly.
250       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
251         if (CI->getZExtValue() == 0) continue;
252         uint64_t Offs = 
253           TD.getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
254         N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT);
255         if (N == 0)
256           // Unhandled operand. Halt "fast" selection and bail.
257           return false;
258         continue;
259       }
260       
261       // N = N + Idx * ElementSize;
262       uint64_t ElementSize = TD.getABITypeSize(Ty);
263       unsigned IdxN = getRegForValue(Idx);
264       if (IdxN == 0)
265         // Unhandled operand. Halt "fast" selection and bail.
266         return false;
267
268       // If the index is smaller or larger than intptr_t, truncate or extend
269       // it.
270       MVT IdxVT = MVT::getMVT(Idx->getType(), /*HandleUnknown=*/false);
271       if (IdxVT.bitsLT(VT))
272         IdxN = FastEmit_r(IdxVT.getSimpleVT(), VT, ISD::SIGN_EXTEND, IdxN);
273       else if (IdxVT.bitsGT(VT))
274         IdxN = FastEmit_r(IdxVT.getSimpleVT(), VT, ISD::TRUNCATE, IdxN);
275       if (IdxN == 0)
276         // Unhandled operand. Halt "fast" selection and bail.
277         return false;
278
279       if (ElementSize != 1) {
280         IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, ElementSize, VT);
281         if (IdxN == 0)
282           // Unhandled operand. Halt "fast" selection and bail.
283           return false;
284       }
285       N = FastEmit_rr(VT, VT, ISD::ADD, N, IdxN);
286       if (N == 0)
287         // Unhandled operand. Halt "fast" selection and bail.
288         return false;
289     }
290   }
291
292   // We successfully emitted code for the given LLVM Instruction.
293   UpdateValueMap(I, N);
294   return true;
295 }
296
297 bool FastISel::SelectCall(User *I) {
298   Function *F = cast<CallInst>(I)->getCalledFunction();
299   if (!F) return false;
300
301   unsigned IID = F->getIntrinsicID();
302   switch (IID) {
303   default: break;
304   case Intrinsic::dbg_stoppoint: {
305     DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
306     if (MMI && SPI->getContext() && MMI->Verify(SPI->getContext())) {
307       DebugInfoDesc *DD = MMI->getDescFor(SPI->getContext());
308       assert(DD && "Not a debug information descriptor");
309       const CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
310       unsigned SrcFile = MMI->RecordSource(CompileUnit);
311       unsigned Line = SPI->getLine();
312       unsigned Col = SPI->getColumn();
313       unsigned ID = MMI->RecordSourceLine(Line, Col, SrcFile);
314       const TargetInstrDesc &II = TII.get(TargetInstrInfo::DBG_LABEL);
315       BuildMI(MBB, II).addImm(ID);
316     }
317     return true;
318   }
319   case Intrinsic::dbg_region_start: {
320     DbgRegionStartInst *RSI = cast<DbgRegionStartInst>(I);
321     if (MMI && RSI->getContext() && MMI->Verify(RSI->getContext())) {
322       unsigned ID = MMI->RecordRegionStart(RSI->getContext());
323       const TargetInstrDesc &II = TII.get(TargetInstrInfo::DBG_LABEL);
324       BuildMI(MBB, II).addImm(ID);
325     }
326     return true;
327   }
328   case Intrinsic::dbg_region_end: {
329     DbgRegionEndInst *REI = cast<DbgRegionEndInst>(I);
330     if (MMI && REI->getContext() && MMI->Verify(REI->getContext())) {
331       unsigned ID = MMI->RecordRegionEnd(REI->getContext());
332       const TargetInstrDesc &II = TII.get(TargetInstrInfo::DBG_LABEL);
333       BuildMI(MBB, II).addImm(ID);
334     }
335     return true;
336   }
337   case Intrinsic::dbg_func_start: {
338     if (!MMI) return true;
339     DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
340     Value *SP = FSI->getSubprogram();
341     if (SP && MMI->Verify(SP)) {
342       // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
343       // what (most?) gdb expects.
344       DebugInfoDesc *DD = MMI->getDescFor(SP);
345       assert(DD && "Not a debug information descriptor");
346       SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
347       const CompileUnitDesc *CompileUnit = Subprogram->getFile();
348       unsigned SrcFile = MMI->RecordSource(CompileUnit);
349       // Record the source line but does create a label. It will be emitted
350       // at asm emission time.
351       MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
352     }
353     return true;
354   }
355   case Intrinsic::dbg_declare: {
356     DbgDeclareInst *DI = cast<DbgDeclareInst>(I);
357     Value *Variable = DI->getVariable();
358     if (MMI && Variable && MMI->Verify(Variable)) {
359       // Determine the address of the declared object.
360       Value *Address = DI->getAddress();
361       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
362         Address = BCI->getOperand(0);
363       AllocaInst *AI = dyn_cast<AllocaInst>(Address);
364       // Don't handle byval struct arguments, for example.
365       if (!AI) break;
366       DenseMap<const AllocaInst*, int>::iterator SI =
367         StaticAllocaMap.find(AI);
368       assert(SI != StaticAllocaMap.end() && "Invalid dbg.declare!");
369       int FI = SI->second;
370
371       // Determine the debug globalvariable.
372       GlobalValue *GV = cast<GlobalVariable>(Variable);
373
374       // Build the DECLARE instruction.
375       const TargetInstrDesc &II = TII.get(TargetInstrInfo::DECLARE);
376       BuildMI(MBB, II).addFrameIndex(FI).addGlobalAddress(GV);
377     }
378     return true;
379   }
380   }
381   return false;
382 }
383
384 bool FastISel::SelectCast(User *I, ISD::NodeType Opcode) {
385   MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
386   MVT DstVT = TLI.getValueType(I->getType());
387     
388   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
389       DstVT == MVT::Other || !DstVT.isSimple() ||
390       !TLI.isTypeLegal(DstVT))
391     // Unhandled type. Halt "fast" selection and bail.
392     return false;
393     
394   // Check if the source operand is legal. Or as a special case,
395   // it may be i1 if we're doing zero-extension because that's
396   // trivially easy and somewhat common.
397   if (!TLI.isTypeLegal(SrcVT)) {
398     if (SrcVT == MVT::i1 && Opcode == ISD::ZERO_EXTEND)
399       SrcVT = TLI.getTypeToTransformTo(SrcVT);
400     else
401       // Unhandled type. Halt "fast" selection and bail.
402       return false;
403   }
404     
405   unsigned InputReg = getRegForValue(I->getOperand(0));
406   if (!InputReg)
407     // Unhandled operand.  Halt "fast" selection and bail.
408     return false;
409     
410   unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
411                                   DstVT.getSimpleVT(),
412                                   Opcode,
413                                   InputReg);
414   if (!ResultReg)
415     return false;
416     
417   UpdateValueMap(I, ResultReg);
418   return true;
419 }
420
421 bool FastISel::SelectBitCast(User *I) {
422   // If the bitcast doesn't change the type, just use the operand value.
423   if (I->getType() == I->getOperand(0)->getType()) {
424     unsigned Reg = getRegForValue(I->getOperand(0));
425     if (Reg == 0)
426       return false;
427     UpdateValueMap(I, Reg);
428     return true;
429   }
430
431   // Bitcasts of other values become reg-reg copies or BIT_CONVERT operators.
432   MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
433   MVT DstVT = TLI.getValueType(I->getType());
434   
435   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
436       DstVT == MVT::Other || !DstVT.isSimple() ||
437       !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
438     // Unhandled type. Halt "fast" selection and bail.
439     return false;
440   
441   unsigned Op0 = getRegForValue(I->getOperand(0));
442   if (Op0 == 0)
443     // Unhandled operand. Halt "fast" selection and bail.
444     return false;
445   
446   // First, try to perform the bitcast by inserting a reg-reg copy.
447   unsigned ResultReg = 0;
448   if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) {
449     TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
450     TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
451     ResultReg = createResultReg(DstClass);
452     
453     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
454                                          Op0, DstClass, SrcClass);
455     if (!InsertedCopy)
456       ResultReg = 0;
457   }
458   
459   // If the reg-reg copy failed, select a BIT_CONVERT opcode.
460   if (!ResultReg)
461     ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
462                            ISD::BIT_CONVERT, Op0);
463   
464   if (!ResultReg)
465     return false;
466   
467   UpdateValueMap(I, ResultReg);
468   return true;
469 }
470
471 bool
472 FastISel::SelectInstruction(Instruction *I) {
473   return SelectOperator(I, I->getOpcode());
474 }
475
476 /// FastEmitBranch - Emit an unconditional branch to the given block,
477 /// unless it is the immediate (fall-through) successor, and update
478 /// the CFG.
479 void
480 FastISel::FastEmitBranch(MachineBasicBlock *MSucc) {
481   MachineFunction::iterator NextMBB =
482      next(MachineFunction::iterator(MBB));
483
484   if (MBB->isLayoutSuccessor(MSucc)) {
485     // The unconditional fall-through case, which needs no instructions.
486   } else {
487     // The unconditional branch case.
488     TII.InsertBranch(*MBB, MSucc, NULL, SmallVector<MachineOperand, 0>());
489   }
490   MBB->addSuccessor(MSucc);
491 }
492
493 bool
494 FastISel::SelectOperator(User *I, unsigned Opcode) {
495   switch (Opcode) {
496   case Instruction::Add: {
497     ISD::NodeType Opc = I->getType()->isFPOrFPVector() ? ISD::FADD : ISD::ADD;
498     return SelectBinaryOp(I, Opc);
499   }
500   case Instruction::Sub: {
501     ISD::NodeType Opc = I->getType()->isFPOrFPVector() ? ISD::FSUB : ISD::SUB;
502     return SelectBinaryOp(I, Opc);
503   }
504   case Instruction::Mul: {
505     ISD::NodeType Opc = I->getType()->isFPOrFPVector() ? ISD::FMUL : ISD::MUL;
506     return SelectBinaryOp(I, Opc);
507   }
508   case Instruction::SDiv:
509     return SelectBinaryOp(I, ISD::SDIV);
510   case Instruction::UDiv:
511     return SelectBinaryOp(I, ISD::UDIV);
512   case Instruction::FDiv:
513     return SelectBinaryOp(I, ISD::FDIV);
514   case Instruction::SRem:
515     return SelectBinaryOp(I, ISD::SREM);
516   case Instruction::URem:
517     return SelectBinaryOp(I, ISD::UREM);
518   case Instruction::FRem:
519     return SelectBinaryOp(I, ISD::FREM);
520   case Instruction::Shl:
521     return SelectBinaryOp(I, ISD::SHL);
522   case Instruction::LShr:
523     return SelectBinaryOp(I, ISD::SRL);
524   case Instruction::AShr:
525     return SelectBinaryOp(I, ISD::SRA);
526   case Instruction::And:
527     return SelectBinaryOp(I, ISD::AND);
528   case Instruction::Or:
529     return SelectBinaryOp(I, ISD::OR);
530   case Instruction::Xor:
531     return SelectBinaryOp(I, ISD::XOR);
532
533   case Instruction::GetElementPtr:
534     return SelectGetElementPtr(I);
535
536   case Instruction::Br: {
537     BranchInst *BI = cast<BranchInst>(I);
538
539     if (BI->isUnconditional()) {
540       BasicBlock *LLVMSucc = BI->getSuccessor(0);
541       MachineBasicBlock *MSucc = MBBMap[LLVMSucc];
542       FastEmitBranch(MSucc);
543       return true;
544     }
545
546     // Conditional branches are not handed yet.
547     // Halt "fast" selection and bail.
548     return false;
549   }
550
551   case Instruction::Unreachable:
552     // Nothing to emit.
553     return true;
554
555   case Instruction::PHI:
556     // PHI nodes are already emitted.
557     return true;
558
559   case Instruction::Alloca:
560     // FunctionLowering has the static-sized case covered.
561     if (StaticAllocaMap.count(cast<AllocaInst>(I)))
562       return true;
563
564     // Dynamic-sized alloca is not handled yet.
565     return false;
566     
567   case Instruction::Call:
568     return SelectCall(I);
569   
570   case Instruction::BitCast:
571     return SelectBitCast(I);
572
573   case Instruction::FPToSI:
574     return SelectCast(I, ISD::FP_TO_SINT);
575   case Instruction::ZExt:
576     return SelectCast(I, ISD::ZERO_EXTEND);
577   case Instruction::SExt:
578     return SelectCast(I, ISD::SIGN_EXTEND);
579   case Instruction::Trunc:
580     return SelectCast(I, ISD::TRUNCATE);
581   case Instruction::SIToFP:
582     return SelectCast(I, ISD::SINT_TO_FP);
583
584   case Instruction::IntToPtr: // Deliberate fall-through.
585   case Instruction::PtrToInt: {
586     MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
587     MVT DstVT = TLI.getValueType(I->getType());
588     if (DstVT.bitsGT(SrcVT))
589       return SelectCast(I, ISD::ZERO_EXTEND);
590     if (DstVT.bitsLT(SrcVT))
591       return SelectCast(I, ISD::TRUNCATE);
592     unsigned Reg = getRegForValue(I->getOperand(0));
593     if (Reg == 0) return false;
594     UpdateValueMap(I, Reg);
595     return true;
596   }
597
598   default:
599     // Unhandled instruction. Halt "fast" selection and bail.
600     return false;
601   }
602 }
603
604 FastISel::FastISel(MachineFunction &mf,
605                    MachineModuleInfo *mmi,
606                    DenseMap<const Value *, unsigned> &vm,
607                    DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
608                    DenseMap<const AllocaInst *, int> &am)
609   : MBB(0),
610     ValueMap(vm),
611     MBBMap(bm),
612     StaticAllocaMap(am),
613     MF(mf),
614     MMI(mmi),
615     MRI(MF.getRegInfo()),
616     MFI(*MF.getFrameInfo()),
617     MCP(*MF.getConstantPool()),
618     TM(MF.getTarget()),
619     TD(*TM.getTargetData()),
620     TII(*TM.getInstrInfo()),
621     TLI(*TM.getTargetLowering()) {
622 }
623
624 FastISel::~FastISel() {}
625
626 unsigned FastISel::FastEmit_(MVT::SimpleValueType, MVT::SimpleValueType,
627                              ISD::NodeType) {
628   return 0;
629 }
630
631 unsigned FastISel::FastEmit_r(MVT::SimpleValueType, MVT::SimpleValueType,
632                               ISD::NodeType, unsigned /*Op0*/) {
633   return 0;
634 }
635
636 unsigned FastISel::FastEmit_rr(MVT::SimpleValueType, MVT::SimpleValueType, 
637                                ISD::NodeType, unsigned /*Op0*/,
638                                unsigned /*Op0*/) {
639   return 0;
640 }
641
642 unsigned FastISel::FastEmit_i(MVT::SimpleValueType, MVT::SimpleValueType,
643                               ISD::NodeType, uint64_t /*Imm*/) {
644   return 0;
645 }
646
647 unsigned FastISel::FastEmit_f(MVT::SimpleValueType, MVT::SimpleValueType,
648                               ISD::NodeType, ConstantFP * /*FPImm*/) {
649   return 0;
650 }
651
652 unsigned FastISel::FastEmit_ri(MVT::SimpleValueType, MVT::SimpleValueType,
653                                ISD::NodeType, unsigned /*Op0*/,
654                                uint64_t /*Imm*/) {
655   return 0;
656 }
657
658 unsigned FastISel::FastEmit_rf(MVT::SimpleValueType, MVT::SimpleValueType,
659                                ISD::NodeType, unsigned /*Op0*/,
660                                ConstantFP * /*FPImm*/) {
661   return 0;
662 }
663
664 unsigned FastISel::FastEmit_rri(MVT::SimpleValueType, MVT::SimpleValueType,
665                                 ISD::NodeType,
666                                 unsigned /*Op0*/, unsigned /*Op1*/,
667                                 uint64_t /*Imm*/) {
668   return 0;
669 }
670
671 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
672 /// to emit an instruction with an immediate operand using FastEmit_ri.
673 /// If that fails, it materializes the immediate into a register and try
674 /// FastEmit_rr instead.
675 unsigned FastISel::FastEmit_ri_(MVT::SimpleValueType VT, ISD::NodeType Opcode,
676                                 unsigned Op0, uint64_t Imm,
677                                 MVT::SimpleValueType ImmType) {
678   // First check if immediate type is legal. If not, we can't use the ri form.
679   unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Imm);
680   if (ResultReg != 0)
681     return ResultReg;
682   unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
683   if (MaterialReg == 0)
684     return 0;
685   return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
686 }
687
688 /// FastEmit_rf_ - This method is a wrapper of FastEmit_ri. It first tries
689 /// to emit an instruction with a floating-point immediate operand using
690 /// FastEmit_rf. If that fails, it materializes the immediate into a register
691 /// and try FastEmit_rr instead.
692 unsigned FastISel::FastEmit_rf_(MVT::SimpleValueType VT, ISD::NodeType Opcode,
693                                 unsigned Op0, ConstantFP *FPImm,
694                                 MVT::SimpleValueType ImmType) {
695   // First check if immediate type is legal. If not, we can't use the rf form.
696   unsigned ResultReg = FastEmit_rf(VT, VT, Opcode, Op0, FPImm);
697   if (ResultReg != 0)
698     return ResultReg;
699
700   // Materialize the constant in a register.
701   unsigned MaterialReg = FastEmit_f(ImmType, ImmType, ISD::ConstantFP, FPImm);
702   if (MaterialReg == 0) {
703     // If the target doesn't have a way to directly enter a floating-point
704     // value into a register, use an alternate approach.
705     // TODO: The current approach only supports floating-point constants
706     // that can be constructed by conversion from integer values. This should
707     // be replaced by code that creates a load from a constant-pool entry,
708     // which will require some target-specific work.
709     const APFloat &Flt = FPImm->getValueAPF();
710     MVT IntVT = TLI.getPointerTy();
711
712     uint64_t x[2];
713     uint32_t IntBitWidth = IntVT.getSizeInBits();
714     if (Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
715                              APFloat::rmTowardZero) != APFloat::opOK)
716       return 0;
717     APInt IntVal(IntBitWidth, 2, x);
718
719     unsigned IntegerReg = FastEmit_i(IntVT.getSimpleVT(), IntVT.getSimpleVT(),
720                                      ISD::Constant, IntVal.getZExtValue());
721     if (IntegerReg == 0)
722       return 0;
723     MaterialReg = FastEmit_r(IntVT.getSimpleVT(), VT,
724                              ISD::SINT_TO_FP, IntegerReg);
725     if (MaterialReg == 0)
726       return 0;
727   }
728   return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
729 }
730
731 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
732   return MRI.createVirtualRegister(RC);
733 }
734
735 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
736                                  const TargetRegisterClass* RC) {
737   unsigned ResultReg = createResultReg(RC);
738   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
739
740   BuildMI(MBB, II, ResultReg);
741   return ResultReg;
742 }
743
744 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
745                                   const TargetRegisterClass *RC,
746                                   unsigned Op0) {
747   unsigned ResultReg = createResultReg(RC);
748   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
749
750   if (II.getNumDefs() >= 1)
751     BuildMI(MBB, II, ResultReg).addReg(Op0);
752   else {
753     BuildMI(MBB, II).addReg(Op0);
754     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
755                                          II.ImplicitDefs[0], RC, RC);
756     if (!InsertedCopy)
757       ResultReg = 0;
758   }
759
760   return ResultReg;
761 }
762
763 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
764                                    const TargetRegisterClass *RC,
765                                    unsigned Op0, unsigned Op1) {
766   unsigned ResultReg = createResultReg(RC);
767   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
768
769   if (II.getNumDefs() >= 1)
770     BuildMI(MBB, II, ResultReg).addReg(Op0).addReg(Op1);
771   else {
772     BuildMI(MBB, II).addReg(Op0).addReg(Op1);
773     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
774                                          II.ImplicitDefs[0], RC, RC);
775     if (!InsertedCopy)
776       ResultReg = 0;
777   }
778   return ResultReg;
779 }
780
781 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
782                                    const TargetRegisterClass *RC,
783                                    unsigned Op0, uint64_t Imm) {
784   unsigned ResultReg = createResultReg(RC);
785   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
786
787   if (II.getNumDefs() >= 1)
788     BuildMI(MBB, II, ResultReg).addReg(Op0).addImm(Imm);
789   else {
790     BuildMI(MBB, II).addReg(Op0).addImm(Imm);
791     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
792                                          II.ImplicitDefs[0], RC, RC);
793     if (!InsertedCopy)
794       ResultReg = 0;
795   }
796   return ResultReg;
797 }
798
799 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
800                                    const TargetRegisterClass *RC,
801                                    unsigned Op0, ConstantFP *FPImm) {
802   unsigned ResultReg = createResultReg(RC);
803   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
804
805   if (II.getNumDefs() >= 1)
806     BuildMI(MBB, II, ResultReg).addReg(Op0).addFPImm(FPImm);
807   else {
808     BuildMI(MBB, II).addReg(Op0).addFPImm(FPImm);
809     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
810                                          II.ImplicitDefs[0], RC, RC);
811     if (!InsertedCopy)
812       ResultReg = 0;
813   }
814   return ResultReg;
815 }
816
817 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
818                                     const TargetRegisterClass *RC,
819                                     unsigned Op0, unsigned Op1, uint64_t Imm) {
820   unsigned ResultReg = createResultReg(RC);
821   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
822
823   if (II.getNumDefs() >= 1)
824     BuildMI(MBB, II, ResultReg).addReg(Op0).addReg(Op1).addImm(Imm);
825   else {
826     BuildMI(MBB, II).addReg(Op0).addReg(Op1).addImm(Imm);
827     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
828                                          II.ImplicitDefs[0], RC, RC);
829     if (!InsertedCopy)
830       ResultReg = 0;
831   }
832   return ResultReg;
833 }
834
835 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
836                                   const TargetRegisterClass *RC,
837                                   uint64_t Imm) {
838   unsigned ResultReg = createResultReg(RC);
839   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
840   
841   if (II.getNumDefs() >= 1)
842     BuildMI(MBB, II, ResultReg).addImm(Imm);
843   else {
844     BuildMI(MBB, II).addImm(Imm);
845     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
846                                          II.ImplicitDefs[0], RC, RC);
847     if (!InsertedCopy)
848       ResultReg = 0;
849   }
850   return ResultReg;
851 }
852
853 unsigned FastISel::FastEmitInst_extractsubreg(unsigned Op0, uint32_t Idx) {
854   const TargetRegisterClass* RC = MRI.getRegClass(Op0);
855   const TargetRegisterClass* SRC = *(RC->subregclasses_begin()+Idx-1);
856   
857   unsigned ResultReg = createResultReg(SRC);
858   const TargetInstrDesc &II = TII.get(TargetInstrInfo::EXTRACT_SUBREG);
859   
860   if (II.getNumDefs() >= 1)
861     BuildMI(MBB, II, ResultReg).addReg(Op0).addImm(Idx);
862   else {
863     BuildMI(MBB, II).addReg(Op0).addImm(Idx);
864     bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
865                                          II.ImplicitDefs[0], RC, RC);
866     if (!InsertedCopy)
867       ResultReg = 0;
868   }
869   return ResultReg;
870 }