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