[fast-isel] Add support for the expect intrinsic.
[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 are not supported.  It is
15 // also not intended to be able to do much optimization, except in a few cases
16 // where doing optimizations reduces overall compile time.  For example, folding
17 // constants into immediate fields is often done, because it's cheap and it
18 // 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 #define DEBUG_TYPE "isel"
43 #include "llvm/CodeGen/FastISel.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/Analysis/Loads.h"
46 #include "llvm/CodeGen/Analysis.h"
47 #include "llvm/CodeGen/FunctionLoweringInfo.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineRegisterInfo.h"
51 #include "llvm/DebugInfo.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalVariable.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/Operator.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Target/TargetInstrInfo.h"
61 #include "llvm/Target/TargetLibraryInfo.h"
62 #include "llvm/Target/TargetLowering.h"
63 #include "llvm/Target/TargetMachine.h"
64 using namespace llvm;
65
66 #ifndef NDEBUG
67 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
68           "target-independent selector");
69 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
70           "target-specific selector");
71 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
72 #endif // NDEBUG
73
74 /// startNewBlock - Set the current block to which generated machine
75 /// instructions will be appended, and clear the local CSE map.
76 ///
77 void FastISel::startNewBlock() {
78   LocalValueMap.clear();
79
80   EmitStartPt = 0;
81
82   // Advance the emit start point past any EH_LABEL instructions.
83   MachineBasicBlock::iterator
84     I = FuncInfo.MBB->begin(), E = FuncInfo.MBB->end();
85   while (I != E && I->getOpcode() == TargetOpcode::EH_LABEL) {
86     EmitStartPt = I;
87     ++I;
88   }
89   LastLocalValue = EmitStartPt;
90 }
91
92 bool FastISel::LowerArguments() {
93   if (!FuncInfo.CanLowerReturn)
94     // Fallback to SDISel argument lowering code to deal with sret pointer
95     // parameter.
96     return false;
97   
98   if (!FastLowerArguments())
99     return false;
100
101   // Enter non-dead arguments into ValueMap for uses in non-entry BBs.
102   for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
103          E = FuncInfo.Fn->arg_end(); I != E; ++I) {
104     if (!I->use_empty()) {
105       DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
106       assert(VI != LocalValueMap.end() && "Missed an argument?");
107       FuncInfo.ValueMap[I] = VI->second;
108     }
109   }
110   return true;
111 }
112
113 void FastISel::flushLocalValueMap() {
114   LocalValueMap.clear();
115   LastLocalValue = EmitStartPt;
116   recomputeInsertPt();
117 }
118
119 bool FastISel::hasTrivialKill(const Value *V) const {
120   // Don't consider constants or arguments to have trivial kills.
121   const Instruction *I = dyn_cast<Instruction>(V);
122   if (!I)
123     return false;
124
125   // No-op casts are trivially coalesced by fast-isel.
126   if (const CastInst *Cast = dyn_cast<CastInst>(I))
127     if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) &&
128         !hasTrivialKill(Cast->getOperand(0)))
129       return false;
130
131   // GEPs with all zero indices are trivially coalesced by fast-isel.
132   if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
133     if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
134       return false;
135
136   // Only instructions with a single use in the same basic block are considered
137   // to have trivial kills.
138   return I->hasOneUse() &&
139          !(I->getOpcode() == Instruction::BitCast ||
140            I->getOpcode() == Instruction::PtrToInt ||
141            I->getOpcode() == Instruction::IntToPtr) &&
142          cast<Instruction>(*I->use_begin())->getParent() == I->getParent();
143 }
144
145 unsigned FastISel::getRegForValue(const Value *V) {
146   EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
147   // Don't handle non-simple values in FastISel.
148   if (!RealVT.isSimple())
149     return 0;
150
151   // Ignore illegal types. We must do this before looking up the value
152   // in ValueMap because Arguments are given virtual registers regardless
153   // of whether FastISel can handle them.
154   MVT VT = RealVT.getSimpleVT();
155   if (!TLI.isTypeLegal(VT)) {
156     // Handle integer promotions, though, because they're common and easy.
157     if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
158       VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
159     else
160       return 0;
161   }
162
163   // Look up the value to see if we already have a register for it.
164   unsigned Reg = lookUpRegForValue(V);
165   if (Reg != 0)
166     return Reg;
167
168   // In bottom-up mode, just create the virtual register which will be used
169   // to hold the value. It will be materialized later.
170   if (isa<Instruction>(V) &&
171       (!isa<AllocaInst>(V) ||
172        !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
173     return FuncInfo.InitializeRegForValue(V);
174
175   SavePoint SaveInsertPt = enterLocalValueArea();
176
177   // Materialize the value in a register. Emit any instructions in the
178   // local value area.
179   Reg = materializeRegForValue(V, VT);
180
181   leaveLocalValueArea(SaveInsertPt);
182
183   return Reg;
184 }
185
186 /// materializeRegForValue - Helper for getRegForValue. This function is
187 /// called when the value isn't already available in a register and must
188 /// be materialized with new instructions.
189 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
190   unsigned Reg = 0;
191
192   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
193     if (CI->getValue().getActiveBits() <= 64)
194       Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
195   } else if (isa<AllocaInst>(V)) {
196     Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
197   } else if (isa<ConstantPointerNull>(V)) {
198     // Translate this as an integer zero so that it can be
199     // local-CSE'd with actual integer zeros.
200     Reg =
201       getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
202   } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
203     if (CF->isNullValue()) {
204       Reg = TargetMaterializeFloatZero(CF);
205     } else {
206       // Try to emit the constant directly.
207       Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
208     }
209
210     if (!Reg) {
211       // Try to emit the constant by using an integer constant with a cast.
212       const APFloat &Flt = CF->getValueAPF();
213       EVT IntVT = TLI.getPointerTy();
214
215       uint64_t x[2];
216       uint32_t IntBitWidth = IntVT.getSizeInBits();
217       bool isExact;
218       (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
219                                   APFloat::rmTowardZero, &isExact);
220       if (isExact) {
221         APInt IntVal(IntBitWidth, x);
222
223         unsigned IntegerReg =
224           getRegForValue(ConstantInt::get(V->getContext(), IntVal));
225         if (IntegerReg != 0)
226           Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
227                            IntegerReg, /*Kill=*/false);
228       }
229     }
230   } else if (const Operator *Op = dyn_cast<Operator>(V)) {
231     if (!SelectOperator(Op, Op->getOpcode()))
232       if (!isa<Instruction>(Op) ||
233           !TargetSelectInstruction(cast<Instruction>(Op)))
234         return 0;
235     Reg = lookUpRegForValue(Op);
236   } else if (isa<UndefValue>(V)) {
237     Reg = createResultReg(TLI.getRegClassFor(VT));
238     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
239             TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
240   }
241
242   // If target-independent code couldn't handle the value, give target-specific
243   // code a try.
244   if (!Reg && isa<Constant>(V))
245     Reg = TargetMaterializeConstant(cast<Constant>(V));
246
247   // Don't cache constant materializations in the general ValueMap.
248   // To do so would require tracking what uses they dominate.
249   if (Reg != 0) {
250     LocalValueMap[V] = Reg;
251     LastLocalValue = MRI.getVRegDef(Reg);
252   }
253   return Reg;
254 }
255
256 unsigned FastISel::lookUpRegForValue(const Value *V) {
257   // Look up the value to see if we already have a register for it. We
258   // cache values defined by Instructions across blocks, and other values
259   // only locally. This is because Instructions already have the SSA
260   // def-dominates-use requirement enforced.
261   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
262   if (I != FuncInfo.ValueMap.end())
263     return I->second;
264   return LocalValueMap[V];
265 }
266
267 /// UpdateValueMap - Update the value map to include the new mapping for this
268 /// instruction, or insert an extra copy to get the result in a previous
269 /// determined register.
270 /// NOTE: This is only necessary because we might select a block that uses
271 /// a value before we select the block that defines the value.  It might be
272 /// possible to fix this by selecting blocks in reverse postorder.
273 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
274   if (!isa<Instruction>(I)) {
275     LocalValueMap[I] = Reg;
276     return;
277   }
278
279   unsigned &AssignedReg = FuncInfo.ValueMap[I];
280   if (AssignedReg == 0)
281     // Use the new register.
282     AssignedReg = Reg;
283   else if (Reg != AssignedReg) {
284     // Arrange for uses of AssignedReg to be replaced by uses of Reg.
285     for (unsigned i = 0; i < NumRegs; i++)
286       FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
287
288     AssignedReg = Reg;
289   }
290 }
291
292 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
293   unsigned IdxN = getRegForValue(Idx);
294   if (IdxN == 0)
295     // Unhandled operand. Halt "fast" selection and bail.
296     return std::pair<unsigned, bool>(0, false);
297
298   bool IdxNIsKill = hasTrivialKill(Idx);
299
300   // If the index is smaller or larger than intptr_t, truncate or extend it.
301   MVT PtrVT = TLI.getPointerTy();
302   EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
303   if (IdxVT.bitsLT(PtrVT)) {
304     IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
305                       IdxN, IdxNIsKill);
306     IdxNIsKill = true;
307   }
308   else if (IdxVT.bitsGT(PtrVT)) {
309     IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
310                       IdxN, IdxNIsKill);
311     IdxNIsKill = true;
312   }
313   return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
314 }
315
316 void FastISel::recomputeInsertPt() {
317   if (getLastLocalValue()) {
318     FuncInfo.InsertPt = getLastLocalValue();
319     FuncInfo.MBB = FuncInfo.InsertPt->getParent();
320     ++FuncInfo.InsertPt;
321   } else
322     FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
323
324   // Now skip past any EH_LABELs, which must remain at the beginning.
325   while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
326          FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
327     ++FuncInfo.InsertPt;
328 }
329
330 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
331                               MachineBasicBlock::iterator E) {
332   assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
333   while (I != E) {
334     MachineInstr *Dead = &*I;
335     ++I;
336     Dead->eraseFromParent();
337     DEBUG(++NumFastIselDead);
338   }
339   recomputeInsertPt();
340 }
341
342 FastISel::SavePoint FastISel::enterLocalValueArea() {
343   MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
344   DebugLoc OldDL = DL;
345   recomputeInsertPt();
346   DL = DebugLoc();
347   SavePoint SP = { OldInsertPt, OldDL };
348   return SP;
349 }
350
351 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
352   if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
353     LastLocalValue = llvm::prior(FuncInfo.InsertPt);
354
355   // Restore the previous insert position.
356   FuncInfo.InsertPt = OldInsertPt.InsertPt;
357   DL = OldInsertPt.DL;
358 }
359
360 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
361 /// which has an opcode which directly corresponds to the given ISD opcode.
362 ///
363 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
364   EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
365   if (VT == MVT::Other || !VT.isSimple())
366     // Unhandled type. Halt "fast" selection and bail.
367     return false;
368
369   // We only handle legal types. For example, on x86-32 the instruction
370   // selector contains all of the 64-bit instructions from x86-64,
371   // under the assumption that i64 won't be used if the target doesn't
372   // support it.
373   if (!TLI.isTypeLegal(VT)) {
374     // MVT::i1 is special. Allow AND, OR, or XOR because they
375     // don't require additional zeroing, which makes them easy.
376     if (VT == MVT::i1 &&
377         (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
378          ISDOpcode == ISD::XOR))
379       VT = TLI.getTypeToTransformTo(I->getContext(), VT);
380     else
381       return false;
382   }
383
384   // Check if the first operand is a constant, and handle it as "ri".  At -O0,
385   // we don't have anything that canonicalizes operand order.
386   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
387     if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
388       unsigned Op1 = getRegForValue(I->getOperand(1));
389       if (Op1 == 0) return false;
390
391       bool Op1IsKill = hasTrivialKill(I->getOperand(1));
392
393       unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
394                                         Op1IsKill, CI->getZExtValue(),
395                                         VT.getSimpleVT());
396       if (ResultReg == 0) return false;
397
398       // We successfully emitted code for the given LLVM Instruction.
399       UpdateValueMap(I, ResultReg);
400       return true;
401     }
402
403
404   unsigned Op0 = getRegForValue(I->getOperand(0));
405   if (Op0 == 0)   // Unhandled operand. Halt "fast" selection and bail.
406     return false;
407
408   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
409
410   // Check if the second operand is a constant and handle it appropriately.
411   if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
412     uint64_t Imm = CI->getZExtValue();
413
414     // Transform "sdiv exact X, 8" -> "sra X, 3".
415     if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
416         cast<BinaryOperator>(I)->isExact() &&
417         isPowerOf2_64(Imm)) {
418       Imm = Log2_64(Imm);
419       ISDOpcode = ISD::SRA;
420     }
421
422     // Transform "urem x, pow2" -> "and x, pow2-1".
423     if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
424         isPowerOf2_64(Imm)) {
425       --Imm;
426       ISDOpcode = ISD::AND;
427     }
428
429     unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
430                                       Op0IsKill, Imm, VT.getSimpleVT());
431     if (ResultReg == 0) return false;
432
433     // We successfully emitted code for the given LLVM Instruction.
434     UpdateValueMap(I, ResultReg);
435     return true;
436   }
437
438   // Check if the second operand is a constant float.
439   if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
440     unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
441                                      ISDOpcode, Op0, Op0IsKill, CF);
442     if (ResultReg != 0) {
443       // We successfully emitted code for the given LLVM Instruction.
444       UpdateValueMap(I, ResultReg);
445       return true;
446     }
447   }
448
449   unsigned Op1 = getRegForValue(I->getOperand(1));
450   if (Op1 == 0)
451     // Unhandled operand. Halt "fast" selection and bail.
452     return false;
453
454   bool Op1IsKill = hasTrivialKill(I->getOperand(1));
455
456   // Now we have both operands in registers. Emit the instruction.
457   unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
458                                    ISDOpcode,
459                                    Op0, Op0IsKill,
460                                    Op1, Op1IsKill);
461   if (ResultReg == 0)
462     // Target-specific code wasn't able to find a machine opcode for
463     // the given ISD opcode and type. Halt "fast" selection and bail.
464     return false;
465
466   // We successfully emitted code for the given LLVM Instruction.
467   UpdateValueMap(I, ResultReg);
468   return true;
469 }
470
471 bool FastISel::SelectGetElementPtr(const User *I) {
472   unsigned N = getRegForValue(I->getOperand(0));
473   if (N == 0)
474     // Unhandled operand. Halt "fast" selection and bail.
475     return false;
476
477   bool NIsKill = hasTrivialKill(I->getOperand(0));
478
479   // Keep a running tab of the total offset to coalesce multiple N = N + Offset
480   // into a single N = N + TotalOffset.
481   uint64_t TotalOffs = 0;
482   // FIXME: What's a good SWAG number for MaxOffs?
483   uint64_t MaxOffs = 2048;
484   Type *Ty = I->getOperand(0)->getType();
485   MVT VT = TLI.getPointerTy();
486   for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
487        E = I->op_end(); OI != E; ++OI) {
488     const Value *Idx = *OI;
489     if (StructType *StTy = dyn_cast<StructType>(Ty)) {
490       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
491       if (Field) {
492         // N = N + Offset
493         TotalOffs += TD.getStructLayout(StTy)->getElementOffset(Field);
494         if (TotalOffs >= MaxOffs) {
495           N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
496           if (N == 0)
497             // Unhandled operand. Halt "fast" selection and bail.
498             return false;
499           NIsKill = true;
500           TotalOffs = 0;
501         }
502       }
503       Ty = StTy->getElementType(Field);
504     } else {
505       Ty = cast<SequentialType>(Ty)->getElementType();
506
507       // If this is a constant subscript, handle it quickly.
508       if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
509         if (CI->isZero()) continue;
510         // N = N + Offset
511         TotalOffs +=
512           TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
513         if (TotalOffs >= MaxOffs) {
514           N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
515           if (N == 0)
516             // Unhandled operand. Halt "fast" selection and bail.
517             return false;
518           NIsKill = true;
519           TotalOffs = 0;
520         }
521         continue;
522       }
523       if (TotalOffs) {
524         N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
525         if (N == 0)
526           // Unhandled operand. Halt "fast" selection and bail.
527           return false;
528         NIsKill = true;
529         TotalOffs = 0;
530       }
531
532       // N = N + Idx * ElementSize;
533       uint64_t ElementSize = TD.getTypeAllocSize(Ty);
534       std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
535       unsigned IdxN = Pair.first;
536       bool IdxNIsKill = Pair.second;
537       if (IdxN == 0)
538         // Unhandled operand. Halt "fast" selection and bail.
539         return false;
540
541       if (ElementSize != 1) {
542         IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
543         if (IdxN == 0)
544           // Unhandled operand. Halt "fast" selection and bail.
545           return false;
546         IdxNIsKill = true;
547       }
548       N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
549       if (N == 0)
550         // Unhandled operand. Halt "fast" selection and bail.
551         return false;
552     }
553   }
554   if (TotalOffs) {
555     N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
556     if (N == 0)
557       // Unhandled operand. Halt "fast" selection and bail.
558       return false;
559   }
560
561   // We successfully emitted code for the given LLVM Instruction.
562   UpdateValueMap(I, N);
563   return true;
564 }
565
566 bool FastISel::SelectCall(const User *I) {
567   const CallInst *Call = cast<CallInst>(I);
568
569   // Handle simple inline asms.
570   if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
571     // Don't attempt to handle constraints.
572     if (!IA->getConstraintString().empty())
573       return false;
574
575     unsigned ExtraInfo = 0;
576     if (IA->hasSideEffects())
577       ExtraInfo |= InlineAsm::Extra_HasSideEffects;
578     if (IA->isAlignStack())
579       ExtraInfo |= InlineAsm::Extra_IsAlignStack;
580
581     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
582             TII.get(TargetOpcode::INLINEASM))
583       .addExternalSymbol(IA->getAsmString().c_str())
584       .addImm(ExtraInfo);
585     return true;
586   }
587
588   MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
589   ComputeUsesVAFloatArgument(*Call, &MMI);
590
591   const Function *F = Call->getCalledFunction();
592   if (!F) return false;
593
594   // Handle selected intrinsic function calls.
595   switch (F->getIntrinsicID()) {
596   default: break;
597     // At -O0 we don't care about the lifetime intrinsics.
598   case Intrinsic::lifetime_start:
599   case Intrinsic::lifetime_end:
600     // The donothing intrinsic does, well, nothing.
601   case Intrinsic::donothing:
602     return true;
603
604   case Intrinsic::dbg_declare: {
605     const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
606     if (!DIVariable(DI->getVariable()).Verify() ||
607         !FuncInfo.MF->getMMI().hasDebugInfo()) {
608       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
609       return true;
610     }
611
612     const Value *Address = DI->getAddress();
613     if (!Address || isa<UndefValue>(Address)) {
614       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
615       return true;
616     }
617
618     unsigned Reg = 0;
619     unsigned Offset = 0;
620     if (const Argument *Arg = dyn_cast<Argument>(Address)) {
621       // Some arguments' frame index is recorded during argument lowering.
622       Offset = FuncInfo.getArgumentFrameIndex(Arg);
623       if (Offset)
624         Reg = TRI.getFrameRegister(*FuncInfo.MF);
625     }
626     if (!Reg)
627       Reg = lookUpRegForValue(Address);
628
629     // If we have a VLA that has a "use" in a metadata node that's then used
630     // here but it has no other uses, then we have a problem. E.g.,
631     //
632     //   int foo (const int *x) {
633     //     char a[*x];
634     //     return 0;
635     //   }
636     //
637     // If we assign 'a' a vreg and fast isel later on has to use the selection
638     // DAG isel, it will want to copy the value to the vreg. However, there are
639     // no uses, which goes counter to what selection DAG isel expects.
640     if (!Reg && !Address->use_empty() && isa<Instruction>(Address) &&
641         (!isa<AllocaInst>(Address) ||
642          !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
643       Reg = FuncInfo.InitializeRegForValue(Address);
644
645     if (Reg)
646       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
647               TII.get(TargetOpcode::DBG_VALUE))
648         .addReg(Reg, RegState::Debug).addImm(Offset)
649         .addMetadata(DI->getVariable());
650     else
651       // We can't yet handle anything else here because it would require
652       // generating code, thus altering codegen because of debug info.
653       DEBUG(dbgs() << "Dropping debug info for " << DI);
654     return true;
655   }
656   case Intrinsic::dbg_value: {
657     // This form of DBG_VALUE is target-independent.
658     const DbgValueInst *DI = cast<DbgValueInst>(Call);
659     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
660     const Value *V = DI->getValue();
661     if (!V) {
662       // Currently the optimizer can produce this; insert an undef to
663       // help debugging.  Probably the optimizer should not do this.
664       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
665         .addReg(0U).addImm(DI->getOffset())
666         .addMetadata(DI->getVariable());
667     } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
668       if (CI->getBitWidth() > 64)
669         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
670           .addCImm(CI).addImm(DI->getOffset())
671           .addMetadata(DI->getVariable());
672       else
673         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
674           .addImm(CI->getZExtValue()).addImm(DI->getOffset())
675           .addMetadata(DI->getVariable());
676     } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
677       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
678         .addFPImm(CF).addImm(DI->getOffset())
679         .addMetadata(DI->getVariable());
680     } else if (unsigned Reg = lookUpRegForValue(V)) {
681       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
682         .addReg(Reg, RegState::Debug).addImm(DI->getOffset())
683         .addMetadata(DI->getVariable());
684     } else {
685       // We can't yet handle anything else here because it would require
686       // generating code, thus altering codegen because of debug info.
687       DEBUG(dbgs() << "Dropping debug info for " << DI);
688     }
689     return true;
690   }
691   case Intrinsic::objectsize: {
692     ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
693     unsigned long long Res = CI->isZero() ? -1ULL : 0;
694     Constant *ResCI = ConstantInt::get(Call->getType(), Res);
695     unsigned ResultReg = getRegForValue(ResCI);
696     if (ResultReg == 0)
697       return false;
698     UpdateValueMap(Call, ResultReg);
699     return true;
700   }
701   case Intrinsic::expect: {
702 //    unsigned ResultReg = getRegForValue(Call->getArgOperand(0));
703 //    UpdateValueMap(Call, ResultReg);
704 //    return true;
705   }
706   }
707
708   // Usually, it does not make sense to initialize a value,
709   // make an unrelated function call and use the value, because
710   // it tends to be spilled on the stack. So, we move the pointer
711   // to the last local value to the beginning of the block, so that
712   // all the values which have already been materialized,
713   // appear after the call. It also makes sense to skip intrinsics
714   // since they tend to be inlined.
715   if (!isa<IntrinsicInst>(Call))
716     flushLocalValueMap();
717
718   // An arbitrary call. Bail.
719   return false;
720 }
721
722 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
723   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
724   EVT DstVT = TLI.getValueType(I->getType());
725
726   if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
727       DstVT == MVT::Other || !DstVT.isSimple())
728     // Unhandled type. Halt "fast" selection and bail.
729     return false;
730
731   // Check if the destination type is legal.
732   if (!TLI.isTypeLegal(DstVT))
733     return false;
734
735   // Check if the source operand is legal.
736   if (!TLI.isTypeLegal(SrcVT))
737     return false;
738
739   unsigned InputReg = getRegForValue(I->getOperand(0));
740   if (!InputReg)
741     // Unhandled operand.  Halt "fast" selection and bail.
742     return false;
743
744   bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
745
746   unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
747                                   DstVT.getSimpleVT(),
748                                   Opcode,
749                                   InputReg, InputRegIsKill);
750   if (!ResultReg)
751     return false;
752
753   UpdateValueMap(I, ResultReg);
754   return true;
755 }
756
757 bool FastISel::SelectBitCast(const User *I) {
758   // If the bitcast doesn't change the type, just use the operand value.
759   if (I->getType() == I->getOperand(0)->getType()) {
760     unsigned Reg = getRegForValue(I->getOperand(0));
761     if (Reg == 0)
762       return false;
763     UpdateValueMap(I, Reg);
764     return true;
765   }
766
767   // Bitcasts of other values become reg-reg copies or BITCAST operators.
768   EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
769   EVT DstEVT = TLI.getValueType(I->getType());
770   if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
771       !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
772     // Unhandled type. Halt "fast" selection and bail.
773     return false;
774
775   MVT SrcVT = SrcEVT.getSimpleVT();
776   MVT DstVT = DstEVT.getSimpleVT();
777   unsigned Op0 = getRegForValue(I->getOperand(0));
778   if (Op0 == 0)
779     // Unhandled operand. Halt "fast" selection and bail.
780     return false;
781
782   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
783
784   // First, try to perform the bitcast by inserting a reg-reg copy.
785   unsigned ResultReg = 0;
786   if (SrcVT == DstVT) {
787     const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
788     const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
789     // Don't attempt a cross-class copy. It will likely fail.
790     if (SrcClass == DstClass) {
791       ResultReg = createResultReg(DstClass);
792       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
793               ResultReg).addReg(Op0);
794     }
795   }
796
797   // If the reg-reg copy failed, select a BITCAST opcode.
798   if (!ResultReg)
799     ResultReg = FastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
800
801   if (!ResultReg)
802     return false;
803
804   UpdateValueMap(I, ResultReg);
805   return true;
806 }
807
808 bool
809 FastISel::SelectInstruction(const Instruction *I) {
810   // Just before the terminator instruction, insert instructions to
811   // feed PHI nodes in successor blocks.
812   if (isa<TerminatorInst>(I))
813     if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
814       return false;
815
816   DL = I->getDebugLoc();
817
818   MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
819
820   // As a special case, don't handle calls to builtin library functions that
821   // may be translated directly to target instructions.
822   if (const CallInst *Call = dyn_cast<CallInst>(I)) {
823     const Function *F = Call->getCalledFunction();
824     LibFunc::Func Func;
825     if (F && !F->hasLocalLinkage() && F->hasName() &&
826         LibInfo->getLibFunc(F->getName(), Func) &&
827         LibInfo->hasOptimizedCodeGen(Func))
828       return false;
829   }
830
831   // First, try doing target-independent selection.
832   if (SelectOperator(I, I->getOpcode())) {
833     DEBUG(++NumFastIselSuccessIndependent);
834     DL = DebugLoc();
835     return true;
836   }
837   // Remove dead code.  However, ignore call instructions since we've flushed
838   // the local value map and recomputed the insert point.
839   if (!isa<CallInst>(I)) {
840     recomputeInsertPt();
841     if (SavedInsertPt != FuncInfo.InsertPt)
842       removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
843   }
844
845   // Next, try calling the target to attempt to handle the instruction.
846   SavedInsertPt = FuncInfo.InsertPt;
847   if (TargetSelectInstruction(I)) {
848     DEBUG(++NumFastIselSuccessTarget);
849     DL = DebugLoc();
850     return true;
851   }
852   // Check for dead code and remove as necessary.
853   recomputeInsertPt();
854   if (SavedInsertPt != FuncInfo.InsertPt)
855     removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
856
857   DL = DebugLoc();
858   return false;
859 }
860
861 /// FastEmitBranch - Emit an unconditional branch to the given block,
862 /// unless it is the immediate (fall-through) successor, and update
863 /// the CFG.
864 void
865 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
866
867   if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
868       FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
869     // For more accurate line information if this is the only instruction
870     // in the block then emit it, otherwise we have the unconditional
871     // fall-through case, which needs no instructions.
872   } else {
873     // The unconditional branch case.
874     TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
875                      SmallVector<MachineOperand, 0>(), DL);
876   }
877   FuncInfo.MBB->addSuccessor(MSucc);
878 }
879
880 /// SelectFNeg - Emit an FNeg operation.
881 ///
882 bool
883 FastISel::SelectFNeg(const User *I) {
884   unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
885   if (OpReg == 0) return false;
886
887   bool OpRegIsKill = hasTrivialKill(I);
888
889   // If the target has ISD::FNEG, use it.
890   EVT VT = TLI.getValueType(I->getType());
891   unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
892                                   ISD::FNEG, OpReg, OpRegIsKill);
893   if (ResultReg != 0) {
894     UpdateValueMap(I, ResultReg);
895     return true;
896   }
897
898   // Bitcast the value to integer, twiddle the sign bit with xor,
899   // and then bitcast it back to floating-point.
900   if (VT.getSizeInBits() > 64) return false;
901   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
902   if (!TLI.isTypeLegal(IntVT))
903     return false;
904
905   unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
906                                ISD::BITCAST, OpReg, OpRegIsKill);
907   if (IntReg == 0)
908     return false;
909
910   unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
911                                        IntReg, /*Kill=*/true,
912                                        UINT64_C(1) << (VT.getSizeInBits()-1),
913                                        IntVT.getSimpleVT());
914   if (IntResultReg == 0)
915     return false;
916
917   ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
918                          ISD::BITCAST, IntResultReg, /*Kill=*/true);
919   if (ResultReg == 0)
920     return false;
921
922   UpdateValueMap(I, ResultReg);
923   return true;
924 }
925
926 bool
927 FastISel::SelectExtractValue(const User *U) {
928   const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
929   if (!EVI)
930     return false;
931
932   // Make sure we only try to handle extracts with a legal result.  But also
933   // allow i1 because it's easy.
934   EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
935   if (!RealVT.isSimple())
936     return false;
937   MVT VT = RealVT.getSimpleVT();
938   if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
939     return false;
940
941   const Value *Op0 = EVI->getOperand(0);
942   Type *AggTy = Op0->getType();
943
944   // Get the base result register.
945   unsigned ResultReg;
946   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
947   if (I != FuncInfo.ValueMap.end())
948     ResultReg = I->second;
949   else if (isa<Instruction>(Op0))
950     ResultReg = FuncInfo.InitializeRegForValue(Op0);
951   else
952     return false; // fast-isel can't handle aggregate constants at the moment
953
954   // Get the actual result register, which is an offset from the base register.
955   unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
956
957   SmallVector<EVT, 4> AggValueVTs;
958   ComputeValueVTs(TLI, AggTy, AggValueVTs);
959
960   for (unsigned i = 0; i < VTIndex; i++)
961     ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
962
963   UpdateValueMap(EVI, ResultReg);
964   return true;
965 }
966
967 bool
968 FastISel::SelectOperator(const User *I, unsigned Opcode) {
969   switch (Opcode) {
970   case Instruction::Add:
971     return SelectBinaryOp(I, ISD::ADD);
972   case Instruction::FAdd:
973     return SelectBinaryOp(I, ISD::FADD);
974   case Instruction::Sub:
975     return SelectBinaryOp(I, ISD::SUB);
976   case Instruction::FSub:
977     // FNeg is currently represented in LLVM IR as a special case of FSub.
978     if (BinaryOperator::isFNeg(I))
979       return SelectFNeg(I);
980     return SelectBinaryOp(I, ISD::FSUB);
981   case Instruction::Mul:
982     return SelectBinaryOp(I, ISD::MUL);
983   case Instruction::FMul:
984     return SelectBinaryOp(I, ISD::FMUL);
985   case Instruction::SDiv:
986     return SelectBinaryOp(I, ISD::SDIV);
987   case Instruction::UDiv:
988     return SelectBinaryOp(I, ISD::UDIV);
989   case Instruction::FDiv:
990     return SelectBinaryOp(I, ISD::FDIV);
991   case Instruction::SRem:
992     return SelectBinaryOp(I, ISD::SREM);
993   case Instruction::URem:
994     return SelectBinaryOp(I, ISD::UREM);
995   case Instruction::FRem:
996     return SelectBinaryOp(I, ISD::FREM);
997   case Instruction::Shl:
998     return SelectBinaryOp(I, ISD::SHL);
999   case Instruction::LShr:
1000     return SelectBinaryOp(I, ISD::SRL);
1001   case Instruction::AShr:
1002     return SelectBinaryOp(I, ISD::SRA);
1003   case Instruction::And:
1004     return SelectBinaryOp(I, ISD::AND);
1005   case Instruction::Or:
1006     return SelectBinaryOp(I, ISD::OR);
1007   case Instruction::Xor:
1008     return SelectBinaryOp(I, ISD::XOR);
1009
1010   case Instruction::GetElementPtr:
1011     return SelectGetElementPtr(I);
1012
1013   case Instruction::Br: {
1014     const BranchInst *BI = cast<BranchInst>(I);
1015
1016     if (BI->isUnconditional()) {
1017       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
1018       MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
1019       FastEmitBranch(MSucc, BI->getDebugLoc());
1020       return true;
1021     }
1022
1023     // Conditional branches are not handed yet.
1024     // Halt "fast" selection and bail.
1025     return false;
1026   }
1027
1028   case Instruction::Unreachable:
1029     // Nothing to emit.
1030     return true;
1031
1032   case Instruction::Alloca:
1033     // FunctionLowering has the static-sized case covered.
1034     if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1035       return true;
1036
1037     // Dynamic-sized alloca is not handled yet.
1038     return false;
1039
1040   case Instruction::Call:
1041     return SelectCall(I);
1042
1043   case Instruction::BitCast:
1044     return SelectBitCast(I);
1045
1046   case Instruction::FPToSI:
1047     return SelectCast(I, ISD::FP_TO_SINT);
1048   case Instruction::ZExt:
1049     return SelectCast(I, ISD::ZERO_EXTEND);
1050   case Instruction::SExt:
1051     return SelectCast(I, ISD::SIGN_EXTEND);
1052   case Instruction::Trunc:
1053     return SelectCast(I, ISD::TRUNCATE);
1054   case Instruction::SIToFP:
1055     return SelectCast(I, ISD::SINT_TO_FP);
1056
1057   case Instruction::IntToPtr: // Deliberate fall-through.
1058   case Instruction::PtrToInt: {
1059     EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1060     EVT DstVT = TLI.getValueType(I->getType());
1061     if (DstVT.bitsGT(SrcVT))
1062       return SelectCast(I, ISD::ZERO_EXTEND);
1063     if (DstVT.bitsLT(SrcVT))
1064       return SelectCast(I, ISD::TRUNCATE);
1065     unsigned Reg = getRegForValue(I->getOperand(0));
1066     if (Reg == 0) return false;
1067     UpdateValueMap(I, Reg);
1068     return true;
1069   }
1070
1071   case Instruction::ExtractValue:
1072     return SelectExtractValue(I);
1073
1074   case Instruction::PHI:
1075     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1076
1077   default:
1078     // Unhandled instruction. Halt "fast" selection and bail.
1079     return false;
1080   }
1081 }
1082
1083 FastISel::FastISel(FunctionLoweringInfo &funcInfo,
1084                    const TargetLibraryInfo *libInfo)
1085   : FuncInfo(funcInfo),
1086     MRI(FuncInfo.MF->getRegInfo()),
1087     MFI(*FuncInfo.MF->getFrameInfo()),
1088     MCP(*FuncInfo.MF->getConstantPool()),
1089     TM(FuncInfo.MF->getTarget()),
1090     TD(*TM.getDataLayout()),
1091     TII(*TM.getInstrInfo()),
1092     TLI(*TM.getTargetLowering()),
1093     TRI(*TM.getRegisterInfo()),
1094     LibInfo(libInfo) {
1095 }
1096
1097 FastISel::~FastISel() {}
1098
1099 bool FastISel::FastLowerArguments() {
1100   return false;
1101 }
1102
1103 unsigned FastISel::FastEmit_(MVT, MVT,
1104                              unsigned) {
1105   return 0;
1106 }
1107
1108 unsigned FastISel::FastEmit_r(MVT, MVT,
1109                               unsigned,
1110                               unsigned /*Op0*/, bool /*Op0IsKill*/) {
1111   return 0;
1112 }
1113
1114 unsigned FastISel::FastEmit_rr(MVT, MVT,
1115                                unsigned,
1116                                unsigned /*Op0*/, bool /*Op0IsKill*/,
1117                                unsigned /*Op1*/, bool /*Op1IsKill*/) {
1118   return 0;
1119 }
1120
1121 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1122   return 0;
1123 }
1124
1125 unsigned FastISel::FastEmit_f(MVT, MVT,
1126                               unsigned, const ConstantFP * /*FPImm*/) {
1127   return 0;
1128 }
1129
1130 unsigned FastISel::FastEmit_ri(MVT, MVT,
1131                                unsigned,
1132                                unsigned /*Op0*/, bool /*Op0IsKill*/,
1133                                uint64_t /*Imm*/) {
1134   return 0;
1135 }
1136
1137 unsigned FastISel::FastEmit_rf(MVT, MVT,
1138                                unsigned,
1139                                unsigned /*Op0*/, bool /*Op0IsKill*/,
1140                                const ConstantFP * /*FPImm*/) {
1141   return 0;
1142 }
1143
1144 unsigned FastISel::FastEmit_rri(MVT, MVT,
1145                                 unsigned,
1146                                 unsigned /*Op0*/, bool /*Op0IsKill*/,
1147                                 unsigned /*Op1*/, bool /*Op1IsKill*/,
1148                                 uint64_t /*Imm*/) {
1149   return 0;
1150 }
1151
1152 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1153 /// to emit an instruction with an immediate operand using FastEmit_ri.
1154 /// If that fails, it materializes the immediate into a register and try
1155 /// FastEmit_rr instead.
1156 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1157                                 unsigned Op0, bool Op0IsKill,
1158                                 uint64_t Imm, MVT ImmType) {
1159   // If this is a multiply by a power of two, emit this as a shift left.
1160   if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1161     Opcode = ISD::SHL;
1162     Imm = Log2_64(Imm);
1163   } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1164     // div x, 8 -> srl x, 3
1165     Opcode = ISD::SRL;
1166     Imm = Log2_64(Imm);
1167   }
1168
1169   // Horrible hack (to be removed), check to make sure shift amounts are
1170   // in-range.
1171   if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1172       Imm >= VT.getSizeInBits())
1173     return 0;
1174
1175   // First check if immediate type is legal. If not, we can't use the ri form.
1176   unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1177   if (ResultReg != 0)
1178     return ResultReg;
1179   unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1180   if (MaterialReg == 0) {
1181     // This is a bit ugly/slow, but failing here means falling out of
1182     // fast-isel, which would be very slow.
1183     IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1184                                               VT.getSizeInBits());
1185     MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1186   }
1187   return FastEmit_rr(VT, VT, Opcode,
1188                      Op0, Op0IsKill,
1189                      MaterialReg, /*Kill=*/true);
1190 }
1191
1192 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1193   return MRI.createVirtualRegister(RC);
1194 }
1195
1196 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1197                                  const TargetRegisterClass* RC) {
1198   unsigned ResultReg = createResultReg(RC);
1199   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1200
1201   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1202   return ResultReg;
1203 }
1204
1205 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1206                                   const TargetRegisterClass *RC,
1207                                   unsigned Op0, bool Op0IsKill) {
1208   unsigned ResultReg = createResultReg(RC);
1209   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1210
1211   if (II.getNumDefs() >= 1)
1212     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1213       .addReg(Op0, Op0IsKill * RegState::Kill);
1214   else {
1215     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1216       .addReg(Op0, Op0IsKill * RegState::Kill);
1217     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1218             ResultReg).addReg(II.ImplicitDefs[0]);
1219   }
1220
1221   return ResultReg;
1222 }
1223
1224 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1225                                    const TargetRegisterClass *RC,
1226                                    unsigned Op0, bool Op0IsKill,
1227                                    unsigned Op1, bool Op1IsKill) {
1228   unsigned ResultReg = createResultReg(RC);
1229   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1230
1231   if (II.getNumDefs() >= 1)
1232     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1233       .addReg(Op0, Op0IsKill * RegState::Kill)
1234       .addReg(Op1, Op1IsKill * RegState::Kill);
1235   else {
1236     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1237       .addReg(Op0, Op0IsKill * RegState::Kill)
1238       .addReg(Op1, Op1IsKill * RegState::Kill);
1239     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1240             ResultReg).addReg(II.ImplicitDefs[0]);
1241   }
1242   return ResultReg;
1243 }
1244
1245 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1246                                    const TargetRegisterClass *RC,
1247                                    unsigned Op0, bool Op0IsKill,
1248                                    unsigned Op1, bool Op1IsKill,
1249                                    unsigned Op2, bool Op2IsKill) {
1250   unsigned ResultReg = createResultReg(RC);
1251   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1252
1253   if (II.getNumDefs() >= 1)
1254     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1255       .addReg(Op0, Op0IsKill * RegState::Kill)
1256       .addReg(Op1, Op1IsKill * RegState::Kill)
1257       .addReg(Op2, Op2IsKill * RegState::Kill);
1258   else {
1259     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1260       .addReg(Op0, Op0IsKill * RegState::Kill)
1261       .addReg(Op1, Op1IsKill * RegState::Kill)
1262       .addReg(Op2, Op2IsKill * RegState::Kill);
1263     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1264             ResultReg).addReg(II.ImplicitDefs[0]);
1265   }
1266   return ResultReg;
1267 }
1268
1269 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1270                                    const TargetRegisterClass *RC,
1271                                    unsigned Op0, bool Op0IsKill,
1272                                    uint64_t Imm) {
1273   unsigned ResultReg = createResultReg(RC);
1274   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1275
1276   if (II.getNumDefs() >= 1)
1277     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1278       .addReg(Op0, Op0IsKill * RegState::Kill)
1279       .addImm(Imm);
1280   else {
1281     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1282       .addReg(Op0, Op0IsKill * RegState::Kill)
1283       .addImm(Imm);
1284     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1285             ResultReg).addReg(II.ImplicitDefs[0]);
1286   }
1287   return ResultReg;
1288 }
1289
1290 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
1291                                    const TargetRegisterClass *RC,
1292                                    unsigned Op0, bool Op0IsKill,
1293                                    uint64_t Imm1, uint64_t Imm2) {
1294   unsigned ResultReg = createResultReg(RC);
1295   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1296
1297   if (II.getNumDefs() >= 1)
1298     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1299       .addReg(Op0, Op0IsKill * RegState::Kill)
1300       .addImm(Imm1)
1301       .addImm(Imm2);
1302   else {
1303     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1304       .addReg(Op0, Op0IsKill * RegState::Kill)
1305       .addImm(Imm1)
1306       .addImm(Imm2);
1307     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1308             ResultReg).addReg(II.ImplicitDefs[0]);
1309   }
1310   return ResultReg;
1311 }
1312
1313 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1314                                    const TargetRegisterClass *RC,
1315                                    unsigned Op0, bool Op0IsKill,
1316                                    const ConstantFP *FPImm) {
1317   unsigned ResultReg = createResultReg(RC);
1318   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1319
1320   if (II.getNumDefs() >= 1)
1321     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1322       .addReg(Op0, Op0IsKill * RegState::Kill)
1323       .addFPImm(FPImm);
1324   else {
1325     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1326       .addReg(Op0, Op0IsKill * RegState::Kill)
1327       .addFPImm(FPImm);
1328     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1329             ResultReg).addReg(II.ImplicitDefs[0]);
1330   }
1331   return ResultReg;
1332 }
1333
1334 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1335                                     const TargetRegisterClass *RC,
1336                                     unsigned Op0, bool Op0IsKill,
1337                                     unsigned Op1, bool Op1IsKill,
1338                                     uint64_t Imm) {
1339   unsigned ResultReg = createResultReg(RC);
1340   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1341
1342   if (II.getNumDefs() >= 1)
1343     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1344       .addReg(Op0, Op0IsKill * RegState::Kill)
1345       .addReg(Op1, Op1IsKill * RegState::Kill)
1346       .addImm(Imm);
1347   else {
1348     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1349       .addReg(Op0, Op0IsKill * RegState::Kill)
1350       .addReg(Op1, Op1IsKill * RegState::Kill)
1351       .addImm(Imm);
1352     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1353             ResultReg).addReg(II.ImplicitDefs[0]);
1354   }
1355   return ResultReg;
1356 }
1357
1358 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode,
1359                                      const TargetRegisterClass *RC,
1360                                      unsigned Op0, bool Op0IsKill,
1361                                      unsigned Op1, bool Op1IsKill,
1362                                      uint64_t Imm1, uint64_t Imm2) {
1363   unsigned ResultReg = createResultReg(RC);
1364   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1365
1366   if (II.getNumDefs() >= 1)
1367     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1368       .addReg(Op0, Op0IsKill * RegState::Kill)
1369       .addReg(Op1, Op1IsKill * RegState::Kill)
1370       .addImm(Imm1).addImm(Imm2);
1371   else {
1372     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1373       .addReg(Op0, Op0IsKill * RegState::Kill)
1374       .addReg(Op1, Op1IsKill * RegState::Kill)
1375       .addImm(Imm1).addImm(Imm2);
1376     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1377             ResultReg).addReg(II.ImplicitDefs[0]);
1378   }
1379   return ResultReg;
1380 }
1381
1382 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1383                                   const TargetRegisterClass *RC,
1384                                   uint64_t Imm) {
1385   unsigned ResultReg = createResultReg(RC);
1386   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1387
1388   if (II.getNumDefs() >= 1)
1389     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1390   else {
1391     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1392     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1393             ResultReg).addReg(II.ImplicitDefs[0]);
1394   }
1395   return ResultReg;
1396 }
1397
1398 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1399                                   const TargetRegisterClass *RC,
1400                                   uint64_t Imm1, uint64_t Imm2) {
1401   unsigned ResultReg = createResultReg(RC);
1402   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1403
1404   if (II.getNumDefs() >= 1)
1405     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1406       .addImm(Imm1).addImm(Imm2);
1407   else {
1408     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2);
1409     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1410             ResultReg).addReg(II.ImplicitDefs[0]);
1411   }
1412   return ResultReg;
1413 }
1414
1415 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1416                                               unsigned Op0, bool Op0IsKill,
1417                                               uint32_t Idx) {
1418   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1419   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1420          "Cannot yet extract from physregs");
1421   const TargetRegisterClass *RC = MRI.getRegClass(Op0);
1422   MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
1423   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1424           DL, TII.get(TargetOpcode::COPY), ResultReg)
1425     .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1426   return ResultReg;
1427 }
1428
1429 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1430 /// with all but the least significant bit set to zero.
1431 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1432   return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1433 }
1434
1435 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1436 /// Emit code to ensure constants are copied into registers when needed.
1437 /// Remember the virtual registers that need to be added to the Machine PHI
1438 /// nodes as input.  We cannot just directly add them, because expansion
1439 /// might result in multiple MBB's for one BB.  As such, the start of the
1440 /// BB might correspond to a different MBB than the end.
1441 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1442   const TerminatorInst *TI = LLVMBB->getTerminator();
1443
1444   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1445   unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1446
1447   // Check successor nodes' PHI nodes that expect a constant to be available
1448   // from this block.
1449   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1450     const BasicBlock *SuccBB = TI->getSuccessor(succ);
1451     if (!isa<PHINode>(SuccBB->begin())) continue;
1452     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1453
1454     // If this terminator has multiple identical successors (common for
1455     // switches), only handle each succ once.
1456     if (!SuccsHandled.insert(SuccMBB)) continue;
1457
1458     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1459
1460     // At this point we know that there is a 1-1 correspondence between LLVM PHI
1461     // nodes and Machine PHI nodes, but the incoming operands have not been
1462     // emitted yet.
1463     for (BasicBlock::const_iterator I = SuccBB->begin();
1464          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1465
1466       // Ignore dead phi's.
1467       if (PN->use_empty()) continue;
1468
1469       // Only handle legal types. Two interesting things to note here. First,
1470       // by bailing out early, we may leave behind some dead instructions,
1471       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1472       // own moves. Second, this check is necessary because FastISel doesn't
1473       // use CreateRegs to create registers, so it always creates
1474       // exactly one register for each non-void instruction.
1475       EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1476       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1477         // Handle integer promotions, though, because they're common and easy.
1478         if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1479           VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1480         else {
1481           FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1482           return false;
1483         }
1484       }
1485
1486       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1487
1488       // Set the DebugLoc for the copy. Prefer the location of the operand
1489       // if there is one; use the location of the PHI otherwise.
1490       DL = PN->getDebugLoc();
1491       if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1492         DL = Inst->getDebugLoc();
1493
1494       unsigned Reg = getRegForValue(PHIOp);
1495       if (Reg == 0) {
1496         FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1497         return false;
1498       }
1499       FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
1500       DL = DebugLoc();
1501     }
1502   }
1503
1504   return true;
1505 }