Right now DBG_LABEL are required for llvm.dbg.region_start and llvm.dbg.region_end...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuild.cpp
1 //===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
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 implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuild.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Module.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/GCMetadata.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/CodeGen/DwarfWriter.h"
41 #include "llvm/Analysis/DebugInfo.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetFrameInfo.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetIntrinsicInfo.h"
47 #include "llvm/Target/TargetLowering.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include <algorithm>
56 using namespace llvm;
57
58 /// LimitFloatPrecision - Generate low-precision inline sequences for
59 /// some float libcalls (6, 8 or 12 bits).
60 static unsigned LimitFloatPrecision;
61
62 static cl::opt<unsigned, true>
63 LimitFPPrecision("limit-float-precision",
64                  cl::desc("Generate low-precision inline sequences "
65                           "for some float libcalls"),
66                  cl::location(LimitFloatPrecision),
67                  cl::init(0));
68
69 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
70 /// of insertvalue or extractvalue indices that identify a member, return
71 /// the linearized index of the start of the member.
72 ///
73 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
74                                    const unsigned *Indices,
75                                    const unsigned *IndicesEnd,
76                                    unsigned CurIndex = 0) {
77   // Base case: We're done.
78   if (Indices && Indices == IndicesEnd)
79     return CurIndex;
80
81   // Given a struct type, recursively traverse the elements.
82   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
83     for (StructType::element_iterator EB = STy->element_begin(),
84                                       EI = EB,
85                                       EE = STy->element_end();
86         EI != EE; ++EI) {
87       if (Indices && *Indices == unsigned(EI - EB))
88         return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
89       CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
90     }
91     return CurIndex;
92   }
93   // Given an array type, recursively traverse the elements.
94   else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
95     const Type *EltTy = ATy->getElementType();
96     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
97       if (Indices && *Indices == i)
98         return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
99       CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
100     }
101     return CurIndex;
102   }
103   // We haven't found the type we're looking for, so keep searching.
104   return CurIndex + 1;
105 }
106
107 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
108 /// MVTs that represent all the individual underlying
109 /// non-aggregate types that comprise it.
110 ///
111 /// If Offsets is non-null, it points to a vector to be filled in
112 /// with the in-memory offsets of each of the individual values.
113 ///
114 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
115                             SmallVectorImpl<MVT> &ValueVTs,
116                             SmallVectorImpl<uint64_t> *Offsets = 0,
117                             uint64_t StartingOffset = 0) {
118   // Given a struct type, recursively traverse the elements.
119   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
120     const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
121     for (StructType::element_iterator EB = STy->element_begin(),
122                                       EI = EB,
123                                       EE = STy->element_end();
124          EI != EE; ++EI)
125       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
126                       StartingOffset + SL->getElementOffset(EI - EB));
127     return;
128   }
129   // Given an array type, recursively traverse the elements.
130   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
131     const Type *EltTy = ATy->getElementType();
132     uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
133     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
134       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
135                       StartingOffset + i * EltSize);
136     return;
137   }
138   // Base case: we can get an MVT for this LLVM IR type.
139   ValueVTs.push_back(TLI.getValueType(Ty));
140   if (Offsets)
141     Offsets->push_back(StartingOffset);
142 }
143
144 namespace llvm {
145   /// RegsForValue - This struct represents the registers (physical or virtual)
146   /// that a particular set of values is assigned, and the type information about
147   /// the value. The most common situation is to represent one value at a time,
148   /// but struct or array values are handled element-wise as multiple values.
149   /// The splitting of aggregates is performed recursively, so that we never
150   /// have aggregate-typed registers. The values at this point do not necessarily
151   /// have legal types, so each value may require one or more registers of some
152   /// legal type.
153   ///
154   struct VISIBILITY_HIDDEN RegsForValue {
155     /// TLI - The TargetLowering object.
156     ///
157     const TargetLowering *TLI;
158
159     /// ValueVTs - The value types of the values, which may not be legal, and
160     /// may need be promoted or synthesized from one or more registers.
161     ///
162     SmallVector<MVT, 4> ValueVTs;
163
164     /// RegVTs - The value types of the registers. This is the same size as
165     /// ValueVTs and it records, for each value, what the type of the assigned
166     /// register or registers are. (Individual values are never synthesized
167     /// from more than one type of register.)
168     ///
169     /// With virtual registers, the contents of RegVTs is redundant with TLI's
170     /// getRegisterType member function, however when with physical registers
171     /// it is necessary to have a separate record of the types.
172     ///
173     SmallVector<MVT, 4> RegVTs;
174
175     /// Regs - This list holds the registers assigned to the values.
176     /// Each legal or promoted value requires one register, and each
177     /// expanded value requires multiple registers.
178     ///
179     SmallVector<unsigned, 4> Regs;
180
181     RegsForValue() : TLI(0) {}
182
183     RegsForValue(const TargetLowering &tli,
184                  const SmallVector<unsigned, 4> &regs,
185                  MVT regvt, MVT valuevt)
186       : TLI(&tli),  ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
187     RegsForValue(const TargetLowering &tli,
188                  const SmallVector<unsigned, 4> &regs,
189                  const SmallVector<MVT, 4> &regvts,
190                  const SmallVector<MVT, 4> &valuevts)
191       : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
192     RegsForValue(const TargetLowering &tli,
193                  unsigned Reg, const Type *Ty) : TLI(&tli) {
194       ComputeValueVTs(tli, Ty, ValueVTs);
195
196       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
197         MVT ValueVT = ValueVTs[Value];
198         unsigned NumRegs = TLI->getNumRegisters(ValueVT);
199         MVT RegisterVT = TLI->getRegisterType(ValueVT);
200         for (unsigned i = 0; i != NumRegs; ++i)
201           Regs.push_back(Reg + i);
202         RegVTs.push_back(RegisterVT);
203         Reg += NumRegs;
204       }
205     }
206
207     /// append - Add the specified values to this one.
208     void append(const RegsForValue &RHS) {
209       TLI = RHS.TLI;
210       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
211       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
212       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
213     }
214
215
216     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
217     /// this value and returns the result as a ValueVTs value.  This uses
218     /// Chain/Flag as the input and updates them for the output Chain/Flag.
219     /// If the Flag pointer is NULL, no flag is used.
220     SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
221                               SDValue &Chain, SDValue *Flag) const;
222
223     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
224     /// specified value into the registers specified by this object.  This uses
225     /// Chain/Flag as the input and updates them for the output Chain/Flag.
226     /// If the Flag pointer is NULL, no flag is used.
227     void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
228                        SDValue &Chain, SDValue *Flag) const;
229
230     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
231     /// operand list.  This adds the code marker, matching input operand index
232     /// (if applicable), and includes the number of values added into it.
233     void AddInlineAsmOperands(unsigned Code,
234                               bool HasMatching, unsigned MatchingIdx,
235                               SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
236   };
237 }
238
239 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
240 /// PHI nodes or outside of the basic block that defines it, or used by a
241 /// switch or atomic instruction, which may expand to multiple basic blocks.
242 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
243   if (isa<PHINode>(I)) return true;
244   BasicBlock *BB = I->getParent();
245   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
246     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
247         // FIXME: Remove switchinst special case.
248         isa<SwitchInst>(*UI))
249       return true;
250   return false;
251 }
252
253 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
254 /// entry block, return true.  This includes arguments used by switches, since
255 /// the switch may expand into multiple basic blocks.
256 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
257   // With FastISel active, we may be splitting blocks, so force creation
258   // of virtual registers for all non-dead arguments.
259   // Don't force virtual registers for byval arguments though, because
260   // fast-isel can't handle those in all cases.
261   if (EnableFastISel && !A->hasByValAttr())
262     return A->use_empty();
263
264   BasicBlock *Entry = A->getParent()->begin();
265   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
266     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
267       return false;  // Use not in entry block.
268   return true;
269 }
270
271 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
272   : TLI(tli) {
273 }
274
275 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
276                                SelectionDAG &DAG,
277                                bool EnableFastISel) {
278   Fn = &fn;
279   MF = &mf;
280   RegInfo = &MF->getRegInfo();
281
282   // Create a vreg for each argument register that is not dead and is used
283   // outside of the entry block for the function.
284   for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
285        AI != E; ++AI)
286     if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
287       InitializeRegForValue(AI);
288
289   // Initialize the mapping of values to registers.  This is only set up for
290   // instruction values that are used outside of the block that defines
291   // them.
292   Function::iterator BB = Fn->begin(), EB = Fn->end();
293   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
294     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
295       if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
296         const Type *Ty = AI->getAllocatedType();
297         uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
298         unsigned Align =
299           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
300                    AI->getAlignment());
301
302         TySize *= CUI->getZExtValue();   // Get total allocated size.
303         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
304         StaticAllocaMap[AI] =
305           MF->getFrameInfo()->CreateStackObject(TySize, Align);
306       }
307
308   for (; BB != EB; ++BB)
309     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
310       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
311         if (!isa<AllocaInst>(I) ||
312             !StaticAllocaMap.count(cast<AllocaInst>(I)))
313           InitializeRegForValue(I);
314
315   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
316   // also creates the initial PHI MachineInstrs, though none of the input
317   // operands are populated.
318   for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
319     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
320     MBBMap[BB] = MBB;
321     MF->push_back(MBB);
322
323     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
324     // appropriate.
325     PHINode *PN;
326     DebugLoc DL;
327     for (BasicBlock::iterator
328            I = BB->begin(), E = BB->end(); I != E; ++I) {
329       if (CallInst *CI = dyn_cast<CallInst>(I)) {
330         if (Function *F = CI->getCalledFunction()) {
331           switch (F->getIntrinsicID()) {
332           default: break;
333           case Intrinsic::dbg_stoppoint: {
334             DwarfWriter *DW = DAG.getDwarfWriter();
335             DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
336
337             if (DW && DW->ValidDebugInfo(SPI->getContext())) {
338               DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
339               std::string Dir, FN;
340               unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
341                                                          CU.getFilename(FN));
342               unsigned idx = MF->getOrCreateDebugLocID(SrcFile,
343                                                        SPI->getLine(),
344                                                        SPI->getColumn());
345               DL = DebugLoc::get(idx);
346             }
347
348             break;
349           }
350           case Intrinsic::dbg_func_start: {
351             DwarfWriter *DW = DAG.getDwarfWriter();
352             if (DW) {
353               DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
354               Value *SP = FSI->getSubprogram();
355
356               if (DW->ValidDebugInfo(SP)) {
357                 DISubprogram Subprogram(cast<GlobalVariable>(SP));
358                 DICompileUnit CU(Subprogram.getCompileUnit());
359                 std::string Dir, FN;
360                 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
361                                                            CU.getFilename(FN));
362                 unsigned Line = Subprogram.getLineNumber();
363                 DL = DebugLoc::get(MF->getOrCreateDebugLocID(SrcFile, Line, 0));
364               }
365             }
366
367             break;
368           }
369           }
370         }
371       }
372
373       PN = dyn_cast<PHINode>(I);
374       if (!PN || PN->use_empty()) continue;
375
376       unsigned PHIReg = ValueMap[PN];
377       assert(PHIReg && "PHI node does not have an assigned virtual register!");
378
379       SmallVector<MVT, 4> ValueVTs;
380       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
381       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
382         MVT VT = ValueVTs[vti];
383         unsigned NumRegisters = TLI.getNumRegisters(VT);
384         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
385         for (unsigned i = 0; i != NumRegisters; ++i)
386           BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
387         PHIReg += NumRegisters;
388       }
389     }
390   }
391 }
392
393 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
394   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
395 }
396
397 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
398 /// the correctly promoted or expanded types.  Assign these registers
399 /// consecutive vreg numbers and return the first assigned number.
400 ///
401 /// In the case that the given value has struct or array type, this function
402 /// will assign registers for each member or element.
403 ///
404 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
405   SmallVector<MVT, 4> ValueVTs;
406   ComputeValueVTs(TLI, V->getType(), ValueVTs);
407
408   unsigned FirstReg = 0;
409   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
410     MVT ValueVT = ValueVTs[Value];
411     MVT RegisterVT = TLI.getRegisterType(ValueVT);
412
413     unsigned NumRegs = TLI.getNumRegisters(ValueVT);
414     for (unsigned i = 0; i != NumRegs; ++i) {
415       unsigned R = MakeReg(RegisterVT);
416       if (!FirstReg) FirstReg = R;
417     }
418   }
419   return FirstReg;
420 }
421
422 /// getCopyFromParts - Create a value that contains the specified legal parts
423 /// combined into the value they represent.  If the parts combine to a type
424 /// larger then ValueVT then AssertOp can be used to specify whether the extra
425 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
426 /// (ISD::AssertSext).
427 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
428                                 const SDValue *Parts,
429                                 unsigned NumParts, MVT PartVT, MVT ValueVT,
430                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
431   assert(NumParts > 0 && "No parts to assemble!");
432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
433   SDValue Val = Parts[0];
434
435   if (NumParts > 1) {
436     // Assemble the value from multiple parts.
437     if (!ValueVT.isVector()) {
438       unsigned PartBits = PartVT.getSizeInBits();
439       unsigned ValueBits = ValueVT.getSizeInBits();
440
441       // Assemble the power of 2 part.
442       unsigned RoundParts = NumParts & (NumParts - 1) ?
443         1 << Log2_32(NumParts) : NumParts;
444       unsigned RoundBits = PartBits * RoundParts;
445       MVT RoundVT = RoundBits == ValueBits ?
446         ValueVT : MVT::getIntegerVT(RoundBits);
447       SDValue Lo, Hi;
448
449       MVT HalfVT = ValueVT.isInteger() ?
450         MVT::getIntegerVT(RoundBits/2) :
451         MVT::getFloatingPointVT(RoundBits/2);
452
453       if (RoundParts > 2) {
454         Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
455         Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
456                               PartVT, HalfVT);
457       } else {
458         Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
459         Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
460       }
461       if (TLI.isBigEndian())
462         std::swap(Lo, Hi);
463       Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
464
465       if (RoundParts < NumParts) {
466         // Assemble the trailing non-power-of-2 part.
467         unsigned OddParts = NumParts - RoundParts;
468         MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
469         Hi = getCopyFromParts(DAG, dl,
470                               Parts+RoundParts, OddParts, PartVT, OddVT);
471
472         // Combine the round and odd parts.
473         Lo = Val;
474         if (TLI.isBigEndian())
475           std::swap(Lo, Hi);
476         MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
477         Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
478         Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
479                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
480                                          TLI.getPointerTy()));
481         Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
482         Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
483       }
484     } else {
485       // Handle a multi-element vector.
486       MVT IntermediateVT, RegisterVT;
487       unsigned NumIntermediates;
488       unsigned NumRegs =
489         TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
490                                    RegisterVT);
491       assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
492       NumParts = NumRegs; // Silence a compiler warning.
493       assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
494       assert(RegisterVT == Parts[0].getValueType() &&
495              "Part type doesn't match part!");
496
497       // Assemble the parts into intermediate operands.
498       SmallVector<SDValue, 8> Ops(NumIntermediates);
499       if (NumIntermediates == NumParts) {
500         // If the register was not expanded, truncate or copy the value,
501         // as appropriate.
502         for (unsigned i = 0; i != NumParts; ++i)
503           Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
504                                     PartVT, IntermediateVT);
505       } else if (NumParts > 0) {
506         // If the intermediate type was expanded, build the intermediate operands
507         // from the parts.
508         assert(NumParts % NumIntermediates == 0 &&
509                "Must expand into a divisible number of parts!");
510         unsigned Factor = NumParts / NumIntermediates;
511         for (unsigned i = 0; i != NumIntermediates; ++i)
512           Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
513                                     PartVT, IntermediateVT);
514       }
515
516       // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
517       // operands.
518       Val = DAG.getNode(IntermediateVT.isVector() ?
519                         ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
520                         ValueVT, &Ops[0], NumIntermediates);
521     }
522   }
523
524   // There is now one part, held in Val.  Correct it to match ValueVT.
525   PartVT = Val.getValueType();
526
527   if (PartVT == ValueVT)
528     return Val;
529
530   if (PartVT.isVector()) {
531     assert(ValueVT.isVector() && "Unknown vector conversion!");
532     return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
533   }
534
535   if (ValueVT.isVector()) {
536     assert(ValueVT.getVectorElementType() == PartVT &&
537            ValueVT.getVectorNumElements() == 1 &&
538            "Only trivial scalar-to-vector conversions should get here!");
539     return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
540   }
541
542   if (PartVT.isInteger() &&
543       ValueVT.isInteger()) {
544     if (ValueVT.bitsLT(PartVT)) {
545       // For a truncate, see if we have any information to
546       // indicate whether the truncated bits will always be
547       // zero or sign-extension.
548       if (AssertOp != ISD::DELETED_NODE)
549         Val = DAG.getNode(AssertOp, dl, PartVT, Val,
550                           DAG.getValueType(ValueVT));
551       return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
552     } else {
553       return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
554     }
555   }
556
557   if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
558     if (ValueVT.bitsLT(Val.getValueType()))
559       // FP_ROUND's are always exact here.
560       return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
561                          DAG.getIntPtrConstant(1));
562     return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
563   }
564
565   if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
566     return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
567
568   assert(0 && "Unknown mismatch!");
569   return SDValue();
570 }
571
572 /// getCopyToParts - Create a series of nodes that contain the specified value
573 /// split into legal parts.  If the parts contain more bits than Val, then, for
574 /// integers, ExtendKind can be used to specify how to generate the extra bits.
575 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
576                            SDValue *Parts, unsigned NumParts, MVT PartVT,
577                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
578   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
579   MVT PtrVT = TLI.getPointerTy();
580   MVT ValueVT = Val.getValueType();
581   unsigned PartBits = PartVT.getSizeInBits();
582   unsigned OrigNumParts = NumParts;
583   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
584
585   if (!NumParts)
586     return;
587
588   if (!ValueVT.isVector()) {
589     if (PartVT == ValueVT) {
590       assert(NumParts == 1 && "No-op copy with multiple parts!");
591       Parts[0] = Val;
592       return;
593     }
594
595     if (NumParts * PartBits > ValueVT.getSizeInBits()) {
596       // If the parts cover more bits than the value has, promote the value.
597       if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
598         assert(NumParts == 1 && "Do not know what to promote to!");
599         Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
600       } else if (PartVT.isInteger() && ValueVT.isInteger()) {
601         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
602         Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
603       } else {
604         assert(0 && "Unknown mismatch!");
605       }
606     } else if (PartBits == ValueVT.getSizeInBits()) {
607       // Different types of the same size.
608       assert(NumParts == 1 && PartVT != ValueVT);
609       Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
610     } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
611       // If the parts cover less bits than value has, truncate the value.
612       if (PartVT.isInteger() && ValueVT.isInteger()) {
613         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
614         Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
615       } else {
616         assert(0 && "Unknown mismatch!");
617       }
618     }
619
620     // The value may have changed - recompute ValueVT.
621     ValueVT = Val.getValueType();
622     assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
623            "Failed to tile the value with PartVT!");
624
625     if (NumParts == 1) {
626       assert(PartVT == ValueVT && "Type conversion failed!");
627       Parts[0] = Val;
628       return;
629     }
630
631     // Expand the value into multiple parts.
632     if (NumParts & (NumParts - 1)) {
633       // The number of parts is not a power of 2.  Split off and copy the tail.
634       assert(PartVT.isInteger() && ValueVT.isInteger() &&
635              "Do not know what to expand to!");
636       unsigned RoundParts = 1 << Log2_32(NumParts);
637       unsigned RoundBits = RoundParts * PartBits;
638       unsigned OddParts = NumParts - RoundParts;
639       SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
640                                    DAG.getConstant(RoundBits,
641                                                    TLI.getPointerTy()));
642       getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
643       if (TLI.isBigEndian())
644         // The odd parts were reversed by getCopyToParts - unreverse them.
645         std::reverse(Parts + RoundParts, Parts + NumParts);
646       NumParts = RoundParts;
647       ValueVT = MVT::getIntegerVT(NumParts * PartBits);
648       Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
649     }
650
651     // The number of parts is a power of 2.  Repeatedly bisect the value using
652     // EXTRACT_ELEMENT.
653     Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
654                            MVT::getIntegerVT(ValueVT.getSizeInBits()),
655                            Val);
656     for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
657       for (unsigned i = 0; i < NumParts; i += StepSize) {
658         unsigned ThisBits = StepSize * PartBits / 2;
659         MVT ThisVT = MVT::getIntegerVT (ThisBits);
660         SDValue &Part0 = Parts[i];
661         SDValue &Part1 = Parts[i+StepSize/2];
662
663         Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
664                             ThisVT, Part0,
665                             DAG.getConstant(1, PtrVT));
666         Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
667                             ThisVT, Part0,
668                             DAG.getConstant(0, PtrVT));
669
670         if (ThisBits == PartBits && ThisVT != PartVT) {
671           Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
672                                                 PartVT, Part0);
673           Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
674                                                 PartVT, Part1);
675         }
676       }
677     }
678
679     if (TLI.isBigEndian())
680       std::reverse(Parts, Parts + OrigNumParts);
681
682     return;
683   }
684
685   // Vector ValueVT.
686   if (NumParts == 1) {
687     if (PartVT != ValueVT) {
688       if (PartVT.isVector()) {
689         Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
690       } else {
691         assert(ValueVT.getVectorElementType() == PartVT &&
692                ValueVT.getVectorNumElements() == 1 &&
693                "Only trivial vector-to-scalar conversions should get here!");
694         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
695                           PartVT, Val,
696                           DAG.getConstant(0, PtrVT));
697       }
698     }
699
700     Parts[0] = Val;
701     return;
702   }
703
704   // Handle a multi-element vector.
705   MVT IntermediateVT, RegisterVT;
706   unsigned NumIntermediates;
707   unsigned NumRegs = TLI
708       .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
709                               RegisterVT);
710   unsigned NumElements = ValueVT.getVectorNumElements();
711
712   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
713   NumParts = NumRegs; // Silence a compiler warning.
714   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
715
716   // Split the vector into intermediate operands.
717   SmallVector<SDValue, 8> Ops(NumIntermediates);
718   for (unsigned i = 0; i != NumIntermediates; ++i)
719     if (IntermediateVT.isVector())
720       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
721                            IntermediateVT, Val,
722                            DAG.getConstant(i * (NumElements / NumIntermediates),
723                                            PtrVT));
724     else
725       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
726                            IntermediateVT, Val,
727                            DAG.getConstant(i, PtrVT));
728
729   // Split the intermediate operands into legal parts.
730   if (NumParts == NumIntermediates) {
731     // If the register was not expanded, promote or copy the value,
732     // as appropriate.
733     for (unsigned i = 0; i != NumParts; ++i)
734       getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
735   } else if (NumParts > 0) {
736     // If the intermediate type was expanded, split each the value into
737     // legal parts.
738     assert(NumParts % NumIntermediates == 0 &&
739            "Must expand into a divisible number of parts!");
740     unsigned Factor = NumParts / NumIntermediates;
741     for (unsigned i = 0; i != NumIntermediates; ++i)
742       getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
743   }
744 }
745
746
747 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
748   AA = &aa;
749   GFI = gfi;
750   TD = DAG.getTarget().getTargetData();
751 }
752
753 /// clear - Clear out the curret SelectionDAG and the associated
754 /// state and prepare this SelectionDAGLowering object to be used
755 /// for a new block. This doesn't clear out information about
756 /// additional blocks that are needed to complete switch lowering
757 /// or PHI node updating; that information is cleared out as it is
758 /// consumed.
759 void SelectionDAGLowering::clear() {
760   NodeMap.clear();
761   PendingLoads.clear();
762   PendingExports.clear();
763   DAG.clear();
764   CurDebugLoc = DebugLoc::getUnknownLoc();
765 }
766
767 /// getRoot - Return the current virtual root of the Selection DAG,
768 /// flushing any PendingLoad items. This must be done before emitting
769 /// a store or any other node that may need to be ordered after any
770 /// prior load instructions.
771 ///
772 SDValue SelectionDAGLowering::getRoot() {
773   if (PendingLoads.empty())
774     return DAG.getRoot();
775
776   if (PendingLoads.size() == 1) {
777     SDValue Root = PendingLoads[0];
778     DAG.setRoot(Root);
779     PendingLoads.clear();
780     return Root;
781   }
782
783   // Otherwise, we have to make a token factor node.
784   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
785                                &PendingLoads[0], PendingLoads.size());
786   PendingLoads.clear();
787   DAG.setRoot(Root);
788   return Root;
789 }
790
791 /// getControlRoot - Similar to getRoot, but instead of flushing all the
792 /// PendingLoad items, flush all the PendingExports items. It is necessary
793 /// to do this before emitting a terminator instruction.
794 ///
795 SDValue SelectionDAGLowering::getControlRoot() {
796   SDValue Root = DAG.getRoot();
797
798   if (PendingExports.empty())
799     return Root;
800
801   // Turn all of the CopyToReg chains into one factored node.
802   if (Root.getOpcode() != ISD::EntryToken) {
803     unsigned i = 0, e = PendingExports.size();
804     for (; i != e; ++i) {
805       assert(PendingExports[i].getNode()->getNumOperands() > 1);
806       if (PendingExports[i].getNode()->getOperand(0) == Root)
807         break;  // Don't add the root if we already indirectly depend on it.
808     }
809
810     if (i == e)
811       PendingExports.push_back(Root);
812   }
813
814   Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
815                      &PendingExports[0],
816                      PendingExports.size());
817   PendingExports.clear();
818   DAG.setRoot(Root);
819   return Root;
820 }
821
822 void SelectionDAGLowering::visit(Instruction &I) {
823   visit(I.getOpcode(), I);
824 }
825
826 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
827   // Note: this doesn't use InstVisitor, because it has to work with
828   // ConstantExpr's in addition to instructions.
829   switch (Opcode) {
830   default: assert(0 && "Unknown instruction type encountered!");
831            abort();
832     // Build the switch statement using the Instruction.def file.
833 #define HANDLE_INST(NUM, OPCODE, CLASS) \
834   case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
835 #include "llvm/Instruction.def"
836   }
837 }
838
839 void SelectionDAGLowering::visitAdd(User &I) {
840   if (I.getType()->isFPOrFPVector())
841     visitBinary(I, ISD::FADD);
842   else
843     visitBinary(I, ISD::ADD);
844 }
845
846 void SelectionDAGLowering::visitMul(User &I) {
847   if (I.getType()->isFPOrFPVector())
848     visitBinary(I, ISD::FMUL);
849   else
850     visitBinary(I, ISD::MUL);
851 }
852
853 SDValue SelectionDAGLowering::getValue(const Value *V) {
854   SDValue &N = NodeMap[V];
855   if (N.getNode()) return N;
856
857   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
858     MVT VT = TLI.getValueType(V->getType(), true);
859
860     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
861       return N = DAG.getConstant(*CI, VT);
862
863     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
864       return N = DAG.getGlobalAddress(GV, VT);
865
866     if (isa<ConstantPointerNull>(C))
867       return N = DAG.getConstant(0, TLI.getPointerTy());
868
869     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
870       return N = DAG.getConstantFP(*CFP, VT);
871
872     if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
873         !V->getType()->isAggregateType())
874       return N = DAG.getUNDEF(VT);
875
876     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
877       visit(CE->getOpcode(), *CE);
878       SDValue N1 = NodeMap[V];
879       assert(N1.getNode() && "visit didn't populate the ValueMap!");
880       return N1;
881     }
882
883     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
884       SmallVector<SDValue, 4> Constants;
885       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
886            OI != OE; ++OI) {
887         SDNode *Val = getValue(*OI).getNode();
888         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
889           Constants.push_back(SDValue(Val, i));
890       }
891       return DAG.getMergeValues(&Constants[0], Constants.size(),
892                                 getCurDebugLoc());
893     }
894
895     if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
896       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
897              "Unknown struct or array constant!");
898
899       SmallVector<MVT, 4> ValueVTs;
900       ComputeValueVTs(TLI, C->getType(), ValueVTs);
901       unsigned NumElts = ValueVTs.size();
902       if (NumElts == 0)
903         return SDValue(); // empty struct
904       SmallVector<SDValue, 4> Constants(NumElts);
905       for (unsigned i = 0; i != NumElts; ++i) {
906         MVT EltVT = ValueVTs[i];
907         if (isa<UndefValue>(C))
908           Constants[i] = DAG.getUNDEF(EltVT);
909         else if (EltVT.isFloatingPoint())
910           Constants[i] = DAG.getConstantFP(0, EltVT);
911         else
912           Constants[i] = DAG.getConstant(0, EltVT);
913       }
914       return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
915     }
916
917     const VectorType *VecTy = cast<VectorType>(V->getType());
918     unsigned NumElements = VecTy->getNumElements();
919
920     // Now that we know the number and type of the elements, get that number of
921     // elements into the Ops array based on what kind of constant it is.
922     SmallVector<SDValue, 16> Ops;
923     if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
924       for (unsigned i = 0; i != NumElements; ++i)
925         Ops.push_back(getValue(CP->getOperand(i)));
926     } else {
927       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
928              "Unknown vector constant!");
929       MVT EltVT = TLI.getValueType(VecTy->getElementType());
930
931       SDValue Op;
932       if (isa<UndefValue>(C))
933         Op = DAG.getUNDEF(EltVT);
934       else if (EltVT.isFloatingPoint())
935         Op = DAG.getConstantFP(0, EltVT);
936       else
937         Op = DAG.getConstant(0, EltVT);
938       Ops.assign(NumElements, Op);
939     }
940
941     // Create a BUILD_VECTOR node.
942     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
943                                     VT, &Ops[0], Ops.size());
944   }
945
946   // If this is a static alloca, generate it as the frameindex instead of
947   // computation.
948   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
949     DenseMap<const AllocaInst*, int>::iterator SI =
950       FuncInfo.StaticAllocaMap.find(AI);
951     if (SI != FuncInfo.StaticAllocaMap.end())
952       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
953   }
954
955   unsigned InReg = FuncInfo.ValueMap[V];
956   assert(InReg && "Value not in map!");
957
958   RegsForValue RFV(TLI, InReg, V->getType());
959   SDValue Chain = DAG.getEntryNode();
960   return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
961 }
962
963
964 void SelectionDAGLowering::visitRet(ReturnInst &I) {
965   if (I.getNumOperands() == 0) {
966     DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
967                             MVT::Other, getControlRoot()));
968     return;
969   }
970
971   SmallVector<SDValue, 8> NewValues;
972   NewValues.push_back(getControlRoot());
973   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
974     SmallVector<MVT, 4> ValueVTs;
975     ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
976     unsigned NumValues = ValueVTs.size();
977     if (NumValues == 0) continue;
978
979     SDValue RetOp = getValue(I.getOperand(i));
980     for (unsigned j = 0, f = NumValues; j != f; ++j) {
981       MVT VT = ValueVTs[j];
982
983       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
984
985       const Function *F = I.getParent()->getParent();
986       if (F->paramHasAttr(0, Attribute::SExt))
987         ExtendKind = ISD::SIGN_EXTEND;
988       else if (F->paramHasAttr(0, Attribute::ZExt))
989         ExtendKind = ISD::ZERO_EXTEND;
990
991       // FIXME: C calling convention requires the return type to be promoted to
992       // at least 32-bit. But this is not necessary for non-C calling
993       // conventions. The frontend should mark functions whose return values
994       // require promoting with signext or zeroext attributes.
995       if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
996         MVT MinVT = TLI.getRegisterType(MVT::i32);
997         if (VT.bitsLT(MinVT))
998           VT = MinVT;
999       }
1000
1001       unsigned NumParts = TLI.getNumRegisters(VT);
1002       MVT PartVT = TLI.getRegisterType(VT);
1003       SmallVector<SDValue, 4> Parts(NumParts);
1004       getCopyToParts(DAG, getCurDebugLoc(),
1005                      SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1006                      &Parts[0], NumParts, PartVT, ExtendKind);
1007
1008       // 'inreg' on function refers to return value
1009       ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1010       if (F->paramHasAttr(0, Attribute::InReg))
1011         Flags.setInReg();
1012       for (unsigned i = 0; i < NumParts; ++i) {
1013         NewValues.push_back(Parts[i]);
1014         NewValues.push_back(DAG.getArgFlags(Flags));
1015       }
1016     }
1017   }
1018   DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
1019                           &NewValues[0], NewValues.size()));
1020 }
1021
1022 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1023 /// the current basic block, add it to ValueMap now so that we'll get a
1024 /// CopyTo/FromReg.
1025 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1026   // No need to export constants.
1027   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1028
1029   // Already exported?
1030   if (FuncInfo.isExportedInst(V)) return;
1031
1032   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1033   CopyValueToVirtualRegister(V, Reg);
1034 }
1035
1036 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1037                                                     const BasicBlock *FromBB) {
1038   // The operands of the setcc have to be in this block.  We don't know
1039   // how to export them from some other block.
1040   if (Instruction *VI = dyn_cast<Instruction>(V)) {
1041     // Can export from current BB.
1042     if (VI->getParent() == FromBB)
1043       return true;
1044
1045     // Is already exported, noop.
1046     return FuncInfo.isExportedInst(V);
1047   }
1048
1049   // If this is an argument, we can export it if the BB is the entry block or
1050   // if it is already exported.
1051   if (isa<Argument>(V)) {
1052     if (FromBB == &FromBB->getParent()->getEntryBlock())
1053       return true;
1054
1055     // Otherwise, can only export this if it is already exported.
1056     return FuncInfo.isExportedInst(V);
1057   }
1058
1059   // Otherwise, constants can always be exported.
1060   return true;
1061 }
1062
1063 static bool InBlock(const Value *V, const BasicBlock *BB) {
1064   if (const Instruction *I = dyn_cast<Instruction>(V))
1065     return I->getParent() == BB;
1066   return true;
1067 }
1068
1069 /// getFCmpCondCode - Return the ISD condition code corresponding to
1070 /// the given LLVM IR floating-point condition code.  This includes
1071 /// consideration of global floating-point math flags.
1072 ///
1073 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1074   ISD::CondCode FPC, FOC;
1075   switch (Pred) {
1076   case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1077   case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1078   case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1079   case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1080   case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1081   case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1082   case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1083   case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
1084   case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
1085   case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1086   case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1087   case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1088   case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1089   case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1090   case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1091   case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
1092   default:
1093     assert(0 && "Invalid FCmp predicate opcode!");
1094     FOC = FPC = ISD::SETFALSE;
1095     break;
1096   }
1097   if (FiniteOnlyFPMath())
1098     return FOC;
1099   else
1100     return FPC;
1101 }
1102
1103 /// getICmpCondCode - Return the ISD condition code corresponding to
1104 /// the given LLVM IR integer condition code.
1105 ///
1106 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1107   switch (Pred) {
1108   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
1109   case ICmpInst::ICMP_NE:  return ISD::SETNE;
1110   case ICmpInst::ICMP_SLE: return ISD::SETLE;
1111   case ICmpInst::ICMP_ULE: return ISD::SETULE;
1112   case ICmpInst::ICMP_SGE: return ISD::SETGE;
1113   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1114   case ICmpInst::ICMP_SLT: return ISD::SETLT;
1115   case ICmpInst::ICMP_ULT: return ISD::SETULT;
1116   case ICmpInst::ICMP_SGT: return ISD::SETGT;
1117   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1118   default:
1119     assert(0 && "Invalid ICmp predicate opcode!");
1120     return ISD::SETNE;
1121   }
1122 }
1123
1124 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1125 /// This function emits a branch and is used at the leaves of an OR or an
1126 /// AND operator tree.
1127 ///
1128 void
1129 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1130                                                    MachineBasicBlock *TBB,
1131                                                    MachineBasicBlock *FBB,
1132                                                    MachineBasicBlock *CurBB) {
1133   const BasicBlock *BB = CurBB->getBasicBlock();
1134
1135   // If the leaf of the tree is a comparison, merge the condition into
1136   // the caseblock.
1137   if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1138     // The operands of the cmp have to be in this block.  We don't know
1139     // how to export them from some other block.  If this is the first block
1140     // of the sequence, no exporting is needed.
1141     if (CurBB == CurMBB ||
1142         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1143          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1144       ISD::CondCode Condition;
1145       if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1146         Condition = getICmpCondCode(IC->getPredicate());
1147       } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1148         Condition = getFCmpCondCode(FC->getPredicate());
1149       } else {
1150         Condition = ISD::SETEQ; // silence warning.
1151         assert(0 && "Unknown compare instruction");
1152       }
1153
1154       CaseBlock CB(Condition, BOp->getOperand(0),
1155                    BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1156       SwitchCases.push_back(CB);
1157       return;
1158     }
1159   }
1160
1161   // Create a CaseBlock record representing this branch.
1162   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1163                NULL, TBB, FBB, CurBB);
1164   SwitchCases.push_back(CB);
1165 }
1166
1167 /// FindMergedConditions - If Cond is an expression like
1168 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1169                                                 MachineBasicBlock *TBB,
1170                                                 MachineBasicBlock *FBB,
1171                                                 MachineBasicBlock *CurBB,
1172                                                 unsigned Opc) {
1173   // If this node is not part of the or/and tree, emit it as a branch.
1174   Instruction *BOp = dyn_cast<Instruction>(Cond);
1175   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1176       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1177       BOp->getParent() != CurBB->getBasicBlock() ||
1178       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1179       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1180     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1181     return;
1182   }
1183
1184   //  Create TmpBB after CurBB.
1185   MachineFunction::iterator BBI = CurBB;
1186   MachineFunction &MF = DAG.getMachineFunction();
1187   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1188   CurBB->getParent()->insert(++BBI, TmpBB);
1189
1190   if (Opc == Instruction::Or) {
1191     // Codegen X | Y as:
1192     //   jmp_if_X TBB
1193     //   jmp TmpBB
1194     // TmpBB:
1195     //   jmp_if_Y TBB
1196     //   jmp FBB
1197     //
1198
1199     // Emit the LHS condition.
1200     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1201
1202     // Emit the RHS condition into TmpBB.
1203     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1204   } else {
1205     assert(Opc == Instruction::And && "Unknown merge op!");
1206     // Codegen X & Y as:
1207     //   jmp_if_X TmpBB
1208     //   jmp FBB
1209     // TmpBB:
1210     //   jmp_if_Y TBB
1211     //   jmp FBB
1212     //
1213     //  This requires creation of TmpBB after CurBB.
1214
1215     // Emit the LHS condition.
1216     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1217
1218     // Emit the RHS condition into TmpBB.
1219     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1220   }
1221 }
1222
1223 /// If the set of cases should be emitted as a series of branches, return true.
1224 /// If we should emit this as a bunch of and/or'd together conditions, return
1225 /// false.
1226 bool
1227 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1228   if (Cases.size() != 2) return true;
1229
1230   // If this is two comparisons of the same values or'd or and'd together, they
1231   // will get folded into a single comparison, so don't emit two blocks.
1232   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1233        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1234       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1235        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1236     return false;
1237   }
1238
1239   return true;
1240 }
1241
1242 void SelectionDAGLowering::visitBr(BranchInst &I) {
1243   // Update machine-CFG edges.
1244   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1245
1246   // Figure out which block is immediately after the current one.
1247   MachineBasicBlock *NextBlock = 0;
1248   MachineFunction::iterator BBI = CurMBB;
1249   if (++BBI != CurMBB->getParent()->end())
1250     NextBlock = BBI;
1251
1252   if (I.isUnconditional()) {
1253     // Update machine-CFG edges.
1254     CurMBB->addSuccessor(Succ0MBB);
1255
1256     // If this is not a fall-through branch, emit the branch.
1257     if (Succ0MBB != NextBlock)
1258       DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1259                               MVT::Other, getControlRoot(),
1260                               DAG.getBasicBlock(Succ0MBB)));
1261     return;
1262   }
1263
1264   // If this condition is one of the special cases we handle, do special stuff
1265   // now.
1266   Value *CondVal = I.getCondition();
1267   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1268
1269   // If this is a series of conditions that are or'd or and'd together, emit
1270   // this as a sequence of branches instead of setcc's with and/or operations.
1271   // For example, instead of something like:
1272   //     cmp A, B
1273   //     C = seteq
1274   //     cmp D, E
1275   //     F = setle
1276   //     or C, F
1277   //     jnz foo
1278   // Emit:
1279   //     cmp A, B
1280   //     je foo
1281   //     cmp D, E
1282   //     jle foo
1283   //
1284   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1285     if (BOp->hasOneUse() &&
1286         (BOp->getOpcode() == Instruction::And ||
1287          BOp->getOpcode() == Instruction::Or)) {
1288       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1289       // If the compares in later blocks need to use values not currently
1290       // exported from this block, export them now.  This block should always
1291       // be the first entry.
1292       assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1293
1294       // Allow some cases to be rejected.
1295       if (ShouldEmitAsBranches(SwitchCases)) {
1296         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1297           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1298           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1299         }
1300
1301         // Emit the branch for this block.
1302         visitSwitchCase(SwitchCases[0]);
1303         SwitchCases.erase(SwitchCases.begin());
1304         return;
1305       }
1306
1307       // Okay, we decided not to do this, remove any inserted MBB's and clear
1308       // SwitchCases.
1309       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1310         CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1311
1312       SwitchCases.clear();
1313     }
1314   }
1315
1316   // Create a CaseBlock record representing this branch.
1317   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1318                NULL, Succ0MBB, Succ1MBB, CurMBB);
1319   // Use visitSwitchCase to actually insert the fast branch sequence for this
1320   // cond branch.
1321   visitSwitchCase(CB);
1322 }
1323
1324 /// visitSwitchCase - Emits the necessary code to represent a single node in
1325 /// the binary search tree resulting from lowering a switch instruction.
1326 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1327   SDValue Cond;
1328   SDValue CondLHS = getValue(CB.CmpLHS);
1329   DebugLoc dl = getCurDebugLoc();
1330
1331   // Build the setcc now.
1332   if (CB.CmpMHS == NULL) {
1333     // Fold "(X == true)" to X and "(X == false)" to !X to
1334     // handle common cases produced by branch lowering.
1335     if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1336       Cond = CondLHS;
1337     else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1338       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1339       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1340     } else
1341       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1342   } else {
1343     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1344
1345     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1346     const APInt& High  = cast<ConstantInt>(CB.CmpRHS)->getValue();
1347
1348     SDValue CmpOp = getValue(CB.CmpMHS);
1349     MVT VT = CmpOp.getValueType();
1350
1351     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1352       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1353                           ISD::SETLE);
1354     } else {
1355       SDValue SUB = DAG.getNode(ISD::SUB, dl,
1356                                 VT, CmpOp, DAG.getConstant(Low, VT));
1357       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1358                           DAG.getConstant(High-Low, VT), ISD::SETULE);
1359     }
1360   }
1361
1362   // Update successor info
1363   CurMBB->addSuccessor(CB.TrueBB);
1364   CurMBB->addSuccessor(CB.FalseBB);
1365
1366   // Set NextBlock to be the MBB immediately after the current one, if any.
1367   // This is used to avoid emitting unnecessary branches to the next block.
1368   MachineBasicBlock *NextBlock = 0;
1369   MachineFunction::iterator BBI = CurMBB;
1370   if (++BBI != CurMBB->getParent()->end())
1371     NextBlock = BBI;
1372
1373   // If the lhs block is the next block, invert the condition so that we can
1374   // fall through to the lhs instead of the rhs block.
1375   if (CB.TrueBB == NextBlock) {
1376     std::swap(CB.TrueBB, CB.FalseBB);
1377     SDValue True = DAG.getConstant(1, Cond.getValueType());
1378     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1379   }
1380   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1381                                MVT::Other, getControlRoot(), Cond,
1382                                DAG.getBasicBlock(CB.TrueBB));
1383
1384   // If the branch was constant folded, fix up the CFG.
1385   if (BrCond.getOpcode() == ISD::BR) {
1386     CurMBB->removeSuccessor(CB.FalseBB);
1387     DAG.setRoot(BrCond);
1388   } else {
1389     // Otherwise, go ahead and insert the false branch.
1390     if (BrCond == getControlRoot())
1391       CurMBB->removeSuccessor(CB.TrueBB);
1392
1393     if (CB.FalseBB == NextBlock)
1394       DAG.setRoot(BrCond);
1395     else
1396       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1397                               DAG.getBasicBlock(CB.FalseBB)));
1398   }
1399 }
1400
1401 /// visitJumpTable - Emit JumpTable node in the current MBB
1402 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1403   // Emit the code for the jump table
1404   assert(JT.Reg != -1U && "Should lower JT Header first!");
1405   MVT PTy = TLI.getPointerTy();
1406   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1407                                      JT.Reg, PTy);
1408   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1409   DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1410                           MVT::Other, Index.getValue(1),
1411                           Table, Index));
1412 }
1413
1414 /// visitJumpTableHeader - This function emits necessary code to produce index
1415 /// in the JumpTable from switch case.
1416 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1417                                                 JumpTableHeader &JTH) {
1418   // Subtract the lowest switch case value from the value being switched on and
1419   // conditional branch to default mbb if the result is greater than the
1420   // difference between smallest and largest cases.
1421   SDValue SwitchOp = getValue(JTH.SValue);
1422   MVT VT = SwitchOp.getValueType();
1423   SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1424                             DAG.getConstant(JTH.First, VT));
1425
1426   // The SDNode we just created, which holds the value being switched on minus
1427   // the the smallest case value, needs to be copied to a virtual register so it
1428   // can be used as an index into the jump table in a subsequent basic block.
1429   // This value may be smaller or larger than the target's pointer type, and
1430   // therefore require extension or truncating.
1431   if (VT.bitsGT(TLI.getPointerTy()))
1432     SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
1433                            TLI.getPointerTy(), SUB);
1434   else
1435     SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
1436                            TLI.getPointerTy(), SUB);
1437
1438   unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1439   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1440                                     JumpTableReg, SwitchOp);
1441   JT.Reg = JumpTableReg;
1442
1443   // Emit the range check for the jump table, and branch to the default block
1444   // for the switch statement if the value being switched on exceeds the largest
1445   // case in the switch.
1446   SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1447                              TLI.getSetCCResultType(SUB.getValueType()), SUB,
1448                              DAG.getConstant(JTH.Last-JTH.First,VT),
1449                              ISD::SETUGT);
1450
1451   // Set NextBlock to be the MBB immediately after the current one, if any.
1452   // This is used to avoid emitting unnecessary branches to the next block.
1453   MachineBasicBlock *NextBlock = 0;
1454   MachineFunction::iterator BBI = CurMBB;
1455   if (++BBI != CurMBB->getParent()->end())
1456     NextBlock = BBI;
1457
1458   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1459                                MVT::Other, CopyTo, CMP,
1460                                DAG.getBasicBlock(JT.Default));
1461
1462   if (JT.MBB == NextBlock)
1463     DAG.setRoot(BrCond);
1464   else
1465     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1466                             DAG.getBasicBlock(JT.MBB)));
1467 }
1468
1469 /// visitBitTestHeader - This function emits necessary code to produce value
1470 /// suitable for "bit tests"
1471 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1472   // Subtract the minimum value
1473   SDValue SwitchOp = getValue(B.SValue);
1474   MVT VT = SwitchOp.getValueType();
1475   SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1476                             DAG.getConstant(B.First, VT));
1477
1478   // Check range
1479   SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1480                                   TLI.getSetCCResultType(SUB.getValueType()),
1481                                   SUB, DAG.getConstant(B.Range, VT),
1482                                   ISD::SETUGT);
1483
1484   SDValue ShiftOp;
1485   if (VT.bitsGT(TLI.getPointerTy()))
1486     ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
1487                           TLI.getPointerTy(), SUB);
1488   else
1489     ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
1490                           TLI.getPointerTy(), SUB);
1491
1492   B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1493   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1494                                     B.Reg, ShiftOp);
1495
1496   // Set NextBlock to be the MBB immediately after the current one, if any.
1497   // This is used to avoid emitting unnecessary branches to the next block.
1498   MachineBasicBlock *NextBlock = 0;
1499   MachineFunction::iterator BBI = CurMBB;
1500   if (++BBI != CurMBB->getParent()->end())
1501     NextBlock = BBI;
1502
1503   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1504
1505   CurMBB->addSuccessor(B.Default);
1506   CurMBB->addSuccessor(MBB);
1507
1508   SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1509                                 MVT::Other, CopyTo, RangeCmp,
1510                                 DAG.getBasicBlock(B.Default));
1511
1512   if (MBB == NextBlock)
1513     DAG.setRoot(BrRange);
1514   else
1515     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1516                             DAG.getBasicBlock(MBB)));
1517 }
1518
1519 /// visitBitTestCase - this function produces one "bit test"
1520 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1521                                             unsigned Reg,
1522                                             BitTestCase &B) {
1523   // Make desired shift
1524   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1525                                        TLI.getPointerTy());
1526   SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1527                                   TLI.getPointerTy(),
1528                                   DAG.getConstant(1, TLI.getPointerTy()),
1529                                   ShiftOp);
1530
1531   // Emit bit tests and jumps
1532   SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1533                               TLI.getPointerTy(), SwitchVal,
1534                               DAG.getConstant(B.Mask, TLI.getPointerTy()));
1535   SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1536                                 TLI.getSetCCResultType(AndOp.getValueType()),
1537                                 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1538                                 ISD::SETNE);
1539
1540   CurMBB->addSuccessor(B.TargetBB);
1541   CurMBB->addSuccessor(NextMBB);
1542
1543   SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1544                               MVT::Other, getControlRoot(),
1545                               AndCmp, DAG.getBasicBlock(B.TargetBB));
1546
1547   // Set NextBlock to be the MBB immediately after the current one, if any.
1548   // This is used to avoid emitting unnecessary branches to the next block.
1549   MachineBasicBlock *NextBlock = 0;
1550   MachineFunction::iterator BBI = CurMBB;
1551   if (++BBI != CurMBB->getParent()->end())
1552     NextBlock = BBI;
1553
1554   if (NextMBB == NextBlock)
1555     DAG.setRoot(BrAnd);
1556   else
1557     DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1558                             DAG.getBasicBlock(NextMBB)));
1559 }
1560
1561 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1562   // Retrieve successors.
1563   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1564   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1565
1566   const Value *Callee(I.getCalledValue());
1567   if (isa<InlineAsm>(Callee))
1568     visitInlineAsm(&I);
1569   else
1570     LowerCallTo(&I, getValue(Callee), false, LandingPad);
1571
1572   // If the value of the invoke is used outside of its defining block, make it
1573   // available as a virtual register.
1574   if (!I.use_empty()) {
1575     DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1576     if (VMI != FuncInfo.ValueMap.end())
1577       CopyValueToVirtualRegister(&I, VMI->second);
1578   }
1579
1580   // Update successor info
1581   CurMBB->addSuccessor(Return);
1582   CurMBB->addSuccessor(LandingPad);
1583
1584   // Drop into normal successor.
1585   DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1586                           MVT::Other, getControlRoot(),
1587                           DAG.getBasicBlock(Return)));
1588 }
1589
1590 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1591 }
1592
1593 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1594 /// small case ranges).
1595 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1596                                                   CaseRecVector& WorkList,
1597                                                   Value* SV,
1598                                                   MachineBasicBlock* Default) {
1599   Case& BackCase  = *(CR.Range.second-1);
1600
1601   // Size is the number of Cases represented by this range.
1602   size_t Size = CR.Range.second - CR.Range.first;
1603   if (Size > 3)
1604     return false;
1605
1606   // Get the MachineFunction which holds the current MBB.  This is used when
1607   // inserting any additional MBBs necessary to represent the switch.
1608   MachineFunction *CurMF = CurMBB->getParent();
1609
1610   // Figure out which block is immediately after the current one.
1611   MachineBasicBlock *NextBlock = 0;
1612   MachineFunction::iterator BBI = CR.CaseBB;
1613
1614   if (++BBI != CurMBB->getParent()->end())
1615     NextBlock = BBI;
1616
1617   // TODO: If any two of the cases has the same destination, and if one value
1618   // is the same as the other, but has one bit unset that the other has set,
1619   // use bit manipulation to do two compares at once.  For example:
1620   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1621
1622   // Rearrange the case blocks so that the last one falls through if possible.
1623   if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1624     // The last case block won't fall through into 'NextBlock' if we emit the
1625     // branches in this order.  See if rearranging a case value would help.
1626     for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1627       if (I->BB == NextBlock) {
1628         std::swap(*I, BackCase);
1629         break;
1630       }
1631     }
1632   }
1633
1634   // Create a CaseBlock record representing a conditional branch to
1635   // the Case's target mbb if the value being switched on SV is equal
1636   // to C.
1637   MachineBasicBlock *CurBlock = CR.CaseBB;
1638   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1639     MachineBasicBlock *FallThrough;
1640     if (I != E-1) {
1641       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1642       CurMF->insert(BBI, FallThrough);
1643     } else {
1644       // If the last case doesn't match, go to the default block.
1645       FallThrough = Default;
1646     }
1647
1648     Value *RHS, *LHS, *MHS;
1649     ISD::CondCode CC;
1650     if (I->High == I->Low) {
1651       // This is just small small case range :) containing exactly 1 case
1652       CC = ISD::SETEQ;
1653       LHS = SV; RHS = I->High; MHS = NULL;
1654     } else {
1655       CC = ISD::SETLE;
1656       LHS = I->Low; MHS = SV; RHS = I->High;
1657     }
1658     CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1659
1660     // If emitting the first comparison, just call visitSwitchCase to emit the
1661     // code into the current block.  Otherwise, push the CaseBlock onto the
1662     // vector to be later processed by SDISel, and insert the node's MBB
1663     // before the next MBB.
1664     if (CurBlock == CurMBB)
1665       visitSwitchCase(CB);
1666     else
1667       SwitchCases.push_back(CB);
1668
1669     CurBlock = FallThrough;
1670   }
1671
1672   return true;
1673 }
1674
1675 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1676   return !DisableJumpTables &&
1677           (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1678            TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1679 }
1680
1681 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1682   APInt LastExt(Last), FirstExt(First);
1683   uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1684   LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1685   return (LastExt - FirstExt + 1ULL);
1686 }
1687
1688 /// handleJTSwitchCase - Emit jumptable for current switch case range
1689 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1690                                               CaseRecVector& WorkList,
1691                                               Value* SV,
1692                                               MachineBasicBlock* Default) {
1693   Case& FrontCase = *CR.Range.first;
1694   Case& BackCase  = *(CR.Range.second-1);
1695
1696   const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1697   const APInt& Last  = cast<ConstantInt>(BackCase.High)->getValue();
1698
1699   size_t TSize = 0;
1700   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1701        I!=E; ++I)
1702     TSize += I->size();
1703
1704   if (!areJTsAllowed(TLI) || TSize <= 3)
1705     return false;
1706
1707   APInt Range = ComputeRange(First, Last);
1708   double Density = (double)TSize / Range.roundToDouble();
1709   if (Density < 0.4)
1710     return false;
1711
1712   DEBUG(errs() << "Lowering jump table\n"
1713                << "First entry: " << First << ". Last entry: " << Last << '\n'
1714                << "Range: " << Range
1715                << "Size: " << TSize << ". Density: " << Density << "\n\n");
1716
1717   // Get the MachineFunction which holds the current MBB.  This is used when
1718   // inserting any additional MBBs necessary to represent the switch.
1719   MachineFunction *CurMF = CurMBB->getParent();
1720
1721   // Figure out which block is immediately after the current one.
1722   MachineBasicBlock *NextBlock = 0;
1723   MachineFunction::iterator BBI = CR.CaseBB;
1724
1725   if (++BBI != CurMBB->getParent()->end())
1726     NextBlock = BBI;
1727
1728   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1729
1730   // Create a new basic block to hold the code for loading the address
1731   // of the jump table, and jumping to it.  Update successor information;
1732   // we will either branch to the default case for the switch, or the jump
1733   // table.
1734   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1735   CurMF->insert(BBI, JumpTableBB);
1736   CR.CaseBB->addSuccessor(Default);
1737   CR.CaseBB->addSuccessor(JumpTableBB);
1738
1739   // Build a vector of destination BBs, corresponding to each target
1740   // of the jump table. If the value of the jump table slot corresponds to
1741   // a case statement, push the case's BB onto the vector, otherwise, push
1742   // the default BB.
1743   std::vector<MachineBasicBlock*> DestBBs;
1744   APInt TEI = First;
1745   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1746     const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1747     const APInt& High = cast<ConstantInt>(I->High)->getValue();
1748
1749     if (Low.sle(TEI) && TEI.sle(High)) {
1750       DestBBs.push_back(I->BB);
1751       if (TEI==High)
1752         ++I;
1753     } else {
1754       DestBBs.push_back(Default);
1755     }
1756   }
1757
1758   // Update successor info. Add one edge to each unique successor.
1759   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1760   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1761          E = DestBBs.end(); I != E; ++I) {
1762     if (!SuccsHandled[(*I)->getNumber()]) {
1763       SuccsHandled[(*I)->getNumber()] = true;
1764       JumpTableBB->addSuccessor(*I);
1765     }
1766   }
1767
1768   // Create a jump table index for this jump table, or return an existing
1769   // one.
1770   unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1771
1772   // Set the jump table information so that we can codegen it as a second
1773   // MachineBasicBlock
1774   JumpTable JT(-1U, JTI, JumpTableBB, Default);
1775   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1776   if (CR.CaseBB == CurMBB)
1777     visitJumpTableHeader(JT, JTH);
1778
1779   JTCases.push_back(JumpTableBlock(JTH, JT));
1780
1781   return true;
1782 }
1783
1784 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1785 /// 2 subtrees.
1786 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1787                                                    CaseRecVector& WorkList,
1788                                                    Value* SV,
1789                                                    MachineBasicBlock* Default) {
1790   // Get the MachineFunction which holds the current MBB.  This is used when
1791   // inserting any additional MBBs necessary to represent the switch.
1792   MachineFunction *CurMF = CurMBB->getParent();
1793
1794   // Figure out which block is immediately after the current one.
1795   MachineBasicBlock *NextBlock = 0;
1796   MachineFunction::iterator BBI = CR.CaseBB;
1797
1798   if (++BBI != CurMBB->getParent()->end())
1799     NextBlock = BBI;
1800
1801   Case& FrontCase = *CR.Range.first;
1802   Case& BackCase  = *(CR.Range.second-1);
1803   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1804
1805   // Size is the number of Cases represented by this range.
1806   unsigned Size = CR.Range.second - CR.Range.first;
1807
1808   const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1809   const APInt& Last  = cast<ConstantInt>(BackCase.High)->getValue();
1810   double FMetric = 0;
1811   CaseItr Pivot = CR.Range.first + Size/2;
1812
1813   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1814   // (heuristically) allow us to emit JumpTable's later.
1815   size_t TSize = 0;
1816   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1817        I!=E; ++I)
1818     TSize += I->size();
1819
1820   size_t LSize = FrontCase.size();
1821   size_t RSize = TSize-LSize;
1822   DEBUG(errs() << "Selecting best pivot: \n"
1823                << "First: " << First << ", Last: " << Last <<'\n'
1824                << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1825   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1826        J!=E; ++I, ++J) {
1827     const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1828     const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
1829     APInt Range = ComputeRange(LEnd, RBegin);
1830     assert((Range - 2ULL).isNonNegative() &&
1831            "Invalid case distance");
1832     double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1833     double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
1834     double Metric = Range.logBase2()*(LDensity+RDensity);
1835     // Should always split in some non-trivial place
1836     DEBUG(errs() <<"=>Step\n"
1837                  << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1838                  << "LDensity: " << LDensity
1839                  << ", RDensity: " << RDensity << '\n'
1840                  << "Metric: " << Metric << '\n');
1841     if (FMetric < Metric) {
1842       Pivot = J;
1843       FMetric = Metric;
1844       DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1845     }
1846
1847     LSize += J->size();
1848     RSize -= J->size();
1849   }
1850   if (areJTsAllowed(TLI)) {
1851     // If our case is dense we *really* should handle it earlier!
1852     assert((FMetric > 0) && "Should handle dense range earlier!");
1853   } else {
1854     Pivot = CR.Range.first + Size/2;
1855   }
1856
1857   CaseRange LHSR(CR.Range.first, Pivot);
1858   CaseRange RHSR(Pivot, CR.Range.second);
1859   Constant *C = Pivot->Low;
1860   MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1861
1862   // We know that we branch to the LHS if the Value being switched on is
1863   // less than the Pivot value, C.  We use this to optimize our binary
1864   // tree a bit, by recognizing that if SV is greater than or equal to the
1865   // LHS's Case Value, and that Case Value is exactly one less than the
1866   // Pivot's Value, then we can branch directly to the LHS's Target,
1867   // rather than creating a leaf node for it.
1868   if ((LHSR.second - LHSR.first) == 1 &&
1869       LHSR.first->High == CR.GE &&
1870       cast<ConstantInt>(C)->getValue() ==
1871       (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1872     TrueBB = LHSR.first->BB;
1873   } else {
1874     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1875     CurMF->insert(BBI, TrueBB);
1876     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1877   }
1878
1879   // Similar to the optimization above, if the Value being switched on is
1880   // known to be less than the Constant CR.LT, and the current Case Value
1881   // is CR.LT - 1, then we can branch directly to the target block for
1882   // the current Case Value, rather than emitting a RHS leaf node for it.
1883   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1884       cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1885       (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1886     FalseBB = RHSR.first->BB;
1887   } else {
1888     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1889     CurMF->insert(BBI, FalseBB);
1890     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1891   }
1892
1893   // Create a CaseBlock record representing a conditional branch to
1894   // the LHS node if the value being switched on SV is less than C.
1895   // Otherwise, branch to LHS.
1896   CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1897
1898   if (CR.CaseBB == CurMBB)
1899     visitSwitchCase(CB);
1900   else
1901     SwitchCases.push_back(CB);
1902
1903   return true;
1904 }
1905
1906 /// handleBitTestsSwitchCase - if current case range has few destination and
1907 /// range span less, than machine word bitwidth, encode case range into series
1908 /// of masks and emit bit tests with these masks.
1909 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1910                                                     CaseRecVector& WorkList,
1911                                                     Value* SV,
1912                                                     MachineBasicBlock* Default){
1913   unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1914
1915   Case& FrontCase = *CR.Range.first;
1916   Case& BackCase  = *(CR.Range.second-1);
1917
1918   // Get the MachineFunction which holds the current MBB.  This is used when
1919   // inserting any additional MBBs necessary to represent the switch.
1920   MachineFunction *CurMF = CurMBB->getParent();
1921
1922   size_t numCmps = 0;
1923   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1924        I!=E; ++I) {
1925     // Single case counts one, case range - two.
1926     numCmps += (I->Low == I->High ? 1 : 2);
1927   }
1928
1929   // Count unique destinations
1930   SmallSet<MachineBasicBlock*, 4> Dests;
1931   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1932     Dests.insert(I->BB);
1933     if (Dests.size() > 3)
1934       // Don't bother the code below, if there are too much unique destinations
1935       return false;
1936   }
1937   DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1938                << "Total number of comparisons: " << numCmps << '\n');
1939
1940   // Compute span of values.
1941   const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1942   const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1943   APInt cmpRange = maxValue - minValue;
1944
1945   DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1946                << "Low bound: " << minValue << '\n'
1947                << "High bound: " << maxValue << '\n');
1948
1949   if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1950       (!(Dests.size() == 1 && numCmps >= 3) &&
1951        !(Dests.size() == 2 && numCmps >= 5) &&
1952        !(Dests.size() >= 3 && numCmps >= 6)))
1953     return false;
1954
1955   DEBUG(errs() << "Emitting bit tests\n");
1956   APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1957
1958   // Optimize the case where all the case values fit in a
1959   // word without having to subtract minValue. In this case,
1960   // we can optimize away the subtraction.
1961   if (minValue.isNonNegative() &&
1962       maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1963     cmpRange = maxValue;
1964   } else {
1965     lowBound = minValue;
1966   }
1967
1968   CaseBitsVector CasesBits;
1969   unsigned i, count = 0;
1970
1971   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1972     MachineBasicBlock* Dest = I->BB;
1973     for (i = 0; i < count; ++i)
1974       if (Dest == CasesBits[i].BB)
1975         break;
1976
1977     if (i == count) {
1978       assert((count < 3) && "Too much destinations to test!");
1979       CasesBits.push_back(CaseBits(0, Dest, 0));
1980       count++;
1981     }
1982
1983     const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1984     const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1985
1986     uint64_t lo = (lowValue - lowBound).getZExtValue();
1987     uint64_t hi = (highValue - lowBound).getZExtValue();
1988
1989     for (uint64_t j = lo; j <= hi; j++) {
1990       CasesBits[i].Mask |=  1ULL << j;
1991       CasesBits[i].Bits++;
1992     }
1993
1994   }
1995   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1996
1997   BitTestInfo BTC;
1998
1999   // Figure out which block is immediately after the current one.
2000   MachineFunction::iterator BBI = CR.CaseBB;
2001   ++BBI;
2002
2003   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2004
2005   DEBUG(errs() << "Cases:\n");
2006   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2007     DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2008                  << ", Bits: " << CasesBits[i].Bits
2009                  << ", BB: " << CasesBits[i].BB << '\n');
2010
2011     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2012     CurMF->insert(BBI, CaseBB);
2013     BTC.push_back(BitTestCase(CasesBits[i].Mask,
2014                               CaseBB,
2015                               CasesBits[i].BB));
2016   }
2017
2018   BitTestBlock BTB(lowBound, cmpRange, SV,
2019                    -1U, (CR.CaseBB == CurMBB),
2020                    CR.CaseBB, Default, BTC);
2021
2022   if (CR.CaseBB == CurMBB)
2023     visitBitTestHeader(BTB);
2024
2025   BitTestCases.push_back(BTB);
2026
2027   return true;
2028 }
2029
2030
2031 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2032 size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
2033                                           const SwitchInst& SI) {
2034   size_t numCmps = 0;
2035
2036   // Start with "simple" cases
2037   for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2038     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2039     Cases.push_back(Case(SI.getSuccessorValue(i),
2040                          SI.getSuccessorValue(i),
2041                          SMBB));
2042   }
2043   std::sort(Cases.begin(), Cases.end(), CaseCmp());
2044
2045   // Merge case into clusters
2046   if (Cases.size() >= 2)
2047     // Must recompute end() each iteration because it may be
2048     // invalidated by erase if we hold on to it
2049     for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2050       const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2051       const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2052       MachineBasicBlock* nextBB = J->BB;
2053       MachineBasicBlock* currentBB = I->BB;
2054
2055       // If the two neighboring cases go to the same destination, merge them
2056       // into a single case.
2057       if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2058         I->High = J->High;
2059         J = Cases.erase(J);
2060       } else {
2061         I = J++;
2062       }
2063     }
2064
2065   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2066     if (I->Low != I->High)
2067       // A range counts double, since it requires two compares.
2068       ++numCmps;
2069   }
2070
2071   return numCmps;
2072 }
2073
2074 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2075   // Figure out which block is immediately after the current one.
2076   MachineBasicBlock *NextBlock = 0;
2077   MachineFunction::iterator BBI = CurMBB;
2078
2079   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2080
2081   // If there is only the default destination, branch to it if it is not the
2082   // next basic block.  Otherwise, just fall through.
2083   if (SI.getNumOperands() == 2) {
2084     // Update machine-CFG edges.
2085
2086     // If this is not a fall-through branch, emit the branch.
2087     CurMBB->addSuccessor(Default);
2088     if (Default != NextBlock)
2089       DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2090                               MVT::Other, getControlRoot(),
2091                               DAG.getBasicBlock(Default)));
2092     return;
2093   }
2094
2095   // If there are any non-default case statements, create a vector of Cases
2096   // representing each one, and sort the vector so that we can efficiently
2097   // create a binary search tree from them.
2098   CaseVector Cases;
2099   size_t numCmps = Clusterify(Cases, SI);
2100   DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2101                << ". Total compares: " << numCmps << '\n');
2102   numCmps = 0;
2103
2104   // Get the Value to be switched on and default basic blocks, which will be
2105   // inserted into CaseBlock records, representing basic blocks in the binary
2106   // search tree.
2107   Value *SV = SI.getOperand(0);
2108
2109   // Push the initial CaseRec onto the worklist
2110   CaseRecVector WorkList;
2111   WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2112
2113   while (!WorkList.empty()) {
2114     // Grab a record representing a case range to process off the worklist
2115     CaseRec CR = WorkList.back();
2116     WorkList.pop_back();
2117
2118     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2119       continue;
2120
2121     // If the range has few cases (two or less) emit a series of specific
2122     // tests.
2123     if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2124       continue;
2125
2126     // If the switch has more than 5 blocks, and at least 40% dense, and the
2127     // target supports indirect branches, then emit a jump table rather than
2128     // lowering the switch to a binary tree of conditional branches.
2129     if (handleJTSwitchCase(CR, WorkList, SV, Default))
2130       continue;
2131
2132     // Emit binary tree. We need to pick a pivot, and push left and right ranges
2133     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2134     handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2135   }
2136 }
2137
2138
2139 void SelectionDAGLowering::visitSub(User &I) {
2140   // -0.0 - X --> fneg
2141   const Type *Ty = I.getType();
2142   if (isa<VectorType>(Ty)) {
2143     if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2144       const VectorType *DestTy = cast<VectorType>(I.getType());
2145       const Type *ElTy = DestTy->getElementType();
2146       if (ElTy->isFloatingPoint()) {
2147         unsigned VL = DestTy->getNumElements();
2148         std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2149         Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2150         if (CV == CNZ) {
2151           SDValue Op2 = getValue(I.getOperand(1));
2152           setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2153                                    Op2.getValueType(), Op2));
2154           return;
2155         }
2156       }
2157     }
2158   }
2159   if (Ty->isFloatingPoint()) {
2160     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2161       if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2162         SDValue Op2 = getValue(I.getOperand(1));
2163         setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2164                                  Op2.getValueType(), Op2));
2165         return;
2166       }
2167   }
2168
2169   visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2170 }
2171
2172 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2173   SDValue Op1 = getValue(I.getOperand(0));
2174   SDValue Op2 = getValue(I.getOperand(1));
2175
2176   setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2177                            Op1.getValueType(), Op1, Op2));
2178 }
2179
2180 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2181   SDValue Op1 = getValue(I.getOperand(0));
2182   SDValue Op2 = getValue(I.getOperand(1));
2183   if (!isa<VectorType>(I.getType())) {
2184     if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
2185       Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2186                         TLI.getPointerTy(), Op2);
2187     else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
2188       Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2189                         TLI.getPointerTy(), Op2);
2190   }
2191
2192   setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2193                            Op1.getValueType(), Op1, Op2));
2194 }
2195
2196 void SelectionDAGLowering::visitICmp(User &I) {
2197   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2198   if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2199     predicate = IC->getPredicate();
2200   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2201     predicate = ICmpInst::Predicate(IC->getPredicate());
2202   SDValue Op1 = getValue(I.getOperand(0));
2203   SDValue Op2 = getValue(I.getOperand(1));
2204   ISD::CondCode Opcode = getICmpCondCode(predicate);
2205   setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
2206 }
2207
2208 void SelectionDAGLowering::visitFCmp(User &I) {
2209   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2210   if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2211     predicate = FC->getPredicate();
2212   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2213     predicate = FCmpInst::Predicate(FC->getPredicate());
2214   SDValue Op1 = getValue(I.getOperand(0));
2215   SDValue Op2 = getValue(I.getOperand(1));
2216   ISD::CondCode Condition = getFCmpCondCode(predicate);
2217   setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
2218 }
2219
2220 void SelectionDAGLowering::visitVICmp(User &I) {
2221   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2222   if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2223     predicate = IC->getPredicate();
2224   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2225     predicate = ICmpInst::Predicate(IC->getPredicate());
2226   SDValue Op1 = getValue(I.getOperand(0));
2227   SDValue Op2 = getValue(I.getOperand(1));
2228   ISD::CondCode Opcode = getICmpCondCode(predicate);
2229   setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
2230                              Op1, Op2, Opcode));
2231 }
2232
2233 void SelectionDAGLowering::visitVFCmp(User &I) {
2234   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2235   if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2236     predicate = FC->getPredicate();
2237   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2238     predicate = FCmpInst::Predicate(FC->getPredicate());
2239   SDValue Op1 = getValue(I.getOperand(0));
2240   SDValue Op2 = getValue(I.getOperand(1));
2241   ISD::CondCode Condition = getFCmpCondCode(predicate);
2242   MVT DestVT = TLI.getValueType(I.getType());
2243
2244   setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2245 }
2246
2247 void SelectionDAGLowering::visitSelect(User &I) {
2248   SmallVector<MVT, 4> ValueVTs;
2249   ComputeValueVTs(TLI, I.getType(), ValueVTs);
2250   unsigned NumValues = ValueVTs.size();
2251   if (NumValues != 0) {
2252     SmallVector<SDValue, 4> Values(NumValues);
2253     SDValue Cond     = getValue(I.getOperand(0));
2254     SDValue TrueVal  = getValue(I.getOperand(1));
2255     SDValue FalseVal = getValue(I.getOperand(2));
2256
2257     for (unsigned i = 0; i != NumValues; ++i)
2258       Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2259                               TrueVal.getValueType(), Cond,
2260                               SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2261                               SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2262
2263     setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2264                              DAG.getVTList(&ValueVTs[0], NumValues),
2265                              &Values[0], NumValues));
2266   }
2267 }
2268
2269
2270 void SelectionDAGLowering::visitTrunc(User &I) {
2271   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2272   SDValue N = getValue(I.getOperand(0));
2273   MVT DestVT = TLI.getValueType(I.getType());
2274   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2275 }
2276
2277 void SelectionDAGLowering::visitZExt(User &I) {
2278   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2279   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2280   SDValue N = getValue(I.getOperand(0));
2281   MVT DestVT = TLI.getValueType(I.getType());
2282   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2283 }
2284
2285 void SelectionDAGLowering::visitSExt(User &I) {
2286   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2287   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2288   SDValue N = getValue(I.getOperand(0));
2289   MVT DestVT = TLI.getValueType(I.getType());
2290   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2291 }
2292
2293 void SelectionDAGLowering::visitFPTrunc(User &I) {
2294   // FPTrunc is never a no-op cast, no need to check
2295   SDValue N = getValue(I.getOperand(0));
2296   MVT DestVT = TLI.getValueType(I.getType());
2297   setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2298                            DestVT, N, DAG.getIntPtrConstant(0)));
2299 }
2300
2301 void SelectionDAGLowering::visitFPExt(User &I){
2302   // FPTrunc is never a no-op cast, no need to check
2303   SDValue N = getValue(I.getOperand(0));
2304   MVT DestVT = TLI.getValueType(I.getType());
2305   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2306 }
2307
2308 void SelectionDAGLowering::visitFPToUI(User &I) {
2309   // FPToUI is never a no-op cast, no need to check
2310   SDValue N = getValue(I.getOperand(0));
2311   MVT DestVT = TLI.getValueType(I.getType());
2312   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2313 }
2314
2315 void SelectionDAGLowering::visitFPToSI(User &I) {
2316   // FPToSI is never a no-op cast, no need to check
2317   SDValue N = getValue(I.getOperand(0));
2318   MVT DestVT = TLI.getValueType(I.getType());
2319   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2320 }
2321
2322 void SelectionDAGLowering::visitUIToFP(User &I) {
2323   // UIToFP is never a no-op cast, no need to check
2324   SDValue N = getValue(I.getOperand(0));
2325   MVT DestVT = TLI.getValueType(I.getType());
2326   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2327 }
2328
2329 void SelectionDAGLowering::visitSIToFP(User &I){
2330   // SIToFP is never a no-op cast, no need to check
2331   SDValue N = getValue(I.getOperand(0));
2332   MVT DestVT = TLI.getValueType(I.getType());
2333   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2334 }
2335
2336 void SelectionDAGLowering::visitPtrToInt(User &I) {
2337   // What to do depends on the size of the integer and the size of the pointer.
2338   // We can either truncate, zero extend, or no-op, accordingly.
2339   SDValue N = getValue(I.getOperand(0));
2340   MVT SrcVT = N.getValueType();
2341   MVT DestVT = TLI.getValueType(I.getType());
2342   SDValue Result;
2343   if (DestVT.bitsLT(SrcVT))
2344     Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
2345   else
2346     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2347     Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
2348   setValue(&I, Result);
2349 }
2350
2351 void SelectionDAGLowering::visitIntToPtr(User &I) {
2352   // What to do depends on the size of the integer and the size of the pointer.
2353   // We can either truncate, zero extend, or no-op, accordingly.
2354   SDValue N = getValue(I.getOperand(0));
2355   MVT SrcVT = N.getValueType();
2356   MVT DestVT = TLI.getValueType(I.getType());
2357   if (DestVT.bitsLT(SrcVT))
2358     setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2359   else
2360     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2361     setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2362                              DestVT, N));
2363 }
2364
2365 void SelectionDAGLowering::visitBitCast(User &I) {
2366   SDValue N = getValue(I.getOperand(0));
2367   MVT DestVT = TLI.getValueType(I.getType());
2368
2369   // BitCast assures us that source and destination are the same size so this
2370   // is either a BIT_CONVERT or a no-op.
2371   if (DestVT != N.getValueType())
2372     setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2373                              DestVT, N)); // convert types
2374   else
2375     setValue(&I, N); // noop cast.
2376 }
2377
2378 void SelectionDAGLowering::visitInsertElement(User &I) {
2379   SDValue InVec = getValue(I.getOperand(0));
2380   SDValue InVal = getValue(I.getOperand(1));
2381   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2382                                 TLI.getPointerTy(),
2383                                 getValue(I.getOperand(2)));
2384
2385   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2386                            TLI.getValueType(I.getType()),
2387                            InVec, InVal, InIdx));
2388 }
2389
2390 void SelectionDAGLowering::visitExtractElement(User &I) {
2391   SDValue InVec = getValue(I.getOperand(0));
2392   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2393                                 TLI.getPointerTy(),
2394                                 getValue(I.getOperand(1)));
2395   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2396                            TLI.getValueType(I.getType()), InVec, InIdx));
2397 }
2398
2399
2400 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2401 // from SIndx and increasing to the element length (undefs are allowed).
2402 static bool SequentialMask(SDValue Mask, unsigned SIndx) {
2403   unsigned MaskNumElts = Mask.getNumOperands();
2404   for (unsigned i = 0; i != MaskNumElts; ++i) {
2405     if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2406       unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2407       if (Idx != i + SIndx)
2408         return false;
2409     }
2410   }
2411   return true;
2412 }
2413
2414 void SelectionDAGLowering::visitShuffleVector(User &I) {
2415   SDValue Src1 = getValue(I.getOperand(0));
2416   SDValue Src2 = getValue(I.getOperand(1));
2417   SDValue Mask = getValue(I.getOperand(2));
2418
2419   MVT VT = TLI.getValueType(I.getType());
2420   MVT SrcVT = Src1.getValueType();
2421   int MaskNumElts = Mask.getNumOperands();
2422   int SrcNumElts = SrcVT.getVectorNumElements();
2423
2424   if (SrcNumElts == MaskNumElts) {
2425     setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
2426                              VT, Src1, Src2, Mask));
2427     return;
2428   }
2429
2430   // Normalize the shuffle vector since mask and vector length don't match.
2431   MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2432
2433   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2434     // Mask is longer than the source vectors and is a multiple of the source
2435     // vectors.  We can use concatenate vector to make the mask and vectors
2436     // lengths match.
2437     if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2438       // The shuffle is concatenating two vectors together.
2439       setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2440                                VT, Src1, Src2));
2441       return;
2442     }
2443
2444     // Pad both vectors with undefs to make them the same length as the mask.
2445     unsigned NumConcat = MaskNumElts / SrcNumElts;
2446     SDValue UndefVal = DAG.getUNDEF(SrcVT);
2447
2448     SDValue* MOps1 = new SDValue[NumConcat];
2449     SDValue* MOps2 = new SDValue[NumConcat];
2450     MOps1[0] = Src1;
2451     MOps2[0] = Src2;
2452     for (unsigned i = 1; i != NumConcat; ++i) {
2453       MOps1[i] = UndefVal;
2454       MOps2[i] = UndefVal;
2455     }
2456     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2457                        VT, MOps1, NumConcat);
2458     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2459                        VT, MOps2, NumConcat);
2460
2461     delete [] MOps1;
2462     delete [] MOps2;
2463
2464     // Readjust mask for new input vector length.
2465     SmallVector<SDValue, 8> MappedOps;
2466     for (int i = 0; i != MaskNumElts; ++i) {
2467       if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2468         MappedOps.push_back(Mask.getOperand(i));
2469       } else {
2470         int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2471         if (Idx < SrcNumElts)
2472           MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2473         else
2474           MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2475                                               MaskEltVT));
2476       }
2477     }
2478     Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2479                        Mask.getValueType(),
2480                        &MappedOps[0], MappedOps.size());
2481
2482     setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
2483                              VT, Src1, Src2, Mask));
2484     return;
2485   }
2486
2487   if (SrcNumElts > MaskNumElts) {
2488     // Resulting vector is shorter than the incoming vector.
2489     if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
2490       // Shuffle extracts 1st vector.
2491       setValue(&I, Src1);
2492       return;
2493     }
2494
2495     if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
2496       // Shuffle extracts 2nd vector.
2497       setValue(&I, Src2);
2498       return;
2499     }
2500
2501     // Analyze the access pattern of the vector to see if we can extract
2502     // two subvectors and do the shuffle. The analysis is done by calculating
2503     // the range of elements the mask access on both vectors.
2504     int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2505     int MaxRange[2] = {-1, -1};
2506
2507     for (int i = 0; i != MaskNumElts; ++i) {
2508       SDValue Arg = Mask.getOperand(i);
2509       if (Arg.getOpcode() != ISD::UNDEF) {
2510         assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2511         int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2512         int Input = 0;
2513         if (Idx >= SrcNumElts) {
2514           Input = 1;
2515           Idx -= SrcNumElts;
2516         }
2517         if (Idx > MaxRange[Input])
2518           MaxRange[Input] = Idx;
2519         if (Idx < MinRange[Input])
2520           MinRange[Input] = Idx;
2521       }
2522     }
2523
2524     // Check if the access is smaller than the vector size and can we find
2525     // a reasonable extract index.
2526     int RangeUse[2] = { 2, 2 };  // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2527     int StartIdx[2];  // StartIdx to extract from
2528     for (int Input=0; Input < 2; ++Input) {
2529       if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2530         RangeUse[Input] = 0; // Unused
2531         StartIdx[Input] = 0;
2532       } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2533         // Fits within range but we should see if we can find a good
2534         // start index that is a multiple of the mask length.
2535         if (MaxRange[Input] < MaskNumElts) {
2536           RangeUse[Input] = 1; // Extract from beginning of the vector
2537           StartIdx[Input] = 0;
2538         } else {
2539           StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2540           if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
2541               StartIdx[Input] + MaskNumElts < SrcNumElts)
2542             RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2543         }
2544       }
2545     }
2546
2547     if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2548       setValue(&I, DAG.getUNDEF(VT));  // Vectors are not used.
2549       return;
2550     }
2551     else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2552       // Extract appropriate subvector and generate a vector shuffle
2553       for (int Input=0; Input < 2; ++Input) {
2554         SDValue& Src = Input == 0 ? Src1 : Src2;
2555         if (RangeUse[Input] == 0) {
2556           Src = DAG.getUNDEF(VT);
2557         } else {
2558           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2559                             Src, DAG.getIntPtrConstant(StartIdx[Input]));
2560         }
2561       }
2562       // Calculate new mask.
2563       SmallVector<SDValue, 8> MappedOps;
2564       for (int i = 0; i != MaskNumElts; ++i) {
2565         SDValue Arg = Mask.getOperand(i);
2566         if (Arg.getOpcode() == ISD::UNDEF) {
2567           MappedOps.push_back(Arg);
2568         } else {
2569           int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2570           if (Idx < SrcNumElts)
2571             MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2572           else {
2573             Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2574             MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2575           }
2576         }
2577       }
2578       Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2579                          Mask.getValueType(),
2580                          &MappedOps[0], MappedOps.size());
2581       setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
2582                                VT, Src1, Src2, Mask));
2583       return;
2584     }
2585   }
2586
2587   // We can't use either concat vectors or extract subvectors so fall back to
2588   // replacing the shuffle with extract and build vector.
2589   // to insert and build vector.
2590   MVT EltVT = VT.getVectorElementType();
2591   MVT PtrVT = TLI.getPointerTy();
2592   SmallVector<SDValue,8> Ops;
2593   for (int i = 0; i != MaskNumElts; ++i) {
2594     SDValue Arg = Mask.getOperand(i);
2595     if (Arg.getOpcode() == ISD::UNDEF) {
2596       Ops.push_back(DAG.getUNDEF(EltVT));
2597     } else {
2598       assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2599       int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2600       if (Idx < SrcNumElts)
2601         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2602                                   EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
2603       else
2604         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2605                                   EltVT, Src2,
2606                                   DAG.getConstant(Idx - SrcNumElts, PtrVT)));
2607     }
2608   }
2609   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2610                            VT, &Ops[0], Ops.size()));
2611 }
2612
2613 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2614   const Value *Op0 = I.getOperand(0);
2615   const Value *Op1 = I.getOperand(1);
2616   const Type *AggTy = I.getType();
2617   const Type *ValTy = Op1->getType();
2618   bool IntoUndef = isa<UndefValue>(Op0);
2619   bool FromUndef = isa<UndefValue>(Op1);
2620
2621   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2622                                             I.idx_begin(), I.idx_end());
2623
2624   SmallVector<MVT, 4> AggValueVTs;
2625   ComputeValueVTs(TLI, AggTy, AggValueVTs);
2626   SmallVector<MVT, 4> ValValueVTs;
2627   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2628
2629   unsigned NumAggValues = AggValueVTs.size();
2630   unsigned NumValValues = ValValueVTs.size();
2631   SmallVector<SDValue, 4> Values(NumAggValues);
2632
2633   SDValue Agg = getValue(Op0);
2634   SDValue Val = getValue(Op1);
2635   unsigned i = 0;
2636   // Copy the beginning value(s) from the original aggregate.
2637   for (; i != LinearIndex; ++i)
2638     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2639                 SDValue(Agg.getNode(), Agg.getResNo() + i);
2640   // Copy values from the inserted value(s).
2641   for (; i != LinearIndex + NumValValues; ++i)
2642     Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2643                 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2644   // Copy remaining value(s) from the original aggregate.
2645   for (; i != NumAggValues; ++i)
2646     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2647                 SDValue(Agg.getNode(), Agg.getResNo() + i);
2648
2649   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2650                            DAG.getVTList(&AggValueVTs[0], NumAggValues),
2651                            &Values[0], NumAggValues));
2652 }
2653
2654 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2655   const Value *Op0 = I.getOperand(0);
2656   const Type *AggTy = Op0->getType();
2657   const Type *ValTy = I.getType();
2658   bool OutOfUndef = isa<UndefValue>(Op0);
2659
2660   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2661                                             I.idx_begin(), I.idx_end());
2662
2663   SmallVector<MVT, 4> ValValueVTs;
2664   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2665
2666   unsigned NumValValues = ValValueVTs.size();
2667   SmallVector<SDValue, 4> Values(NumValValues);
2668
2669   SDValue Agg = getValue(Op0);
2670   // Copy out the selected value(s).
2671   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2672     Values[i - LinearIndex] =
2673       OutOfUndef ?
2674         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2675         SDValue(Agg.getNode(), Agg.getResNo() + i);
2676
2677   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2678                            DAG.getVTList(&ValValueVTs[0], NumValValues),
2679                            &Values[0], NumValValues));
2680 }
2681
2682
2683 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2684   SDValue N = getValue(I.getOperand(0));
2685   const Type *Ty = I.getOperand(0)->getType();
2686
2687   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2688        OI != E; ++OI) {
2689     Value *Idx = *OI;
2690     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2691       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2692       if (Field) {
2693         // N = N + Offset
2694         uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2695         N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2696                         DAG.getIntPtrConstant(Offset));
2697       }
2698       Ty = StTy->getElementType(Field);
2699     } else {
2700       Ty = cast<SequentialType>(Ty)->getElementType();
2701
2702       // If this is a constant subscript, handle it quickly.
2703       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2704         if (CI->getZExtValue() == 0) continue;
2705         uint64_t Offs =
2706             TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2707         SDValue OffsVal;
2708         unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
2709         if (PtrBits < 64) {
2710           OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2711                                 TLI.getPointerTy(),
2712                                 DAG.getConstant(Offs, MVT::i64));
2713         } else
2714           OffsVal = DAG.getIntPtrConstant(Offs);
2715         N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2716                         OffsVal);
2717         continue;
2718       }
2719
2720       // N = N + Idx * ElementSize;
2721       uint64_t ElementSize = TD->getTypePaddedSize(Ty);
2722       SDValue IdxN = getValue(Idx);
2723
2724       // If the index is smaller or larger than intptr_t, truncate or extend
2725       // it.
2726       if (IdxN.getValueType().bitsLT(N.getValueType()))
2727         IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
2728                            N.getValueType(), IdxN);
2729       else if (IdxN.getValueType().bitsGT(N.getValueType()))
2730         IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2731                            N.getValueType(), IdxN);
2732
2733       // If this is a multiply by a power of two, turn it into a shl
2734       // immediately.  This is a very common case.
2735       if (ElementSize != 1) {
2736         if (isPowerOf2_64(ElementSize)) {
2737           unsigned Amt = Log2_64(ElementSize);
2738           IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2739                              N.getValueType(), IdxN,
2740                              DAG.getConstant(Amt, TLI.getPointerTy()));
2741         } else {
2742           SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2743           IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2744                              N.getValueType(), IdxN, Scale);
2745         }
2746       }
2747
2748       N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2749                       N.getValueType(), N, IdxN);
2750     }
2751   }
2752   setValue(&I, N);
2753 }
2754
2755 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2756   // If this is a fixed sized alloca in the entry block of the function,
2757   // allocate it statically on the stack.
2758   if (FuncInfo.StaticAllocaMap.count(&I))
2759     return;   // getValue will auto-populate this.
2760
2761   const Type *Ty = I.getAllocatedType();
2762   uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
2763   unsigned Align =
2764     std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2765              I.getAlignment());
2766
2767   SDValue AllocSize = getValue(I.getArraySize());
2768   
2769   AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2770                           AllocSize,
2771                           DAG.getConstant(TySize, AllocSize.getValueType()));
2772   
2773   
2774   
2775   MVT IntPtr = TLI.getPointerTy();
2776   if (IntPtr.bitsLT(AllocSize.getValueType()))
2777     AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2778                             IntPtr, AllocSize);
2779   else if (IntPtr.bitsGT(AllocSize.getValueType()))
2780     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2781                             IntPtr, AllocSize);
2782
2783   // Handle alignment.  If the requested alignment is less than or equal to
2784   // the stack alignment, ignore it.  If the size is greater than or equal to
2785   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2786   unsigned StackAlign =
2787     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2788   if (Align <= StackAlign)
2789     Align = 0;
2790
2791   // Round the size of the allocation up to the stack alignment size
2792   // by add SA-1 to the size.
2793   AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2794                           AllocSize.getValueType(), AllocSize,
2795                           DAG.getIntPtrConstant(StackAlign-1));
2796   // Mask out the low bits for alignment purposes.
2797   AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2798                           AllocSize.getValueType(), AllocSize,
2799                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2800
2801   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2802   const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2803                                                     MVT::Other);
2804   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2805                             VTs, 2, Ops, 3);
2806   setValue(&I, DSA);
2807   DAG.setRoot(DSA.getValue(1));
2808
2809   // Inform the Frame Information that we have just allocated a variable-sized
2810   // object.
2811   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2812 }
2813
2814 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2815   const Value *SV = I.getOperand(0);
2816   SDValue Ptr = getValue(SV);
2817
2818   const Type *Ty = I.getType();
2819   bool isVolatile = I.isVolatile();
2820   unsigned Alignment = I.getAlignment();
2821
2822   SmallVector<MVT, 4> ValueVTs;
2823   SmallVector<uint64_t, 4> Offsets;
2824   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2825   unsigned NumValues = ValueVTs.size();
2826   if (NumValues == 0)
2827     return;
2828
2829   SDValue Root;
2830   bool ConstantMemory = false;
2831   if (I.isVolatile())
2832     // Serialize volatile loads with other side effects.
2833     Root = getRoot();
2834   else if (AA->pointsToConstantMemory(SV)) {
2835     // Do not serialize (non-volatile) loads of constant memory with anything.
2836     Root = DAG.getEntryNode();
2837     ConstantMemory = true;
2838   } else {
2839     // Do not serialize non-volatile loads against each other.
2840     Root = DAG.getRoot();
2841   }
2842
2843   SmallVector<SDValue, 4> Values(NumValues);
2844   SmallVector<SDValue, 4> Chains(NumValues);
2845   MVT PtrVT = Ptr.getValueType();
2846   for (unsigned i = 0; i != NumValues; ++i) {
2847     SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2848                               DAG.getNode(ISD::ADD, getCurDebugLoc(),
2849                                           PtrVT, Ptr,
2850                                           DAG.getConstant(Offsets[i], PtrVT)),
2851                               SV, Offsets[i],
2852                               isVolatile, Alignment);
2853     Values[i] = L;
2854     Chains[i] = L.getValue(1);
2855   }
2856
2857   if (!ConstantMemory) {
2858     SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2859                                   MVT::Other,
2860                                   &Chains[0], NumValues);
2861     if (isVolatile)
2862       DAG.setRoot(Chain);
2863     else
2864       PendingLoads.push_back(Chain);
2865   }
2866
2867   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2868                            DAG.getVTList(&ValueVTs[0], NumValues),
2869                            &Values[0], NumValues));
2870 }
2871
2872
2873 void SelectionDAGLowering::visitStore(StoreInst &I) {
2874   Value *SrcV = I.getOperand(0);
2875   Value *PtrV = I.getOperand(1);
2876
2877   SmallVector<MVT, 4> ValueVTs;
2878   SmallVector<uint64_t, 4> Offsets;
2879   ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2880   unsigned NumValues = ValueVTs.size();
2881   if (NumValues == 0)
2882     return;
2883
2884   // Get the lowered operands. Note that we do this after
2885   // checking if NumResults is zero, because with zero results
2886   // the operands won't have values in the map.
2887   SDValue Src = getValue(SrcV);
2888   SDValue Ptr = getValue(PtrV);
2889
2890   SDValue Root = getRoot();
2891   SmallVector<SDValue, 4> Chains(NumValues);
2892   MVT PtrVT = Ptr.getValueType();
2893   bool isVolatile = I.isVolatile();
2894   unsigned Alignment = I.getAlignment();
2895   for (unsigned i = 0; i != NumValues; ++i)
2896     Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2897                              SDValue(Src.getNode(), Src.getResNo() + i),
2898                              DAG.getNode(ISD::ADD, getCurDebugLoc(),
2899                                          PtrVT, Ptr,
2900                                          DAG.getConstant(Offsets[i], PtrVT)),
2901                              PtrV, Offsets[i],
2902                              isVolatile, Alignment);
2903
2904   DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2905                           MVT::Other, &Chains[0], NumValues));
2906 }
2907
2908 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2909 /// node.
2910 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2911                                                 unsigned Intrinsic) {
2912   bool HasChain = !I.doesNotAccessMemory();
2913   bool OnlyLoad = HasChain && I.onlyReadsMemory();
2914
2915   // Build the operand list.
2916   SmallVector<SDValue, 8> Ops;
2917   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
2918     if (OnlyLoad) {
2919       // We don't need to serialize loads against other loads.
2920       Ops.push_back(DAG.getRoot());
2921     } else {
2922       Ops.push_back(getRoot());
2923     }
2924   }
2925
2926   // Info is set by getTgtMemInstrinsic
2927   TargetLowering::IntrinsicInfo Info;
2928   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2929
2930   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2931   if (!IsTgtIntrinsic)
2932     Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2933
2934   // Add all operands of the call to the operand list.
2935   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2936     SDValue Op = getValue(I.getOperand(i));
2937     assert(TLI.isTypeLegal(Op.getValueType()) &&
2938            "Intrinsic uses a non-legal type?");
2939     Ops.push_back(Op);
2940   }
2941
2942   std::vector<MVT> VTs;
2943   if (I.getType() != Type::VoidTy) {
2944     MVT VT = TLI.getValueType(I.getType());
2945     if (VT.isVector()) {
2946       const VectorType *DestTy = cast<VectorType>(I.getType());
2947       MVT EltVT = TLI.getValueType(DestTy->getElementType());
2948
2949       VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2950       assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2951     }
2952
2953     assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2954     VTs.push_back(VT);
2955   }
2956   if (HasChain)
2957     VTs.push_back(MVT::Other);
2958
2959   const MVT *VTList = DAG.getNodeValueTypes(VTs);
2960
2961   // Create the node.
2962   SDValue Result;
2963   if (IsTgtIntrinsic) {
2964     // This is target intrinsic that touches memory
2965     Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2966                                      VTList, VTs.size(),
2967                                      &Ops[0], Ops.size(),
2968                                      Info.memVT, Info.ptrVal, Info.offset,
2969                                      Info.align, Info.vol,
2970                                      Info.readMem, Info.writeMem);
2971   }
2972   else if (!HasChain)
2973     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2974                          VTList, VTs.size(),
2975                          &Ops[0], Ops.size());
2976   else if (I.getType() != Type::VoidTy)
2977     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2978                          VTList, VTs.size(),
2979                          &Ops[0], Ops.size());
2980   else
2981     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2982                          VTList, VTs.size(),
2983                          &Ops[0], Ops.size());
2984
2985   if (HasChain) {
2986     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2987     if (OnlyLoad)
2988       PendingLoads.push_back(Chain);
2989     else
2990       DAG.setRoot(Chain);
2991   }
2992   if (I.getType() != Type::VoidTy) {
2993     if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2994       MVT VT = TLI.getValueType(PTy);
2995       Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2996     }
2997     setValue(&I, Result);
2998   }
2999 }
3000
3001 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3002 static GlobalVariable *ExtractTypeInfo(Value *V) {
3003   V = V->stripPointerCasts();
3004   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3005   assert ((GV || isa<ConstantPointerNull>(V)) &&
3006           "TypeInfo must be a global variable or NULL");
3007   return GV;
3008 }
3009
3010 namespace llvm {
3011
3012 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
3013 /// call, and add them to the specified machine basic block.
3014 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3015                   MachineBasicBlock *MBB) {
3016   // Inform the MachineModuleInfo of the personality for this landing pad.
3017   ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3018   assert(CE->getOpcode() == Instruction::BitCast &&
3019          isa<Function>(CE->getOperand(0)) &&
3020          "Personality should be a function");
3021   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3022
3023   // Gather all the type infos for this landing pad and pass them along to
3024   // MachineModuleInfo.
3025   std::vector<GlobalVariable *> TyInfo;
3026   unsigned N = I.getNumOperands();
3027
3028   for (unsigned i = N - 1; i > 2; --i) {
3029     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3030       unsigned FilterLength = CI->getZExtValue();
3031       unsigned FirstCatch = i + FilterLength + !FilterLength;
3032       assert (FirstCatch <= N && "Invalid filter length");
3033
3034       if (FirstCatch < N) {
3035         TyInfo.reserve(N - FirstCatch);
3036         for (unsigned j = FirstCatch; j < N; ++j)
3037           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3038         MMI->addCatchTypeInfo(MBB, TyInfo);
3039         TyInfo.clear();
3040       }
3041
3042       if (!FilterLength) {
3043         // Cleanup.
3044         MMI->addCleanup(MBB);
3045       } else {
3046         // Filter.
3047         TyInfo.reserve(FilterLength - 1);
3048         for (unsigned j = i + 1; j < FirstCatch; ++j)
3049           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3050         MMI->addFilterTypeInfo(MBB, TyInfo);
3051         TyInfo.clear();
3052       }
3053
3054       N = i;
3055     }
3056   }
3057
3058   if (N > 3) {
3059     TyInfo.reserve(N - 3);
3060     for (unsigned j = 3; j < N; ++j)
3061       TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3062     MMI->addCatchTypeInfo(MBB, TyInfo);
3063   }
3064 }
3065
3066 }
3067
3068 /// GetSignificand - Get the significand and build it into a floating-point
3069 /// number with exponent of 1:
3070 ///
3071 ///   Op = (Op & 0x007fffff) | 0x3f800000;
3072 ///
3073 /// where Op is the hexidecimal representation of floating point value.
3074 static SDValue
3075 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3076   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3077                            DAG.getConstant(0x007fffff, MVT::i32));
3078   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3079                            DAG.getConstant(0x3f800000, MVT::i32));
3080   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3081 }
3082
3083 /// GetExponent - Get the exponent:
3084 ///
3085 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3086 ///
3087 /// where Op is the hexidecimal representation of floating point value.
3088 static SDValue
3089 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3090             DebugLoc dl) {
3091   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3092                            DAG.getConstant(0x7f800000, MVT::i32));
3093   SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3094                            DAG.getConstant(23, TLI.getPointerTy()));
3095   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3096                            DAG.getConstant(127, MVT::i32));
3097   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3098 }
3099
3100 /// getF32Constant - Get 32-bit floating point constant.
3101 static SDValue
3102 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3103   return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3104 }
3105
3106 /// Inlined utility function to implement binary input atomic intrinsics for
3107 /// visitIntrinsicCall: I is a call instruction
3108 ///                     Op is the associated NodeType for I
3109 const char *
3110 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3111   SDValue Root = getRoot();
3112   SDValue L =
3113     DAG.getAtomic(Op, getCurDebugLoc(),
3114                   getValue(I.getOperand(2)).getValueType().getSimpleVT(),
3115                   Root,
3116                   getValue(I.getOperand(1)),
3117                   getValue(I.getOperand(2)),
3118                   I.getOperand(1));
3119   setValue(&I, L);
3120   DAG.setRoot(L.getValue(1));
3121   return 0;
3122 }
3123
3124 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3125 const char *
3126 SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
3127   SDValue Op1 = getValue(I.getOperand(1));
3128   SDValue Op2 = getValue(I.getOperand(2));
3129
3130   MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
3131   SDValue Ops[] = { Op1, Op2 };
3132
3133   SDValue Result = DAG.getNode(Op, getCurDebugLoc(),
3134                                DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
3135
3136   setValue(&I, Result);
3137   return 0;
3138 }
3139
3140 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3141 /// limited-precision mode.
3142 void
3143 SelectionDAGLowering::visitExp(CallInst &I) {
3144   SDValue result;
3145   DebugLoc dl = getCurDebugLoc();
3146
3147   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3148       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3149     SDValue Op = getValue(I.getOperand(1));
3150
3151     // Put the exponent in the right bit position for later addition to the
3152     // final result:
3153     //
3154     //   #define LOG2OFe 1.4426950f
3155     //   IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3156     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3157                              getF32Constant(DAG, 0x3fb8aa3b));
3158     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3159
3160     //   FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3161     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3162     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3163
3164     //   IntegerPartOfX <<= 23;
3165     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3166                                  DAG.getConstant(23, TLI.getPointerTy()));
3167
3168     if (LimitFloatPrecision <= 6) {
3169       // For floating-point precision of 6:
3170       //
3171       //   TwoToFractionalPartOfX =
3172       //     0.997535578f +
3173       //       (0.735607626f + 0.252464424f * x) * x;
3174       //
3175       // error 0.0144103317, which is 6 bits
3176       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3177                                getF32Constant(DAG, 0x3e814304));
3178       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3179                                getF32Constant(DAG, 0x3f3c50c8));
3180       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3181       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3182                                getF32Constant(DAG, 0x3f7f5e7e));
3183       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3184
3185       // Add the exponent into the result in integer domain.
3186       SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3187                                TwoToFracPartOfX, IntegerPartOfX);
3188
3189       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3190     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3191       // For floating-point precision of 12:
3192       //
3193       //   TwoToFractionalPartOfX =
3194       //     0.999892986f +
3195       //       (0.696457318f +
3196       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3197       //
3198       // 0.000107046256 error, which is 13 to 14 bits
3199       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3200                                getF32Constant(DAG, 0x3da235e3));
3201       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3202                                getF32Constant(DAG, 0x3e65b8f3));
3203       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3204       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3205                                getF32Constant(DAG, 0x3f324b07));
3206       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3207       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3208                                getF32Constant(DAG, 0x3f7ff8fd));
3209       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3210
3211       // Add the exponent into the result in integer domain.
3212       SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3213                                TwoToFracPartOfX, IntegerPartOfX);
3214
3215       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3216     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3217       // For floating-point precision of 18:
3218       //
3219       //   TwoToFractionalPartOfX =
3220       //     0.999999982f +
3221       //       (0.693148872f +
3222       //         (0.240227044f +
3223       //           (0.554906021e-1f +
3224       //             (0.961591928e-2f +
3225       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3226       //
3227       // error 2.47208000*10^(-7), which is better than 18 bits
3228       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3229                                getF32Constant(DAG, 0x3924b03e));
3230       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3231                                getF32Constant(DAG, 0x3ab24b87));
3232       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3233       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3234                                getF32Constant(DAG, 0x3c1d8c17));
3235       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3236       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3237                                getF32Constant(DAG, 0x3d634a1d));
3238       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3239       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3240                                getF32Constant(DAG, 0x3e75fe14));
3241       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3242       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3243                                 getF32Constant(DAG, 0x3f317234));
3244       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3245       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3246                                 getF32Constant(DAG, 0x3f800000));
3247       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3248                                              MVT::i32, t13);
3249
3250       // Add the exponent into the result in integer domain.
3251       SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3252                                 TwoToFracPartOfX, IntegerPartOfX);
3253
3254       result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3255     }
3256   } else {
3257     // No special expansion.
3258     result = DAG.getNode(ISD::FEXP, dl,
3259                          getValue(I.getOperand(1)).getValueType(),
3260                          getValue(I.getOperand(1)));
3261   }
3262
3263   setValue(&I, result);
3264 }
3265
3266 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3267 /// limited-precision mode.
3268 void
3269 SelectionDAGLowering::visitLog(CallInst &I) {
3270   SDValue result;
3271   DebugLoc dl = getCurDebugLoc();
3272
3273   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3274       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3275     SDValue Op = getValue(I.getOperand(1));
3276     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3277
3278     // Scale the exponent by log(2) [0.69314718f].
3279     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3280     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3281                                         getF32Constant(DAG, 0x3f317218));
3282
3283     // Get the significand and build it into a floating-point number with
3284     // exponent of 1.
3285     SDValue X = GetSignificand(DAG, Op1, dl);
3286
3287     if (LimitFloatPrecision <= 6) {
3288       // For floating-point precision of 6:
3289       //
3290       //   LogofMantissa =
3291       //     -1.1609546f +
3292       //       (1.4034025f - 0.23903021f * x) * x;
3293       //
3294       // error 0.0034276066, which is better than 8 bits
3295       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3296                                getF32Constant(DAG, 0xbe74c456));
3297       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3298                                getF32Constant(DAG, 0x3fb3a2b1));
3299       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3300       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3301                                           getF32Constant(DAG, 0x3f949a29));
3302
3303       result = DAG.getNode(ISD::FADD, dl,
3304                            MVT::f32, LogOfExponent, LogOfMantissa);
3305     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3306       // For floating-point precision of 12:
3307       //
3308       //   LogOfMantissa =
3309       //     -1.7417939f +
3310       //       (2.8212026f +
3311       //         (-1.4699568f +
3312       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3313       //
3314       // error 0.000061011436, which is 14 bits
3315       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3316                                getF32Constant(DAG, 0xbd67b6d6));
3317       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3318                                getF32Constant(DAG, 0x3ee4f4b8));
3319       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3320       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3321                                getF32Constant(DAG, 0x3fbc278b));
3322       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3323       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3324                                getF32Constant(DAG, 0x40348e95));
3325       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3326       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3327                                           getF32Constant(DAG, 0x3fdef31a));
3328
3329       result = DAG.getNode(ISD::FADD, dl,
3330                            MVT::f32, LogOfExponent, LogOfMantissa);
3331     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3332       // For floating-point precision of 18:
3333       //
3334       //   LogOfMantissa =
3335       //     -2.1072184f +
3336       //       (4.2372794f +
3337       //         (-3.7029485f +
3338       //           (2.2781945f +
3339       //             (-0.87823314f +
3340       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3341       //
3342       // error 0.0000023660568, which is better than 18 bits
3343       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3344                                getF32Constant(DAG, 0xbc91e5ac));
3345       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3346                                getF32Constant(DAG, 0x3e4350aa));
3347       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3348       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3349                                getF32Constant(DAG, 0x3f60d3e3));
3350       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3351       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3352                                getF32Constant(DAG, 0x4011cdf0));
3353       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3354       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3355                                getF32Constant(DAG, 0x406cfd1c));
3356       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3357       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3358                                getF32Constant(DAG, 0x408797cb));
3359       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3360       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3361                                           getF32Constant(DAG, 0x4006dcab));
3362
3363       result = DAG.getNode(ISD::FADD, dl,
3364                            MVT::f32, LogOfExponent, LogOfMantissa);
3365     }
3366   } else {
3367     // No special expansion.
3368     result = DAG.getNode(ISD::FLOG, dl,
3369                          getValue(I.getOperand(1)).getValueType(),
3370                          getValue(I.getOperand(1)));
3371   }
3372
3373   setValue(&I, result);
3374 }
3375
3376 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3377 /// limited-precision mode.
3378 void
3379 SelectionDAGLowering::visitLog2(CallInst &I) {
3380   SDValue result;
3381   DebugLoc dl = getCurDebugLoc();
3382
3383   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3384       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3385     SDValue Op = getValue(I.getOperand(1));
3386     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3387
3388     // Get the exponent.
3389     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3390
3391     // Get the significand and build it into a floating-point number with
3392     // exponent of 1.
3393     SDValue X = GetSignificand(DAG, Op1, dl);
3394
3395     // Different possible minimax approximations of significand in
3396     // floating-point for various degrees of accuracy over [1,2].
3397     if (LimitFloatPrecision <= 6) {
3398       // For floating-point precision of 6:
3399       //
3400       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3401       //
3402       // error 0.0049451742, which is more than 7 bits
3403       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3404                                getF32Constant(DAG, 0xbeb08fe0));
3405       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3406                                getF32Constant(DAG, 0x40019463));
3407       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3408       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3409                                            getF32Constant(DAG, 0x3fd6633d));
3410
3411       result = DAG.getNode(ISD::FADD, dl,
3412                            MVT::f32, LogOfExponent, Log2ofMantissa);
3413     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3414       // For floating-point precision of 12:
3415       //
3416       //   Log2ofMantissa =
3417       //     -2.51285454f +
3418       //       (4.07009056f +
3419       //         (-2.12067489f +
3420       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3421       //
3422       // error 0.0000876136000, which is better than 13 bits
3423       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3424                                getF32Constant(DAG, 0xbda7262e));
3425       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3426                                getF32Constant(DAG, 0x3f25280b));
3427       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3428       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3429                                getF32Constant(DAG, 0x4007b923));
3430       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3431       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3432                                getF32Constant(DAG, 0x40823e2f));
3433       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3434       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3435                                            getF32Constant(DAG, 0x4020d29c));
3436
3437       result = DAG.getNode(ISD::FADD, dl,
3438                            MVT::f32, LogOfExponent, Log2ofMantissa);
3439     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3440       // For floating-point precision of 18:
3441       //
3442       //   Log2ofMantissa =
3443       //     -3.0400495f +
3444       //       (6.1129976f +
3445       //         (-5.3420409f +
3446       //           (3.2865683f +
3447       //             (-1.2669343f +
3448       //               (0.27515199f -
3449       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3450       //
3451       // error 0.0000018516, which is better than 18 bits
3452       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3453                                getF32Constant(DAG, 0xbcd2769e));
3454       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3455                                getF32Constant(DAG, 0x3e8ce0b9));
3456       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3457       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3458                                getF32Constant(DAG, 0x3fa22ae7));
3459       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3460       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3461                                getF32Constant(DAG, 0x40525723));
3462       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3463       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3464                                getF32Constant(DAG, 0x40aaf200));
3465       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3466       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3467                                getF32Constant(DAG, 0x40c39dad));
3468       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3469       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3470                                            getF32Constant(DAG, 0x4042902c));
3471
3472       result = DAG.getNode(ISD::FADD, dl,
3473                            MVT::f32, LogOfExponent, Log2ofMantissa);
3474     }
3475   } else {
3476     // No special expansion.
3477     result = DAG.getNode(ISD::FLOG2, dl,
3478                          getValue(I.getOperand(1)).getValueType(),
3479                          getValue(I.getOperand(1)));
3480   }
3481
3482   setValue(&I, result);
3483 }
3484
3485 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3486 /// limited-precision mode.
3487 void
3488 SelectionDAGLowering::visitLog10(CallInst &I) {
3489   SDValue result;
3490   DebugLoc dl = getCurDebugLoc();
3491
3492   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3493       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3494     SDValue Op = getValue(I.getOperand(1));
3495     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3496
3497     // Scale the exponent by log10(2) [0.30102999f].
3498     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3499     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3500                                         getF32Constant(DAG, 0x3e9a209a));
3501
3502     // Get the significand and build it into a floating-point number with
3503     // exponent of 1.
3504     SDValue X = GetSignificand(DAG, Op1, dl);
3505
3506     if (LimitFloatPrecision <= 6) {
3507       // For floating-point precision of 6:
3508       //
3509       //   Log10ofMantissa =
3510       //     -0.50419619f +
3511       //       (0.60948995f - 0.10380950f * x) * x;
3512       //
3513       // error 0.0014886165, which is 6 bits
3514       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3515                                getF32Constant(DAG, 0xbdd49a13));
3516       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3517                                getF32Constant(DAG, 0x3f1c0789));
3518       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3519       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3520                                             getF32Constant(DAG, 0x3f011300));
3521
3522       result = DAG.getNode(ISD::FADD, dl,
3523                            MVT::f32, LogOfExponent, Log10ofMantissa);
3524     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3525       // For floating-point precision of 12:
3526       //
3527       //   Log10ofMantissa =
3528       //     -0.64831180f +
3529       //       (0.91751397f +
3530       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3531       //
3532       // error 0.00019228036, which is better than 12 bits
3533       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3534                                getF32Constant(DAG, 0x3d431f31));
3535       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3536                                getF32Constant(DAG, 0x3ea21fb2));
3537       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3538       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3539                                getF32Constant(DAG, 0x3f6ae232));
3540       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3541       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3542                                             getF32Constant(DAG, 0x3f25f7c3));
3543
3544       result = DAG.getNode(ISD::FADD, dl,
3545                            MVT::f32, LogOfExponent, Log10ofMantissa);
3546     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3547       // For floating-point precision of 18:
3548       //
3549       //   Log10ofMantissa =
3550       //     -0.84299375f +
3551       //       (1.5327582f +
3552       //         (-1.0688956f +
3553       //           (0.49102474f +
3554       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3555       //
3556       // error 0.0000037995730, which is better than 18 bits
3557       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3558                                getF32Constant(DAG, 0x3c5d51ce));
3559       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3560                                getF32Constant(DAG, 0x3e00685a));
3561       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3562       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3563                                getF32Constant(DAG, 0x3efb6798));
3564       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3565       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3566                                getF32Constant(DAG, 0x3f88d192));
3567       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3568       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3569                                getF32Constant(DAG, 0x3fc4316c));
3570       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3571       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3572                                             getF32Constant(DAG, 0x3f57ce70));
3573
3574       result = DAG.getNode(ISD::FADD, dl,
3575                            MVT::f32, LogOfExponent, Log10ofMantissa);
3576     }
3577   } else {
3578     // No special expansion.
3579     result = DAG.getNode(ISD::FLOG10, dl,
3580                          getValue(I.getOperand(1)).getValueType(),
3581                          getValue(I.getOperand(1)));
3582   }
3583
3584   setValue(&I, result);
3585 }
3586
3587 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3588 /// limited-precision mode.
3589 void
3590 SelectionDAGLowering::visitExp2(CallInst &I) {
3591   SDValue result;
3592   DebugLoc dl = getCurDebugLoc();
3593
3594   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3595       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3596     SDValue Op = getValue(I.getOperand(1));
3597
3598     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3599
3600     //   FractionalPartOfX = x - (float)IntegerPartOfX;
3601     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3602     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3603
3604     //   IntegerPartOfX <<= 23;
3605     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3606                                  DAG.getConstant(23, TLI.getPointerTy()));
3607
3608     if (LimitFloatPrecision <= 6) {
3609       // For floating-point precision of 6:
3610       //
3611       //   TwoToFractionalPartOfX =
3612       //     0.997535578f +
3613       //       (0.735607626f + 0.252464424f * x) * x;
3614       //
3615       // error 0.0144103317, which is 6 bits
3616       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3617                                getF32Constant(DAG, 0x3e814304));
3618       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3619                                getF32Constant(DAG, 0x3f3c50c8));
3620       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3621       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3622                                getF32Constant(DAG, 0x3f7f5e7e));
3623       SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3624       SDValue TwoToFractionalPartOfX =
3625         DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3626
3627       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3628                            MVT::f32, TwoToFractionalPartOfX);
3629     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3630       // For floating-point precision of 12:
3631       //
3632       //   TwoToFractionalPartOfX =
3633       //     0.999892986f +
3634       //       (0.696457318f +
3635       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3636       //
3637       // error 0.000107046256, which is 13 to 14 bits
3638       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3639                                getF32Constant(DAG, 0x3da235e3));
3640       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3641                                getF32Constant(DAG, 0x3e65b8f3));
3642       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3643       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3644                                getF32Constant(DAG, 0x3f324b07));
3645       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3646       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3647                                getF32Constant(DAG, 0x3f7ff8fd));
3648       SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3649       SDValue TwoToFractionalPartOfX =
3650         DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3651
3652       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3653                            MVT::f32, TwoToFractionalPartOfX);
3654     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3655       // For floating-point precision of 18:
3656       //
3657       //   TwoToFractionalPartOfX =
3658       //     0.999999982f +
3659       //       (0.693148872f +
3660       //         (0.240227044f +
3661       //           (0.554906021e-1f +
3662       //             (0.961591928e-2f +
3663       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3664       // error 2.47208000*10^(-7), which is better than 18 bits
3665       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3666                                getF32Constant(DAG, 0x3924b03e));
3667       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3668                                getF32Constant(DAG, 0x3ab24b87));
3669       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3670       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3671                                getF32Constant(DAG, 0x3c1d8c17));
3672       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3673       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3674                                getF32Constant(DAG, 0x3d634a1d));
3675       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3676       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3677                                getF32Constant(DAG, 0x3e75fe14));
3678       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3679       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3680                                 getF32Constant(DAG, 0x3f317234));
3681       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3682       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3683                                 getF32Constant(DAG, 0x3f800000));
3684       SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3685       SDValue TwoToFractionalPartOfX =
3686         DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3687
3688       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3689                            MVT::f32, TwoToFractionalPartOfX);
3690     }
3691   } else {
3692     // No special expansion.
3693     result = DAG.getNode(ISD::FEXP2, dl,
3694                          getValue(I.getOperand(1)).getValueType(),
3695                          getValue(I.getOperand(1)));
3696   }
3697
3698   setValue(&I, result);
3699 }
3700
3701 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3702 /// limited-precision mode with x == 10.0f.
3703 void
3704 SelectionDAGLowering::visitPow(CallInst &I) {
3705   SDValue result;
3706   Value *Val = I.getOperand(1);
3707   DebugLoc dl = getCurDebugLoc();
3708   bool IsExp10 = false;
3709
3710   if (getValue(Val).getValueType() == MVT::f32 &&
3711       getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3712       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3713     if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3714       if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3715         APFloat Ten(10.0f);
3716         IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3717       }
3718     }
3719   }
3720
3721   if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3722     SDValue Op = getValue(I.getOperand(2));
3723
3724     // Put the exponent in the right bit position for later addition to the
3725     // final result:
3726     //
3727     //   #define LOG2OF10 3.3219281f
3728     //   IntegerPartOfX = (int32_t)(x * LOG2OF10);
3729     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3730                              getF32Constant(DAG, 0x40549a78));
3731     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3732
3733     //   FractionalPartOfX = x - (float)IntegerPartOfX;
3734     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3735     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3736
3737     //   IntegerPartOfX <<= 23;
3738     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3739                                  DAG.getConstant(23, TLI.getPointerTy()));
3740
3741     if (LimitFloatPrecision <= 6) {
3742       // For floating-point precision of 6:
3743       //
3744       //   twoToFractionalPartOfX =
3745       //     0.997535578f +
3746       //       (0.735607626f + 0.252464424f * x) * x;
3747       //
3748       // error 0.0144103317, which is 6 bits
3749       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3750                                getF32Constant(DAG, 0x3e814304));
3751       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3752                                getF32Constant(DAG, 0x3f3c50c8));
3753       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3754       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3755                                getF32Constant(DAG, 0x3f7f5e7e));
3756       SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3757       SDValue TwoToFractionalPartOfX =
3758         DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3759
3760       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3761                            MVT::f32, TwoToFractionalPartOfX);
3762     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3763       // For floating-point precision of 12:
3764       //
3765       //   TwoToFractionalPartOfX =
3766       //     0.999892986f +
3767       //       (0.696457318f +
3768       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3769       //
3770       // error 0.000107046256, which is 13 to 14 bits
3771       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3772                                getF32Constant(DAG, 0x3da235e3));
3773       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3774                                getF32Constant(DAG, 0x3e65b8f3));
3775       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3776       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3777                                getF32Constant(DAG, 0x3f324b07));
3778       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3779       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3780                                getF32Constant(DAG, 0x3f7ff8fd));
3781       SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3782       SDValue TwoToFractionalPartOfX =
3783         DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3784
3785       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3786                            MVT::f32, TwoToFractionalPartOfX);
3787     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3788       // For floating-point precision of 18:
3789       //
3790       //   TwoToFractionalPartOfX =
3791       //     0.999999982f +
3792       //       (0.693148872f +
3793       //         (0.240227044f +
3794       //           (0.554906021e-1f +
3795       //             (0.961591928e-2f +
3796       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3797       // error 2.47208000*10^(-7), which is better than 18 bits
3798       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3799                                getF32Constant(DAG, 0x3924b03e));
3800       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3801                                getF32Constant(DAG, 0x3ab24b87));
3802       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3803       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3804                                getF32Constant(DAG, 0x3c1d8c17));
3805       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3806       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3807                                getF32Constant(DAG, 0x3d634a1d));
3808       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3809       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3810                                getF32Constant(DAG, 0x3e75fe14));
3811       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3812       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3813                                 getF32Constant(DAG, 0x3f317234));
3814       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3815       SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3816                                 getF32Constant(DAG, 0x3f800000));
3817       SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3818       SDValue TwoToFractionalPartOfX =
3819         DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3820
3821       result = DAG.getNode(ISD::BIT_CONVERT, dl,
3822                            MVT::f32, TwoToFractionalPartOfX);
3823     }
3824   } else {
3825     // No special expansion.
3826     result = DAG.getNode(ISD::FPOW, dl,
3827                          getValue(I.getOperand(1)).getValueType(),
3828                          getValue(I.getOperand(1)),
3829                          getValue(I.getOperand(2)));
3830   }
3831
3832   setValue(&I, result);
3833 }
3834
3835 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
3836 /// we want to emit this as a call to a named external function, return the name
3837 /// otherwise lower it and return null.
3838 const char *
3839 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3840   DebugLoc dl = getCurDebugLoc();
3841   switch (Intrinsic) {
3842   default:
3843     // By default, turn this into a target intrinsic node.
3844     visitTargetIntrinsic(I, Intrinsic);
3845     return 0;
3846   case Intrinsic::vastart:  visitVAStart(I); return 0;
3847   case Intrinsic::vaend:    visitVAEnd(I); return 0;
3848   case Intrinsic::vacopy:   visitVACopy(I); return 0;
3849   case Intrinsic::returnaddress:
3850     setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3851                              getValue(I.getOperand(1))));
3852     return 0;
3853   case Intrinsic::frameaddress:
3854     setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3855                              getValue(I.getOperand(1))));
3856     return 0;
3857   case Intrinsic::setjmp:
3858     return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3859     break;
3860   case Intrinsic::longjmp:
3861     return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3862     break;
3863   case Intrinsic::memcpy: {
3864     SDValue Op1 = getValue(I.getOperand(1));
3865     SDValue Op2 = getValue(I.getOperand(2));
3866     SDValue Op3 = getValue(I.getOperand(3));
3867     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3868     DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3869                               I.getOperand(1), 0, I.getOperand(2), 0));
3870     return 0;
3871   }
3872   case Intrinsic::memset: {
3873     SDValue Op1 = getValue(I.getOperand(1));
3874     SDValue Op2 = getValue(I.getOperand(2));
3875     SDValue Op3 = getValue(I.getOperand(3));
3876     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3877     DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3878                               I.getOperand(1), 0));
3879     return 0;
3880   }
3881   case Intrinsic::memmove: {
3882     SDValue Op1 = getValue(I.getOperand(1));
3883     SDValue Op2 = getValue(I.getOperand(2));
3884     SDValue Op3 = getValue(I.getOperand(3));
3885     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3886
3887     // If the source and destination are known to not be aliases, we can
3888     // lower memmove as memcpy.
3889     uint64_t Size = -1ULL;
3890     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3891       Size = C->getZExtValue();
3892     if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3893         AliasAnalysis::NoAlias) {
3894       DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3895                                 I.getOperand(1), 0, I.getOperand(2), 0));
3896       return 0;
3897     }
3898
3899     DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3900                                I.getOperand(1), 0, I.getOperand(2), 0));
3901     return 0;
3902   }
3903   case Intrinsic::dbg_stoppoint: {
3904     DwarfWriter *DW = DAG.getDwarfWriter();
3905     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3906     if (DW && DW->ValidDebugInfo(SPI.getContext())) {
3907       MachineFunction &MF = DAG.getMachineFunction();
3908       if (Fast)
3909         DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3910                                         SPI.getLine(),
3911                                         SPI.getColumn(),
3912                                         SPI.getContext()));
3913       DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
3914       std::string Dir, FN;
3915       unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
3916                                                  CU.getFilename(FN));
3917       unsigned idx = MF.getOrCreateDebugLocID(SrcFile,
3918                                               SPI.getLine(), SPI.getColumn());
3919       setCurDebugLoc(DebugLoc::get(idx));
3920     }
3921     return 0;
3922   }
3923   case Intrinsic::dbg_region_start: {
3924     DwarfWriter *DW = DAG.getDwarfWriter();
3925     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3926     if (DW && DW->ValidDebugInfo(RSI.getContext())) {
3927       unsigned LabelID =
3928         DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
3929       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3930                                getRoot(), LabelID));
3931     }
3932
3933     return 0;
3934   }
3935   case Intrinsic::dbg_region_end: {
3936     DwarfWriter *DW = DAG.getDwarfWriter();
3937     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3938     if (DW && DW->ValidDebugInfo(REI.getContext())) {
3939       unsigned LabelID =
3940         DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
3941       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3942                                getRoot(), LabelID));
3943     }
3944
3945     return 0;
3946   }
3947   case Intrinsic::dbg_func_start: {
3948     DwarfWriter *DW = DAG.getDwarfWriter();
3949     if (!DW) return 0;
3950     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3951     Value *SP = FSI.getSubprogram();
3952     if (SP && DW->ValidDebugInfo(SP)) {
3953       // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3954       // what (most?) gdb expects.
3955       MachineFunction &MF = DAG.getMachineFunction();
3956       DISubprogram Subprogram(cast<GlobalVariable>(SP));
3957       DICompileUnit CompileUnit = Subprogram.getCompileUnit();
3958       std::string Dir, FN;
3959       unsigned SrcFile = DW->getOrCreateSourceID(CompileUnit.getDirectory(Dir),
3960                                                  CompileUnit.getFilename(FN));
3961
3962       // Record the source line but does not create a label for the normal
3963       // function start. It will be emitted at asm emission time. However,
3964       // create a label if this is a beginning of inlined function.
3965       unsigned Line = Subprogram.getLineNumber();
3966
3967       if (Fast) {
3968         unsigned LabelID = DW->RecordSourceLine(Line, 0, SrcFile);
3969         if (DW->getRecordSourceLineCount() != 1)
3970           DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3971                                    getRoot(), LabelID));
3972       }
3973
3974       setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
3975     }
3976
3977     return 0;
3978   }
3979   case Intrinsic::dbg_declare: {
3980     if (Fast) {
3981       DwarfWriter *DW = DAG.getDwarfWriter();
3982       DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3983       Value *Variable = DI.getVariable();
3984       if (DW && DW->ValidDebugInfo(Variable))
3985         DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
3986                                 getValue(DI.getAddress()), getValue(Variable)));
3987     } else {
3988       // FIXME: Do something sensible here when we support debug declare.
3989     }
3990     return 0;
3991   }
3992   case Intrinsic::eh_exception: {
3993     if (!CurMBB->isLandingPad()) {
3994       // FIXME: Mark exception register as live in.  Hack for PR1508.
3995       unsigned Reg = TLI.getExceptionAddressRegister();
3996       if (Reg) CurMBB->addLiveIn(Reg);
3997     }
3998     // Insert the EXCEPTIONADDR instruction.
3999     SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4000     SDValue Ops[1];
4001     Ops[0] = DAG.getRoot();
4002     SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4003     setValue(&I, Op);
4004     DAG.setRoot(Op.getValue(1));
4005     return 0;
4006   }
4007
4008   case Intrinsic::eh_selector_i32:
4009   case Intrinsic::eh_selector_i64: {
4010     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4011     MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
4012                          MVT::i32 : MVT::i64);
4013
4014     if (MMI) {
4015       if (CurMBB->isLandingPad())
4016         AddCatchInfo(I, MMI, CurMBB);
4017       else {
4018 #ifndef NDEBUG
4019         FuncInfo.CatchInfoLost.insert(&I);
4020 #endif
4021         // FIXME: Mark exception selector register as live in.  Hack for PR1508.
4022         unsigned Reg = TLI.getExceptionSelectorRegister();
4023         if (Reg) CurMBB->addLiveIn(Reg);
4024       }
4025
4026       // Insert the EHSELECTION instruction.
4027       SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4028       SDValue Ops[2];
4029       Ops[0] = getValue(I.getOperand(1));
4030       Ops[1] = getRoot();
4031       SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4032       setValue(&I, Op);
4033       DAG.setRoot(Op.getValue(1));
4034     } else {
4035       setValue(&I, DAG.getConstant(0, VT));
4036     }
4037
4038     return 0;
4039   }
4040
4041   case Intrinsic::eh_typeid_for_i32:
4042   case Intrinsic::eh_typeid_for_i64: {
4043     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4044     MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4045                          MVT::i32 : MVT::i64);
4046
4047     if (MMI) {
4048       // Find the type id for the given typeinfo.
4049       GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4050
4051       unsigned TypeID = MMI->getTypeIDFor(GV);
4052       setValue(&I, DAG.getConstant(TypeID, VT));
4053     } else {
4054       // Return something different to eh_selector.
4055       setValue(&I, DAG.getConstant(1, VT));
4056     }
4057
4058     return 0;
4059   }
4060
4061   case Intrinsic::eh_return_i32:
4062   case Intrinsic::eh_return_i64:
4063     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4064       MMI->setCallsEHReturn(true);
4065       DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4066                               MVT::Other,
4067                               getControlRoot(),
4068                               getValue(I.getOperand(1)),
4069                               getValue(I.getOperand(2))));
4070     } else {
4071       setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4072     }
4073
4074     return 0;
4075   case Intrinsic::eh_unwind_init:
4076     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4077       MMI->setCallsUnwindInit(true);
4078     }
4079
4080     return 0;
4081
4082   case Intrinsic::eh_dwarf_cfa: {
4083     MVT VT = getValue(I.getOperand(1)).getValueType();
4084     SDValue CfaArg;
4085     if (VT.bitsGT(TLI.getPointerTy()))
4086       CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
4087                            TLI.getPointerTy(), getValue(I.getOperand(1)));
4088     else
4089       CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
4090                            TLI.getPointerTy(), getValue(I.getOperand(1)));
4091
4092     SDValue Offset = DAG.getNode(ISD::ADD, dl,
4093                                  TLI.getPointerTy(),
4094                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4095                                              TLI.getPointerTy()),
4096                                  CfaArg);
4097     setValue(&I, DAG.getNode(ISD::ADD, dl,
4098                              TLI.getPointerTy(),
4099                              DAG.getNode(ISD::FRAMEADDR, dl,
4100                                          TLI.getPointerTy(),
4101                                          DAG.getConstant(0,
4102                                                          TLI.getPointerTy())),
4103                              Offset));
4104     return 0;
4105   }
4106
4107   case Intrinsic::convertff:
4108   case Intrinsic::convertfsi:
4109   case Intrinsic::convertfui:
4110   case Intrinsic::convertsif:
4111   case Intrinsic::convertuif:
4112   case Intrinsic::convertss:
4113   case Intrinsic::convertsu:
4114   case Intrinsic::convertus:
4115   case Intrinsic::convertuu: {
4116     ISD::CvtCode Code = ISD::CVT_INVALID;
4117     switch (Intrinsic) {
4118     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
4119     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4120     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4121     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4122     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4123     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
4124     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
4125     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
4126     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
4127     }
4128     MVT DestVT = TLI.getValueType(I.getType());
4129     Value* Op1 = I.getOperand(1);
4130     setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4131                                 DAG.getValueType(DestVT),
4132                                 DAG.getValueType(getValue(Op1).getValueType()),
4133                                 getValue(I.getOperand(2)),
4134                                 getValue(I.getOperand(3)),
4135                                 Code));
4136     return 0;
4137   }
4138
4139   case Intrinsic::sqrt:
4140     setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4141                              getValue(I.getOperand(1)).getValueType(),
4142                              getValue(I.getOperand(1))));
4143     return 0;
4144   case Intrinsic::powi:
4145     setValue(&I, DAG.getNode(ISD::FPOWI, dl,
4146                              getValue(I.getOperand(1)).getValueType(),
4147                              getValue(I.getOperand(1)),
4148                              getValue(I.getOperand(2))));
4149     return 0;
4150   case Intrinsic::sin:
4151     setValue(&I, DAG.getNode(ISD::FSIN, dl,
4152                              getValue(I.getOperand(1)).getValueType(),
4153                              getValue(I.getOperand(1))));
4154     return 0;
4155   case Intrinsic::cos:
4156     setValue(&I, DAG.getNode(ISD::FCOS, dl,
4157                              getValue(I.getOperand(1)).getValueType(),
4158                              getValue(I.getOperand(1))));
4159     return 0;
4160   case Intrinsic::log:
4161     visitLog(I);
4162     return 0;
4163   case Intrinsic::log2:
4164     visitLog2(I);
4165     return 0;
4166   case Intrinsic::log10:
4167     visitLog10(I);
4168     return 0;
4169   case Intrinsic::exp:
4170     visitExp(I);
4171     return 0;
4172   case Intrinsic::exp2:
4173     visitExp2(I);
4174     return 0;
4175   case Intrinsic::pow:
4176     visitPow(I);
4177     return 0;
4178   case Intrinsic::pcmarker: {
4179     SDValue Tmp = getValue(I.getOperand(1));
4180     DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4181     return 0;
4182   }
4183   case Intrinsic::readcyclecounter: {
4184     SDValue Op = getRoot();
4185     SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4186                                 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4187                                 &Op, 1);
4188     setValue(&I, Tmp);
4189     DAG.setRoot(Tmp.getValue(1));
4190     return 0;
4191   }
4192   case Intrinsic::part_select: {
4193     // Currently not implemented: just abort
4194     assert(0 && "part_select intrinsic not implemented");
4195     abort();
4196   }
4197   case Intrinsic::part_set: {
4198     // Currently not implemented: just abort
4199     assert(0 && "part_set intrinsic not implemented");
4200     abort();
4201   }
4202   case Intrinsic::bswap:
4203     setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4204                              getValue(I.getOperand(1)).getValueType(),
4205                              getValue(I.getOperand(1))));
4206     return 0;
4207   case Intrinsic::cttz: {
4208     SDValue Arg = getValue(I.getOperand(1));
4209     MVT Ty = Arg.getValueType();
4210     SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
4211     setValue(&I, result);
4212     return 0;
4213   }
4214   case Intrinsic::ctlz: {
4215     SDValue Arg = getValue(I.getOperand(1));
4216     MVT Ty = Arg.getValueType();
4217     SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
4218     setValue(&I, result);
4219     return 0;
4220   }
4221   case Intrinsic::ctpop: {
4222     SDValue Arg = getValue(I.getOperand(1));
4223     MVT Ty = Arg.getValueType();
4224     SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
4225     setValue(&I, result);
4226     return 0;
4227   }
4228   case Intrinsic::stacksave: {
4229     SDValue Op = getRoot();
4230     SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
4231               DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4232     setValue(&I, Tmp);
4233     DAG.setRoot(Tmp.getValue(1));
4234     return 0;
4235   }
4236   case Intrinsic::stackrestore: {
4237     SDValue Tmp = getValue(I.getOperand(1));
4238     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
4239     return 0;
4240   }
4241   case Intrinsic::stackprotector: {
4242     // Emit code into the DAG to store the stack guard onto the stack.
4243     MachineFunction &MF = DAG.getMachineFunction();
4244     MachineFrameInfo *MFI = MF.getFrameInfo();
4245     MVT PtrTy = TLI.getPointerTy();
4246
4247     SDValue Src = getValue(I.getOperand(1));   // The guard's value.
4248     AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4249
4250     int FI = FuncInfo.StaticAllocaMap[Slot];
4251     MFI->setStackProtectorIndex(FI);
4252
4253     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4254
4255     // Store the stack protector onto the stack.
4256     SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4257                                   PseudoSourceValue::getFixedStack(FI),
4258                                   0, true);
4259     setValue(&I, Result);
4260     DAG.setRoot(Result);
4261     return 0;
4262   }
4263   case Intrinsic::var_annotation:
4264     // Discard annotate attributes
4265     return 0;
4266
4267   case Intrinsic::init_trampoline: {
4268     const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4269
4270     SDValue Ops[6];
4271     Ops[0] = getRoot();
4272     Ops[1] = getValue(I.getOperand(1));
4273     Ops[2] = getValue(I.getOperand(2));
4274     Ops[3] = getValue(I.getOperand(3));
4275     Ops[4] = DAG.getSrcValue(I.getOperand(1));
4276     Ops[5] = DAG.getSrcValue(F);
4277
4278     SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
4279                                 DAG.getNodeValueTypes(TLI.getPointerTy(),
4280                                                       MVT::Other), 2,
4281                                 Ops, 6);
4282
4283     setValue(&I, Tmp);
4284     DAG.setRoot(Tmp.getValue(1));
4285     return 0;
4286   }
4287
4288   case Intrinsic::gcroot:
4289     if (GFI) {
4290       Value *Alloca = I.getOperand(1);
4291       Constant *TypeMap = cast<Constant>(I.getOperand(2));
4292
4293       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4294       GFI->addStackRoot(FI->getIndex(), TypeMap);
4295     }
4296     return 0;
4297
4298   case Intrinsic::gcread:
4299   case Intrinsic::gcwrite:
4300     assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4301     return 0;
4302
4303   case Intrinsic::flt_rounds: {
4304     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4305     return 0;
4306   }
4307
4308   case Intrinsic::trap: {
4309     DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4310     return 0;
4311   }
4312
4313   case Intrinsic::uadd_with_overflow:
4314     return implVisitAluOverflow(I, ISD::UADDO);
4315   case Intrinsic::sadd_with_overflow:
4316     return implVisitAluOverflow(I, ISD::SADDO);
4317   case Intrinsic::usub_with_overflow:
4318     return implVisitAluOverflow(I, ISD::USUBO);
4319   case Intrinsic::ssub_with_overflow:
4320     return implVisitAluOverflow(I, ISD::SSUBO);
4321   case Intrinsic::umul_with_overflow:
4322     return implVisitAluOverflow(I, ISD::UMULO);
4323   case Intrinsic::smul_with_overflow:
4324     return implVisitAluOverflow(I, ISD::SMULO);
4325
4326   case Intrinsic::prefetch: {
4327     SDValue Ops[4];
4328     Ops[0] = getRoot();
4329     Ops[1] = getValue(I.getOperand(1));
4330     Ops[2] = getValue(I.getOperand(2));
4331     Ops[3] = getValue(I.getOperand(3));
4332     DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4333     return 0;
4334   }
4335
4336   case Intrinsic::memory_barrier: {
4337     SDValue Ops[6];
4338     Ops[0] = getRoot();
4339     for (int x = 1; x < 6; ++x)
4340       Ops[x] = getValue(I.getOperand(x));
4341
4342     DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4343     return 0;
4344   }
4345   case Intrinsic::atomic_cmp_swap: {
4346     SDValue Root = getRoot();
4347     SDValue L =
4348       DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4349                     getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4350                     Root,
4351                     getValue(I.getOperand(1)),
4352                     getValue(I.getOperand(2)),
4353                     getValue(I.getOperand(3)),
4354                     I.getOperand(1));
4355     setValue(&I, L);
4356     DAG.setRoot(L.getValue(1));
4357     return 0;
4358   }
4359   case Intrinsic::atomic_load_add:
4360     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4361   case Intrinsic::atomic_load_sub:
4362     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4363   case Intrinsic::atomic_load_or:
4364     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4365   case Intrinsic::atomic_load_xor:
4366     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4367   case Intrinsic::atomic_load_and:
4368     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4369   case Intrinsic::atomic_load_nand:
4370     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4371   case Intrinsic::atomic_load_max:
4372     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4373   case Intrinsic::atomic_load_min:
4374     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4375   case Intrinsic::atomic_load_umin:
4376     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4377   case Intrinsic::atomic_load_umax:
4378     return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4379   case Intrinsic::atomic_swap:
4380     return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4381   }
4382 }
4383
4384
4385 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4386                                        bool IsTailCall,
4387                                        MachineBasicBlock *LandingPad) {
4388   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4389   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4390   MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4391   unsigned BeginLabel = 0, EndLabel = 0;
4392
4393   TargetLowering::ArgListTy Args;
4394   TargetLowering::ArgListEntry Entry;
4395   Args.reserve(CS.arg_size());
4396   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4397        i != e; ++i) {
4398     SDValue ArgNode = getValue(*i);
4399     Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4400
4401     unsigned attrInd = i - CS.arg_begin() + 1;
4402     Entry.isSExt  = CS.paramHasAttr(attrInd, Attribute::SExt);
4403     Entry.isZExt  = CS.paramHasAttr(attrInd, Attribute::ZExt);
4404     Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4405     Entry.isSRet  = CS.paramHasAttr(attrInd, Attribute::StructRet);
4406     Entry.isNest  = CS.paramHasAttr(attrInd, Attribute::Nest);
4407     Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4408     Entry.Alignment = CS.getParamAlignment(attrInd);
4409     Args.push_back(Entry);
4410   }
4411
4412   if (LandingPad && MMI) {
4413     // Insert a label before the invoke call to mark the try range.  This can be
4414     // used to detect deletion of the invoke via the MachineModuleInfo.
4415     BeginLabel = MMI->NextLabelID();
4416     // Both PendingLoads and PendingExports must be flushed here;
4417     // this call might not return.
4418     (void)getRoot();
4419     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4420                              getControlRoot(), BeginLabel));
4421   }
4422
4423   std::pair<SDValue,SDValue> Result =
4424     TLI.LowerCallTo(getRoot(), CS.getType(),
4425                     CS.paramHasAttr(0, Attribute::SExt),
4426                     CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4427                     CS.paramHasAttr(0, Attribute::InReg),
4428                     CS.getCallingConv(),
4429                     IsTailCall && PerformTailCallOpt,
4430                     Callee, Args, DAG, getCurDebugLoc());
4431   if (CS.getType() != Type::VoidTy)
4432     setValue(CS.getInstruction(), Result.first);
4433   DAG.setRoot(Result.second);
4434
4435   if (LandingPad && MMI) {
4436     // Insert a label at the end of the invoke call to mark the try range.  This
4437     // can be used to detect deletion of the invoke via the MachineModuleInfo.
4438     EndLabel = MMI->NextLabelID();
4439     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4440                              getRoot(), EndLabel));
4441
4442     // Inform MachineModuleInfo of range.
4443     MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4444   }
4445 }
4446
4447
4448 void SelectionDAGLowering::visitCall(CallInst &I) {
4449   const char *RenameFn = 0;
4450   if (Function *F = I.getCalledFunction()) {
4451     if (F->isDeclaration()) {
4452       const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4453       if (II) {
4454         if (unsigned IID = II->getIntrinsicID(F)) {
4455           RenameFn = visitIntrinsicCall(I, IID);
4456           if (!RenameFn)
4457             return;
4458         }
4459       }
4460       if (unsigned IID = F->getIntrinsicID()) {
4461         RenameFn = visitIntrinsicCall(I, IID);
4462         if (!RenameFn)
4463           return;
4464       }
4465     }
4466
4467     // Check for well-known libc/libm calls.  If the function is internal, it
4468     // can't be a library call.
4469     unsigned NameLen = F->getNameLen();
4470     if (!F->hasLocalLinkage() && NameLen) {
4471       const char *NameStr = F->getNameStart();
4472       if (NameStr[0] == 'c' &&
4473           ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4474            (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4475         if (I.getNumOperands() == 3 &&   // Basic sanity checks.
4476             I.getOperand(1)->getType()->isFloatingPoint() &&
4477             I.getType() == I.getOperand(1)->getType() &&
4478             I.getType() == I.getOperand(2)->getType()) {
4479           SDValue LHS = getValue(I.getOperand(1));
4480           SDValue RHS = getValue(I.getOperand(2));
4481           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4482                                    LHS.getValueType(), LHS, RHS));
4483           return;
4484         }
4485       } else if (NameStr[0] == 'f' &&
4486                  ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4487                   (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4488                   (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4489         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4490             I.getOperand(1)->getType()->isFloatingPoint() &&
4491             I.getType() == I.getOperand(1)->getType()) {
4492           SDValue Tmp = getValue(I.getOperand(1));
4493           setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4494                                    Tmp.getValueType(), Tmp));
4495           return;
4496         }
4497       } else if (NameStr[0] == 's' &&
4498                  ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4499                   (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4500                   (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4501         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4502             I.getOperand(1)->getType()->isFloatingPoint() &&
4503             I.getType() == I.getOperand(1)->getType()) {
4504           SDValue Tmp = getValue(I.getOperand(1));
4505           setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4506                                    Tmp.getValueType(), Tmp));
4507           return;
4508         }
4509       } else if (NameStr[0] == 'c' &&
4510                  ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4511                   (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4512                   (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4513         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4514             I.getOperand(1)->getType()->isFloatingPoint() &&
4515             I.getType() == I.getOperand(1)->getType()) {
4516           SDValue Tmp = getValue(I.getOperand(1));
4517           setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4518                                    Tmp.getValueType(), Tmp));
4519           return;
4520         }
4521       }
4522     }
4523   } else if (isa<InlineAsm>(I.getOperand(0))) {
4524     visitInlineAsm(&I);
4525     return;
4526   }
4527
4528   SDValue Callee;
4529   if (!RenameFn)
4530     Callee = getValue(I.getOperand(0));
4531   else
4532     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4533
4534   LowerCallTo(&I, Callee, I.isTailCall());
4535 }
4536
4537
4538 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4539 /// this value and returns the result as a ValueVT value.  This uses
4540 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4541 /// If the Flag pointer is NULL, no flag is used.
4542 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4543                                       SDValue &Chain,
4544                                       SDValue *Flag) const {
4545   // Assemble the legal parts into the final values.
4546   SmallVector<SDValue, 4> Values(ValueVTs.size());
4547   SmallVector<SDValue, 8> Parts;
4548   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4549     // Copy the legal parts from the registers.
4550     MVT ValueVT = ValueVTs[Value];
4551     unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4552     MVT RegisterVT = RegVTs[Value];
4553
4554     Parts.resize(NumRegs);
4555     for (unsigned i = 0; i != NumRegs; ++i) {
4556       SDValue P;
4557       if (Flag == 0)
4558         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4559       else {
4560         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4561         *Flag = P.getValue(2);
4562       }
4563       Chain = P.getValue(1);
4564
4565       // If the source register was virtual and if we know something about it,
4566       // add an assert node.
4567       if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4568           RegisterVT.isInteger() && !RegisterVT.isVector()) {
4569         unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4570         FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4571         if (FLI.LiveOutRegInfo.size() > SlotNo) {
4572           FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4573
4574           unsigned RegSize = RegisterVT.getSizeInBits();
4575           unsigned NumSignBits = LOI.NumSignBits;
4576           unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4577
4578           // FIXME: We capture more information than the dag can represent.  For
4579           // now, just use the tightest assertzext/assertsext possible.
4580           bool isSExt = true;
4581           MVT FromVT(MVT::Other);
4582           if (NumSignBits == RegSize)
4583             isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
4584           else if (NumZeroBits >= RegSize-1)
4585             isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
4586           else if (NumSignBits > RegSize-8)
4587             isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
4588           else if (NumZeroBits >= RegSize-8)
4589             isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
4590           else if (NumSignBits > RegSize-16)
4591             isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
4592           else if (NumZeroBits >= RegSize-16)
4593             isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4594           else if (NumSignBits > RegSize-32)
4595             isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
4596           else if (NumZeroBits >= RegSize-32)
4597             isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4598
4599           if (FromVT != MVT::Other) {
4600             P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4601                             RegisterVT, P, DAG.getValueType(FromVT));
4602
4603           }
4604         }
4605       }
4606
4607       Parts[i] = P;
4608     }
4609
4610     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4611                                      NumRegs, RegisterVT, ValueVT);
4612     Part += NumRegs;
4613     Parts.clear();
4614   }
4615
4616   return DAG.getNode(ISD::MERGE_VALUES, dl,
4617                      DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4618                      &Values[0], ValueVTs.size());
4619 }
4620
4621 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4622 /// specified value into the registers specified by this object.  This uses
4623 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4624 /// If the Flag pointer is NULL, no flag is used.
4625 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4626                                  SDValue &Chain, SDValue *Flag) const {
4627   // Get the list of the values's legal parts.
4628   unsigned NumRegs = Regs.size();
4629   SmallVector<SDValue, 8> Parts(NumRegs);
4630   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4631     MVT ValueVT = ValueVTs[Value];
4632     unsigned NumParts = TLI->getNumRegisters(ValueVT);
4633     MVT RegisterVT = RegVTs[Value];
4634
4635     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
4636                    &Parts[Part], NumParts, RegisterVT);
4637     Part += NumParts;
4638   }
4639
4640   // Copy the parts into the registers.
4641   SmallVector<SDValue, 8> Chains(NumRegs);
4642   for (unsigned i = 0; i != NumRegs; ++i) {
4643     SDValue Part;
4644     if (Flag == 0)
4645       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4646     else {
4647       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4648       *Flag = Part.getValue(1);
4649     }
4650     Chains[i] = Part.getValue(0);
4651   }
4652
4653   if (NumRegs == 1 || Flag)
4654     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4655     // flagged to it. That is the CopyToReg nodes and the user are considered
4656     // a single scheduling unit. If we create a TokenFactor and return it as
4657     // chain, then the TokenFactor is both a predecessor (operand) of the
4658     // user as well as a successor (the TF operands are flagged to the user).
4659     // c1, f1 = CopyToReg
4660     // c2, f2 = CopyToReg
4661     // c3     = TokenFactor c1, c2
4662     // ...
4663     //        = op c3, ..., f2
4664     Chain = Chains[NumRegs-1];
4665   else
4666     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4667 }
4668
4669 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4670 /// operand list.  This adds the code marker and includes the number of
4671 /// values added into it.
4672 void RegsForValue::AddInlineAsmOperands(unsigned Code,
4673                                         bool HasMatching,unsigned MatchingIdx,
4674                                         SelectionDAG &DAG,
4675                                         std::vector<SDValue> &Ops) const {
4676   MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4677   assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4678   unsigned Flag = Code | (Regs.size() << 3);
4679   if (HasMatching)
4680     Flag |= 0x80000000 | (MatchingIdx << 16);
4681   Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
4682   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4683     unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4684     MVT RegisterVT = RegVTs[Value];
4685     for (unsigned i = 0; i != NumRegs; ++i) {
4686       assert(Reg < Regs.size() && "Mismatch in # registers expected");
4687       Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4688     }
4689   }
4690 }
4691
4692 /// isAllocatableRegister - If the specified register is safe to allocate,
4693 /// i.e. it isn't a stack pointer or some other special register, return the
4694 /// register class for the register.  Otherwise, return null.
4695 static const TargetRegisterClass *
4696 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4697                       const TargetLowering &TLI,
4698                       const TargetRegisterInfo *TRI) {
4699   MVT FoundVT = MVT::Other;
4700   const TargetRegisterClass *FoundRC = 0;
4701   for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4702        E = TRI->regclass_end(); RCI != E; ++RCI) {
4703     MVT ThisVT = MVT::Other;
4704
4705     const TargetRegisterClass *RC = *RCI;
4706     // If none of the the value types for this register class are valid, we
4707     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
4708     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4709          I != E; ++I) {
4710       if (TLI.isTypeLegal(*I)) {
4711         // If we have already found this register in a different register class,
4712         // choose the one with the largest VT specified.  For example, on
4713         // PowerPC, we favor f64 register classes over f32.
4714         if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4715           ThisVT = *I;
4716           break;
4717         }
4718       }
4719     }
4720
4721     if (ThisVT == MVT::Other) continue;
4722
4723     // NOTE: This isn't ideal.  In particular, this might allocate the
4724     // frame pointer in functions that need it (due to them not being taken
4725     // out of allocation, because a variable sized allocation hasn't been seen
4726     // yet).  This is a slight code pessimization, but should still work.
4727     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4728          E = RC->allocation_order_end(MF); I != E; ++I)
4729       if (*I == Reg) {
4730         // We found a matching register class.  Keep looking at others in case
4731         // we find one with larger registers that this physreg is also in.
4732         FoundRC = RC;
4733         FoundVT = ThisVT;
4734         break;
4735       }
4736   }
4737   return FoundRC;
4738 }
4739
4740
4741 namespace llvm {
4742 /// AsmOperandInfo - This contains information for each constraint that we are
4743 /// lowering.
4744 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4745     public TargetLowering::AsmOperandInfo {
4746 public:
4747   /// CallOperand - If this is the result output operand or a clobber
4748   /// this is null, otherwise it is the incoming operand to the CallInst.
4749   /// This gets modified as the asm is processed.
4750   SDValue CallOperand;
4751
4752   /// AssignedRegs - If this is a register or register class operand, this
4753   /// contains the set of register corresponding to the operand.
4754   RegsForValue AssignedRegs;
4755
4756   explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4757     : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4758   }
4759
4760   /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4761   /// busy in OutputRegs/InputRegs.
4762   void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4763                          std::set<unsigned> &OutputRegs,
4764                          std::set<unsigned> &InputRegs,
4765                          const TargetRegisterInfo &TRI) const {
4766     if (isOutReg) {
4767       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4768         MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4769     }
4770     if (isInReg) {
4771       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4772         MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4773     }
4774   }
4775
4776   /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4777   /// corresponds to.  If there is no Value* for this operand, it returns
4778   /// MVT::Other.
4779   MVT getCallOperandValMVT(const TargetLowering &TLI,
4780                            const TargetData *TD) const {
4781     if (CallOperandVal == 0) return MVT::Other;
4782
4783     if (isa<BasicBlock>(CallOperandVal))
4784       return TLI.getPointerTy();
4785
4786     const llvm::Type *OpTy = CallOperandVal->getType();
4787
4788     // If this is an indirect operand, the operand is a pointer to the
4789     // accessed type.
4790     if (isIndirect)
4791       OpTy = cast<PointerType>(OpTy)->getElementType();
4792
4793     // If OpTy is not a single value, it may be a struct/union that we
4794     // can tile with integers.
4795     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4796       unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4797       switch (BitSize) {
4798       default: break;
4799       case 1:
4800       case 8:
4801       case 16:
4802       case 32:
4803       case 64:
4804       case 128:
4805         OpTy = IntegerType::get(BitSize);
4806         break;
4807       }
4808     }
4809
4810     return TLI.getValueType(OpTy, true);
4811   }
4812
4813 private:
4814   /// MarkRegAndAliases - Mark the specified register and all aliases in the
4815   /// specified set.
4816   static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4817                                 const TargetRegisterInfo &TRI) {
4818     assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4819     Regs.insert(Reg);
4820     if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4821       for (; *Aliases; ++Aliases)
4822         Regs.insert(*Aliases);
4823   }
4824 };
4825 } // end llvm namespace.
4826
4827
4828 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4829 /// specified operand.  We prefer to assign virtual registers, to allow the
4830 /// register allocator handle the assignment process.  However, if the asm uses
4831 /// features that we can't model on machineinstrs, we have SDISel do the
4832 /// allocation.  This produces generally horrible, but correct, code.
4833 ///
4834 ///   OpInfo describes the operand.
4835 ///   Input and OutputRegs are the set of already allocated physical registers.
4836 ///
4837 void SelectionDAGLowering::
4838 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4839                      std::set<unsigned> &OutputRegs,
4840                      std::set<unsigned> &InputRegs) {
4841   // Compute whether this value requires an input register, an output register,
4842   // or both.
4843   bool isOutReg = false;
4844   bool isInReg = false;
4845   switch (OpInfo.Type) {
4846   case InlineAsm::isOutput:
4847     isOutReg = true;
4848
4849     // If there is an input constraint that matches this, we need to reserve
4850     // the input register so no other inputs allocate to it.
4851     isInReg = OpInfo.hasMatchingInput();
4852     break;
4853   case InlineAsm::isInput:
4854     isInReg = true;
4855     isOutReg = false;
4856     break;
4857   case InlineAsm::isClobber:
4858     isOutReg = true;
4859     isInReg = true;
4860     break;
4861   }
4862
4863
4864   MachineFunction &MF = DAG.getMachineFunction();
4865   SmallVector<unsigned, 4> Regs;
4866
4867   // If this is a constraint for a single physreg, or a constraint for a
4868   // register class, find it.
4869   std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4870     TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4871                                      OpInfo.ConstraintVT);
4872
4873   unsigned NumRegs = 1;
4874   if (OpInfo.ConstraintVT != MVT::Other) {
4875     // If this is a FP input in an integer register (or visa versa) insert a bit
4876     // cast of the input value.  More generally, handle any case where the input
4877     // value disagrees with the register class we plan to stick this in.
4878     if (OpInfo.Type == InlineAsm::isInput &&
4879         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4880       // Try to convert to the first MVT that the reg class contains.  If the
4881       // types are identical size, use a bitcast to convert (e.g. two differing
4882       // vector types).
4883       MVT RegVT = *PhysReg.second->vt_begin();
4884       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4885         OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4886                                          RegVT, OpInfo.CallOperand);
4887         OpInfo.ConstraintVT = RegVT;
4888       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4889         // If the input is a FP value and we want it in FP registers, do a
4890         // bitcast to the corresponding integer type.  This turns an f64 value
4891         // into i64, which can be passed with two i32 values on a 32-bit
4892         // machine.
4893         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4894         OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4895                                          RegVT, OpInfo.CallOperand);
4896         OpInfo.ConstraintVT = RegVT;
4897       }
4898     }
4899
4900     NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4901   }
4902
4903   MVT RegVT;
4904   MVT ValueVT = OpInfo.ConstraintVT;
4905
4906   // If this is a constraint for a specific physical register, like {r17},
4907   // assign it now.
4908   if (unsigned AssignedReg = PhysReg.first) {
4909     const TargetRegisterClass *RC = PhysReg.second;
4910     if (OpInfo.ConstraintVT == MVT::Other)
4911       ValueVT = *RC->vt_begin();
4912
4913     // Get the actual register value type.  This is important, because the user
4914     // may have asked for (e.g.) the AX register in i32 type.  We need to
4915     // remember that AX is actually i16 to get the right extension.
4916     RegVT = *RC->vt_begin();
4917
4918     // This is a explicit reference to a physical register.
4919     Regs.push_back(AssignedReg);
4920
4921     // If this is an expanded reference, add the rest of the regs to Regs.
4922     if (NumRegs != 1) {
4923       TargetRegisterClass::iterator I = RC->begin();
4924       for (; *I != AssignedReg; ++I)
4925         assert(I != RC->end() && "Didn't find reg!");
4926
4927       // Already added the first reg.
4928       --NumRegs; ++I;
4929       for (; NumRegs; --NumRegs, ++I) {
4930         assert(I != RC->end() && "Ran out of registers to allocate!");
4931         Regs.push_back(*I);
4932       }
4933     }
4934     OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4935     const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4936     OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4937     return;
4938   }
4939
4940   // Otherwise, if this was a reference to an LLVM register class, create vregs
4941   // for this reference.
4942   if (const TargetRegisterClass *RC = PhysReg.second) {
4943     RegVT = *RC->vt_begin();
4944     if (OpInfo.ConstraintVT == MVT::Other)
4945       ValueVT = RegVT;
4946
4947     // Create the appropriate number of virtual registers.
4948     MachineRegisterInfo &RegInfo = MF.getRegInfo();
4949     for (; NumRegs; --NumRegs)
4950       Regs.push_back(RegInfo.createVirtualRegister(RC));
4951
4952     OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4953     return;
4954   }
4955   
4956   // This is a reference to a register class that doesn't directly correspond
4957   // to an LLVM register class.  Allocate NumRegs consecutive, available,
4958   // registers from the class.
4959   std::vector<unsigned> RegClassRegs
4960     = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4961                                             OpInfo.ConstraintVT);
4962
4963   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4964   unsigned NumAllocated = 0;
4965   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4966     unsigned Reg = RegClassRegs[i];
4967     // See if this register is available.
4968     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
4969         (isInReg  && InputRegs.count(Reg))) {    // Already used.
4970       // Make sure we find consecutive registers.
4971       NumAllocated = 0;
4972       continue;
4973     }
4974
4975     // Check to see if this register is allocatable (i.e. don't give out the
4976     // stack pointer).
4977     const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4978     if (!RC) {        // Couldn't allocate this register.
4979       // Reset NumAllocated to make sure we return consecutive registers.
4980       NumAllocated = 0;
4981       continue;
4982     }
4983
4984     // Okay, this register is good, we can use it.
4985     ++NumAllocated;
4986
4987     // If we allocated enough consecutive registers, succeed.
4988     if (NumAllocated == NumRegs) {
4989       unsigned RegStart = (i-NumAllocated)+1;
4990       unsigned RegEnd   = i+1;
4991       // Mark all of the allocated registers used.
4992       for (unsigned i = RegStart; i != RegEnd; ++i)
4993         Regs.push_back(RegClassRegs[i]);
4994
4995       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4996                                          OpInfo.ConstraintVT);
4997       OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4998       return;
4999     }
5000   }
5001
5002   // Otherwise, we couldn't allocate enough registers for this.
5003 }
5004
5005 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5006 /// processed uses a memory 'm' constraint.
5007 static bool
5008 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5009                           const TargetLowering &TLI) {
5010   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5011     InlineAsm::ConstraintInfo &CI = CInfos[i];
5012     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5013       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5014       if (CType == TargetLowering::C_Memory)
5015         return true;
5016     }
5017   }
5018
5019   return false;
5020 }
5021
5022 /// visitInlineAsm - Handle a call to an InlineAsm object.
5023 ///
5024 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5025   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5026
5027   /// ConstraintOperands - Information about all of the constraints.
5028   std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5029
5030   SDValue Chain = getRoot();
5031   SDValue Flag;
5032
5033   std::set<unsigned> OutputRegs, InputRegs;
5034
5035   // Do a prepass over the constraints, canonicalizing them, and building up the
5036   // ConstraintOperands list.
5037   std::vector<InlineAsm::ConstraintInfo>
5038     ConstraintInfos = IA->ParseConstraints();
5039
5040   bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5041
5042   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
5043   unsigned ResNo = 0;   // ResNo - The result number of the next output.
5044   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5045     ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5046     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5047
5048     MVT OpVT = MVT::Other;
5049
5050     // Compute the value type for each operand.
5051     switch (OpInfo.Type) {
5052     case InlineAsm::isOutput:
5053       // Indirect outputs just consume an argument.
5054       if (OpInfo.isIndirect) {
5055         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5056         break;
5057       }
5058
5059       // The return value of the call is this value.  As such, there is no
5060       // corresponding argument.
5061       assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5062       if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5063         OpVT = TLI.getValueType(STy->getElementType(ResNo));
5064       } else {
5065         assert(ResNo == 0 && "Asm only has one result!");
5066         OpVT = TLI.getValueType(CS.getType());
5067       }
5068       ++ResNo;
5069       break;
5070     case InlineAsm::isInput:
5071       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5072       break;
5073     case InlineAsm::isClobber:
5074       // Nothing to do.
5075       break;
5076     }
5077
5078     // If this is an input or an indirect output, process the call argument.
5079     // BasicBlocks are labels, currently appearing only in asm's.
5080     if (OpInfo.CallOperandVal) {
5081       if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5082         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5083       } else {
5084         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5085       }
5086
5087       OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
5088     }
5089
5090     OpInfo.ConstraintVT = OpVT;
5091   }
5092
5093   // Second pass over the constraints: compute which constraint option to use
5094   // and assign registers to constraints that want a specific physreg.
5095   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5096     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5097
5098     // If this is an output operand with a matching input operand, look up the
5099     // matching input. If their types mismatch, e.g. one is an integer, the
5100     // other is floating point, or their sizes are different, flag it as an
5101     // error.
5102     if (OpInfo.hasMatchingInput()) {
5103       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5104       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5105         if ((OpInfo.ConstraintVT.isInteger() !=
5106              Input.ConstraintVT.isInteger()) ||
5107             (OpInfo.ConstraintVT.getSizeInBits() !=
5108              Input.ConstraintVT.getSizeInBits())) {
5109           cerr << "Unsupported asm: input constraint with a matching output "
5110                << "constraint of incompatible type!\n";
5111           exit(1);
5112         }
5113         Input.ConstraintVT = OpInfo.ConstraintVT;
5114       }
5115     }
5116
5117     // Compute the constraint code and ConstraintType to use.
5118     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5119
5120     // If this is a memory input, and if the operand is not indirect, do what we
5121     // need to to provide an address for the memory input.
5122     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5123         !OpInfo.isIndirect) {
5124       assert(OpInfo.Type == InlineAsm::isInput &&
5125              "Can only indirectify direct input operands!");
5126
5127       // Memory operands really want the address of the value.  If we don't have
5128       // an indirect input, put it in the constpool if we can, otherwise spill
5129       // it to a stack slot.
5130
5131       // If the operand is a float, integer, or vector constant, spill to a
5132       // constant pool entry to get its address.
5133       Value *OpVal = OpInfo.CallOperandVal;
5134       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5135           isa<ConstantVector>(OpVal)) {
5136         OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5137                                                  TLI.getPointerTy());
5138       } else {
5139         // Otherwise, create a stack slot and emit a store to it before the
5140         // asm.
5141         const Type *Ty = OpVal->getType();
5142         uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
5143         unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5144         MachineFunction &MF = DAG.getMachineFunction();
5145         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5146         SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5147         Chain = DAG.getStore(Chain, getCurDebugLoc(),
5148                              OpInfo.CallOperand, StackSlot, NULL, 0);
5149         OpInfo.CallOperand = StackSlot;
5150       }
5151
5152       // There is no longer a Value* corresponding to this operand.
5153       OpInfo.CallOperandVal = 0;
5154       // It is now an indirect operand.
5155       OpInfo.isIndirect = true;
5156     }
5157
5158     // If this constraint is for a specific register, allocate it before
5159     // anything else.
5160     if (OpInfo.ConstraintType == TargetLowering::C_Register)
5161       GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5162   }
5163   ConstraintInfos.clear();
5164
5165
5166   // Second pass - Loop over all of the operands, assigning virtual or physregs
5167   // to register class operands.
5168   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5169     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5170
5171     // C_Register operands have already been allocated, Other/Memory don't need
5172     // to be.
5173     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5174       GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5175   }
5176
5177   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5178   std::vector<SDValue> AsmNodeOperands;
5179   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
5180   AsmNodeOperands.push_back(
5181           DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
5182
5183
5184   // Loop over all of the inputs, copying the operand values into the
5185   // appropriate registers and processing the output regs.
5186   RegsForValue RetValRegs;
5187
5188   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5189   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5190
5191   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5192     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5193
5194     switch (OpInfo.Type) {
5195     case InlineAsm::isOutput: {
5196       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5197           OpInfo.ConstraintType != TargetLowering::C_Register) {
5198         // Memory output, or 'other' output (e.g. 'X' constraint).
5199         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5200
5201         // Add information to the INLINEASM node to know about this output.
5202         unsigned ResOpType = 4/*MEM*/ | (1<<3);
5203         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5204                                                         TLI.getPointerTy()));
5205         AsmNodeOperands.push_back(OpInfo.CallOperand);
5206         break;
5207       }
5208
5209       // Otherwise, this is a register or register class output.
5210
5211       // Copy the output from the appropriate register.  Find a register that
5212       // we can use.
5213       if (OpInfo.AssignedRegs.Regs.empty()) {
5214         cerr << "Couldn't allocate output reg for constraint '"
5215              << OpInfo.ConstraintCode << "'!\n";
5216         exit(1);
5217       }
5218
5219       // If this is an indirect operand, store through the pointer after the
5220       // asm.
5221       if (OpInfo.isIndirect) {
5222         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5223                                                       OpInfo.CallOperandVal));
5224       } else {
5225         // This is the result value of the call.
5226         assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5227         // Concatenate this output onto the outputs list.
5228         RetValRegs.append(OpInfo.AssignedRegs);
5229       }
5230
5231       // Add information to the INLINEASM node to know that this register is
5232       // set.
5233       OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5234                                                6 /* EARLYCLOBBER REGDEF */ :
5235                                                2 /* REGDEF */ ,
5236                                                false,
5237                                                0,
5238                                                DAG, AsmNodeOperands);
5239       break;
5240     }
5241     case InlineAsm::isInput: {
5242       SDValue InOperandVal = OpInfo.CallOperand;
5243
5244       if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
5245         // If this is required to match an output register we have already set,
5246         // just use its register.
5247         unsigned OperandNo = OpInfo.getMatchedOperand();
5248
5249         // Scan until we find the definition we already emitted of this operand.
5250         // When we find it, create a RegsForValue operand.
5251         unsigned CurOp = 2;  // The first operand.
5252         for (; OperandNo; --OperandNo) {
5253           // Advance to the next operand.
5254           unsigned OpFlag =
5255             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5256           assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5257                   (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5258                   (OpFlag & 7) == 4 /*MEM*/) &&
5259                  "Skipped past definitions?");
5260           CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5261         }
5262
5263         unsigned OpFlag =
5264           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5265         if ((OpFlag & 7) == 2 /*REGDEF*/
5266             || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5267           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5268           RegsForValue MatchedRegs;
5269           MatchedRegs.TLI = &TLI;
5270           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5271           MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5272           MatchedRegs.RegVTs.push_back(RegVT);
5273           MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5274           for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5275                i != e; ++i)
5276             MatchedRegs.Regs.
5277               push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5278
5279           // Use the produced MatchedRegs object to
5280           MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5281                                     Chain, &Flag);
5282           MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5283                                            true, OpInfo.getMatchedOperand(),
5284                                            DAG, AsmNodeOperands);
5285           break;
5286         } else {
5287           assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5288           assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5289                  "Unexpected number of operands");
5290           // Add information to the INLINEASM node to know about this input.
5291           // See InlineAsm.h isUseOperandTiedToDef.
5292           OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5293           AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5294                                                           TLI.getPointerTy()));
5295           AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5296           break;
5297         }
5298       }
5299
5300       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5301         assert(!OpInfo.isIndirect &&
5302                "Don't know how to handle indirect other inputs yet!");
5303
5304         std::vector<SDValue> Ops;
5305         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5306                                          hasMemory, Ops, DAG);
5307         if (Ops.empty()) {
5308           cerr << "Invalid operand for inline asm constraint '"
5309                << OpInfo.ConstraintCode << "'!\n";
5310           exit(1);
5311         }
5312
5313         // Add information to the INLINEASM node to know about this input.
5314         unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5315         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5316                                                         TLI.getPointerTy()));
5317         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5318         break;
5319       } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5320         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5321         assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5322                "Memory operands expect pointer values");
5323
5324         // Add information to the INLINEASM node to know about this input.
5325         unsigned ResOpType = 4/*MEM*/ | (1<<3);
5326         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5327                                                         TLI.getPointerTy()));
5328         AsmNodeOperands.push_back(InOperandVal);
5329         break;
5330       }
5331
5332       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5333               OpInfo.ConstraintType == TargetLowering::C_Register) &&
5334              "Unknown constraint type!");
5335       assert(!OpInfo.isIndirect &&
5336              "Don't know how to handle indirect register inputs yet!");
5337
5338       // Copy the input into the appropriate registers.
5339       if (OpInfo.AssignedRegs.Regs.empty()) {
5340         cerr << "Couldn't allocate output reg for constraint '"
5341              << OpInfo.ConstraintCode << "'!\n";
5342         exit(1);
5343       }
5344
5345       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5346                                         Chain, &Flag);
5347
5348       OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
5349                                                DAG, AsmNodeOperands);
5350       break;
5351     }
5352     case InlineAsm::isClobber: {
5353       // Add the clobbered value to the operand list, so that the register
5354       // allocator is aware that the physreg got clobbered.
5355       if (!OpInfo.AssignedRegs.Regs.empty())
5356         OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5357                                                  false, 0, DAG,AsmNodeOperands);
5358       break;
5359     }
5360     }
5361   }
5362
5363   // Finish up input operands.
5364   AsmNodeOperands[0] = Chain;
5365   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5366
5367   Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5368                       DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5369                       &AsmNodeOperands[0], AsmNodeOperands.size());
5370   Flag = Chain.getValue(1);
5371
5372   // If this asm returns a register value, copy the result from that register
5373   // and set it as the value of the call.
5374   if (!RetValRegs.Regs.empty()) {
5375     SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5376                                              Chain, &Flag);
5377
5378     // FIXME: Why don't we do this for inline asms with MRVs?
5379     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5380       MVT ResultType = TLI.getValueType(CS.getType());
5381
5382       // If any of the results of the inline asm is a vector, it may have the
5383       // wrong width/num elts.  This can happen for register classes that can
5384       // contain multiple different value types.  The preg or vreg allocated may
5385       // not have the same VT as was expected.  Convert it to the right type
5386       // with bit_convert.
5387       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5388         Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5389                           ResultType, Val);
5390
5391       } else if (ResultType != Val.getValueType() &&
5392                  ResultType.isInteger() && Val.getValueType().isInteger()) {
5393         // If a result value was tied to an input value, the computed result may
5394         // have a wider width than the expected result.  Extract the relevant
5395         // portion.
5396         Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5397       }
5398
5399       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5400     }
5401
5402     setValue(CS.getInstruction(), Val);
5403   }
5404
5405   std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5406
5407   // Process indirect outputs, first output all of the flagged copies out of
5408   // physregs.
5409   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5410     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5411     Value *Ptr = IndirectStoresToEmit[i].second;
5412     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5413                                              Chain, &Flag);
5414     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5415   }
5416
5417   // Emit the non-flagged stores from the physregs.
5418   SmallVector<SDValue, 8> OutChains;
5419   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5420     OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
5421                                     StoresToEmit[i].first,
5422                                     getValue(StoresToEmit[i].second),
5423                                     StoresToEmit[i].second, 0));
5424   if (!OutChains.empty())
5425     Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5426                         &OutChains[0], OutChains.size());
5427   DAG.setRoot(Chain);
5428 }
5429
5430
5431 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5432   SDValue Src = getValue(I.getOperand(0));
5433
5434   // Scale up by the type size in the original i32 type width.  Various
5435   // mid-level optimizers may make assumptions about demanded bits etc from the
5436   // i32-ness of the optimizer: we do not want to promote to i64 and then
5437   // multiply on 64-bit targets.
5438   // FIXME: Malloc inst should go away: PR715.
5439   uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
5440   if (ElementSize != 1)
5441     Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5442                       Src, DAG.getConstant(ElementSize, Src.getValueType()));
5443   
5444   MVT IntPtr = TLI.getPointerTy();
5445
5446   if (IntPtr.bitsLT(Src.getValueType()))
5447     Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
5448   else if (IntPtr.bitsGT(Src.getValueType()))
5449     Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
5450
5451   TargetLowering::ArgListTy Args;
5452   TargetLowering::ArgListEntry Entry;
5453   Entry.Node = Src;
5454   Entry.Ty = TLI.getTargetData()->getIntPtrType();
5455   Args.push_back(Entry);
5456
5457   std::pair<SDValue,SDValue> Result =
5458     TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5459                     CallingConv::C, PerformTailCallOpt,
5460                     DAG.getExternalSymbol("malloc", IntPtr),
5461                     Args, DAG, getCurDebugLoc());
5462   setValue(&I, Result.first);  // Pointers always fit in registers
5463   DAG.setRoot(Result.second);
5464 }
5465
5466 void SelectionDAGLowering::visitFree(FreeInst &I) {
5467   TargetLowering::ArgListTy Args;
5468   TargetLowering::ArgListEntry Entry;
5469   Entry.Node = getValue(I.getOperand(0));
5470   Entry.Ty = TLI.getTargetData()->getIntPtrType();
5471   Args.push_back(Entry);
5472   MVT IntPtr = TLI.getPointerTy();
5473   std::pair<SDValue,SDValue> Result =
5474     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5475                     CallingConv::C, PerformTailCallOpt,
5476                     DAG.getExternalSymbol("free", IntPtr), Args, DAG,
5477                     getCurDebugLoc());
5478   DAG.setRoot(Result.second);
5479 }
5480
5481 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5482   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5483                           MVT::Other, getRoot(),
5484                           getValue(I.getOperand(1)),
5485                           DAG.getSrcValue(I.getOperand(1))));
5486 }
5487
5488 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5489   SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5490                            getRoot(), getValue(I.getOperand(0)),
5491                            DAG.getSrcValue(I.getOperand(0)));
5492   setValue(&I, V);
5493   DAG.setRoot(V.getValue(1));
5494 }
5495
5496 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5497   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5498                           MVT::Other, getRoot(),
5499                           getValue(I.getOperand(1)),
5500                           DAG.getSrcValue(I.getOperand(1))));
5501 }
5502
5503 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5504   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5505                           MVT::Other, getRoot(),
5506                           getValue(I.getOperand(1)),
5507                           getValue(I.getOperand(2)),
5508                           DAG.getSrcValue(I.getOperand(1)),
5509                           DAG.getSrcValue(I.getOperand(2))));
5510 }
5511
5512 /// TargetLowering::LowerArguments - This is the default LowerArguments
5513 /// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
5514 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5515 /// integrated into SDISel.
5516 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5517                                     SmallVectorImpl<SDValue> &ArgValues,
5518                                     DebugLoc dl) {
5519   // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5520   SmallVector<SDValue, 3+16> Ops;
5521   Ops.push_back(DAG.getRoot());
5522   Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5523   Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5524
5525   // Add one result value for each formal argument.
5526   SmallVector<MVT, 16> RetVals;
5527   unsigned j = 1;
5528   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5529        I != E; ++I, ++j) {
5530     SmallVector<MVT, 4> ValueVTs;
5531     ComputeValueVTs(*this, I->getType(), ValueVTs);
5532     for (unsigned Value = 0, NumValues = ValueVTs.size();
5533          Value != NumValues; ++Value) {
5534       MVT VT = ValueVTs[Value];
5535       const Type *ArgTy = VT.getTypeForMVT();
5536       ISD::ArgFlagsTy Flags;
5537       unsigned OriginalAlignment =
5538         getTargetData()->getABITypeAlignment(ArgTy);
5539
5540       if (F.paramHasAttr(j, Attribute::ZExt))
5541         Flags.setZExt();
5542       if (F.paramHasAttr(j, Attribute::SExt))
5543         Flags.setSExt();
5544       if (F.paramHasAttr(j, Attribute::InReg))
5545         Flags.setInReg();
5546       if (F.paramHasAttr(j, Attribute::StructRet))
5547         Flags.setSRet();
5548       if (F.paramHasAttr(j, Attribute::ByVal)) {
5549         Flags.setByVal();
5550         const PointerType *Ty = cast<PointerType>(I->getType());
5551         const Type *ElementTy = Ty->getElementType();
5552         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5553         unsigned FrameSize  = getTargetData()->getTypePaddedSize(ElementTy);
5554         // For ByVal, alignment should be passed from FE.  BE will guess if
5555         // this info is not there but there are cases it cannot get right.
5556         if (F.getParamAlignment(j))
5557           FrameAlign = F.getParamAlignment(j);
5558         Flags.setByValAlign(FrameAlign);
5559         Flags.setByValSize(FrameSize);
5560       }
5561       if (F.paramHasAttr(j, Attribute::Nest))
5562         Flags.setNest();
5563       Flags.setOrigAlign(OriginalAlignment);
5564
5565       MVT RegisterVT = getRegisterType(VT);
5566       unsigned NumRegs = getNumRegisters(VT);
5567       for (unsigned i = 0; i != NumRegs; ++i) {
5568         RetVals.push_back(RegisterVT);
5569         ISD::ArgFlagsTy MyFlags = Flags;
5570         if (NumRegs > 1 && i == 0)
5571           MyFlags.setSplit();
5572         // if it isn't first piece, alignment must be 1
5573         else if (i > 0)
5574           MyFlags.setOrigAlign(1);
5575         Ops.push_back(DAG.getArgFlags(MyFlags));
5576       }
5577     }
5578   }
5579
5580   RetVals.push_back(MVT::Other);
5581
5582   // Create the node.
5583   SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
5584                                DAG.getVTList(&RetVals[0], RetVals.size()),
5585                                &Ops[0], Ops.size()).getNode();
5586
5587   // Prelower FORMAL_ARGUMENTS.  This isn't required for functionality, but
5588   // allows exposing the loads that may be part of the argument access to the
5589   // first DAGCombiner pass.
5590   SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5591
5592   // The number of results should match up, except that the lowered one may have
5593   // an extra flag result.
5594   assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5595           (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5596            TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5597          && "Lowering produced unexpected number of results!");
5598
5599   // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5600   if (Result != TmpRes.getNode() && Result->use_empty()) {
5601     HandleSDNode Dummy(DAG.getRoot());
5602     DAG.RemoveDeadNode(Result);
5603   }
5604
5605   Result = TmpRes.getNode();
5606
5607   unsigned NumArgRegs = Result->getNumValues() - 1;
5608   DAG.setRoot(SDValue(Result, NumArgRegs));
5609
5610   // Set up the return result vector.
5611   unsigned i = 0;
5612   unsigned Idx = 1;
5613   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5614       ++I, ++Idx) {
5615     SmallVector<MVT, 4> ValueVTs;
5616     ComputeValueVTs(*this, I->getType(), ValueVTs);
5617     for (unsigned Value = 0, NumValues = ValueVTs.size();
5618          Value != NumValues; ++Value) {
5619       MVT VT = ValueVTs[Value];
5620       MVT PartVT = getRegisterType(VT);
5621
5622       unsigned NumParts = getNumRegisters(VT);
5623       SmallVector<SDValue, 4> Parts(NumParts);
5624       for (unsigned j = 0; j != NumParts; ++j)
5625         Parts[j] = SDValue(Result, i++);
5626
5627       ISD::NodeType AssertOp = ISD::DELETED_NODE;
5628       if (F.paramHasAttr(Idx, Attribute::SExt))
5629         AssertOp = ISD::AssertSext;
5630       else if (F.paramHasAttr(Idx, Attribute::ZExt))
5631         AssertOp = ISD::AssertZext;
5632
5633       ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5634                                            PartVT, VT, AssertOp));
5635     }
5636   }
5637   assert(i == NumArgRegs && "Argument register count mismatch!");
5638 }
5639
5640
5641 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5642 /// implementation, which just inserts an ISD::CALL node, which is later custom
5643 /// lowered by the target to something concrete.  FIXME: When all targets are
5644 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5645 std::pair<SDValue, SDValue>
5646 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5647                             bool RetSExt, bool RetZExt, bool isVarArg,
5648                             bool isInreg,
5649                             unsigned CallingConv, bool isTailCall,
5650                             SDValue Callee,
5651                             ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
5652   assert((!isTailCall || PerformTailCallOpt) &&
5653          "isTailCall set when tail-call optimizations are disabled!");
5654
5655   SmallVector<SDValue, 32> Ops;
5656   Ops.push_back(Chain);   // Op#0 - Chain
5657   Ops.push_back(Callee);
5658
5659   // Handle all of the outgoing arguments.
5660   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5661     SmallVector<MVT, 4> ValueVTs;
5662     ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5663     for (unsigned Value = 0, NumValues = ValueVTs.size();
5664          Value != NumValues; ++Value) {
5665       MVT VT = ValueVTs[Value];
5666       const Type *ArgTy = VT.getTypeForMVT();
5667       SDValue Op = SDValue(Args[i].Node.getNode(),
5668                            Args[i].Node.getResNo() + Value);
5669       ISD::ArgFlagsTy Flags;
5670       unsigned OriginalAlignment =
5671         getTargetData()->getABITypeAlignment(ArgTy);
5672
5673       if (Args[i].isZExt)
5674         Flags.setZExt();
5675       if (Args[i].isSExt)
5676         Flags.setSExt();
5677       if (Args[i].isInReg)
5678         Flags.setInReg();
5679       if (Args[i].isSRet)
5680         Flags.setSRet();
5681       if (Args[i].isByVal) {
5682         Flags.setByVal();
5683         const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5684         const Type *ElementTy = Ty->getElementType();
5685         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5686         unsigned FrameSize  = getTargetData()->getTypePaddedSize(ElementTy);
5687         // For ByVal, alignment should come from FE.  BE will guess if this
5688         // info is not there but there are cases it cannot get right.
5689         if (Args[i].Alignment)
5690           FrameAlign = Args[i].Alignment;
5691         Flags.setByValAlign(FrameAlign);
5692         Flags.setByValSize(FrameSize);
5693       }
5694       if (Args[i].isNest)
5695         Flags.setNest();
5696       Flags.setOrigAlign(OriginalAlignment);
5697
5698       MVT PartVT = getRegisterType(VT);
5699       unsigned NumParts = getNumRegisters(VT);
5700       SmallVector<SDValue, 4> Parts(NumParts);
5701       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5702
5703       if (Args[i].isSExt)
5704         ExtendKind = ISD::SIGN_EXTEND;
5705       else if (Args[i].isZExt)
5706         ExtendKind = ISD::ZERO_EXTEND;
5707
5708       getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5709
5710       for (unsigned i = 0; i != NumParts; ++i) {
5711         // if it isn't first piece, alignment must be 1
5712         ISD::ArgFlagsTy MyFlags = Flags;
5713         if (NumParts > 1 && i == 0)
5714           MyFlags.setSplit();
5715         else if (i != 0)
5716           MyFlags.setOrigAlign(1);
5717
5718         Ops.push_back(Parts[i]);
5719         Ops.push_back(DAG.getArgFlags(MyFlags));
5720       }
5721     }
5722   }
5723
5724   // Figure out the result value types. We start by making a list of
5725   // the potentially illegal return value types.
5726   SmallVector<MVT, 4> LoweredRetTys;
5727   SmallVector<MVT, 4> RetTys;
5728   ComputeValueVTs(*this, RetTy, RetTys);
5729
5730   // Then we translate that to a list of legal types.
5731   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5732     MVT VT = RetTys[I];
5733     MVT RegisterVT = getRegisterType(VT);
5734     unsigned NumRegs = getNumRegisters(VT);
5735     for (unsigned i = 0; i != NumRegs; ++i)
5736       LoweredRetTys.push_back(RegisterVT);
5737   }
5738
5739   LoweredRetTys.push_back(MVT::Other);  // Always has a chain.
5740
5741   // Create the CALL node.
5742   SDValue Res = DAG.getCall(CallingConv, dl,
5743                             isVarArg, isTailCall, isInreg,
5744                             DAG.getVTList(&LoweredRetTys[0],
5745                                           LoweredRetTys.size()),
5746                             &Ops[0], Ops.size()
5747                             );
5748   Chain = Res.getValue(LoweredRetTys.size() - 1);
5749
5750   // Gather up the call result into a single value.
5751   if (RetTy != Type::VoidTy && !RetTys.empty()) {
5752     ISD::NodeType AssertOp = ISD::DELETED_NODE;
5753
5754     if (RetSExt)
5755       AssertOp = ISD::AssertSext;
5756     else if (RetZExt)
5757       AssertOp = ISD::AssertZext;
5758
5759     SmallVector<SDValue, 4> ReturnValues;
5760     unsigned RegNo = 0;
5761     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5762       MVT VT = RetTys[I];
5763       MVT RegisterVT = getRegisterType(VT);
5764       unsigned NumRegs = getNumRegisters(VT);
5765       unsigned RegNoEnd = NumRegs + RegNo;
5766       SmallVector<SDValue, 4> Results;
5767       for (; RegNo != RegNoEnd; ++RegNo)
5768         Results.push_back(Res.getValue(RegNo));
5769       SDValue ReturnValue =
5770         getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
5771                          AssertOp);
5772       ReturnValues.push_back(ReturnValue);
5773     }
5774     Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5775                       DAG.getVTList(&RetTys[0], RetTys.size()),
5776                       &ReturnValues[0], ReturnValues.size());
5777   }
5778
5779   return std::make_pair(Res, Chain);
5780 }
5781
5782 void TargetLowering::LowerOperationWrapper(SDNode *N,
5783                                            SmallVectorImpl<SDValue> &Results,
5784                                            SelectionDAG &DAG) {
5785   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5786   if (Res.getNode())
5787     Results.push_back(Res);
5788 }
5789
5790 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5791   assert(0 && "LowerOperation not implemented for this target!");
5792   abort();
5793   return SDValue();
5794 }
5795
5796
5797 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5798   SDValue Op = getValue(V);
5799   assert((Op.getOpcode() != ISD::CopyFromReg ||
5800           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5801          "Copy from a reg to the same reg!");
5802   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5803
5804   RegsForValue RFV(TLI, Reg, V->getType());
5805   SDValue Chain = DAG.getEntryNode();
5806   RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5807   PendingExports.push_back(Chain);
5808 }
5809
5810 #include "llvm/CodeGen/SelectionDAGISel.h"
5811
5812 void SelectionDAGISel::
5813 LowerArguments(BasicBlock *LLVMBB) {
5814   // If this is the entry block, emit arguments.
5815   Function &F = *LLVMBB->getParent();
5816   SDValue OldRoot = SDL->DAG.getRoot();
5817   SmallVector<SDValue, 16> Args;
5818   TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
5819
5820   unsigned a = 0;
5821   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5822        AI != E; ++AI) {
5823     SmallVector<MVT, 4> ValueVTs;
5824     ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5825     unsigned NumValues = ValueVTs.size();
5826     if (!AI->use_empty()) {
5827       SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
5828                                                 SDL->getCurDebugLoc()));
5829       // If this argument is live outside of the entry block, insert a copy from
5830       // whereever we got it to the vreg that other BB's will reference it as.
5831       DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5832       if (VMI != FuncInfo->ValueMap.end()) {
5833         SDL->CopyValueToVirtualRegister(AI, VMI->second);
5834       }
5835     }
5836     a += NumValues;
5837   }
5838
5839   // Finally, if the target has anything special to do, allow it to do so.
5840   // FIXME: this should insert code into the DAG!
5841   EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5842 }
5843
5844 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
5845 /// ensure constants are generated when needed.  Remember the virtual registers
5846 /// that need to be added to the Machine PHI nodes as input.  We cannot just
5847 /// directly add them, because expansion might result in multiple MBB's for one
5848 /// BB.  As such, the start of the BB might correspond to a different MBB than
5849 /// the end.
5850 ///
5851 void
5852 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5853   TerminatorInst *TI = LLVMBB->getTerminator();
5854
5855   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5856
5857   // Check successor nodes' PHI nodes that expect a constant to be available
5858   // from this block.
5859   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5860     BasicBlock *SuccBB = TI->getSuccessor(succ);
5861     if (!isa<PHINode>(SuccBB->begin())) continue;
5862     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5863
5864     // If this terminator has multiple identical successors (common for
5865     // switches), only handle each succ once.
5866     if (!SuccsHandled.insert(SuccMBB)) continue;
5867
5868     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5869     PHINode *PN;
5870
5871     // At this point we know that there is a 1-1 correspondence between LLVM PHI
5872     // nodes and Machine PHI nodes, but the incoming operands have not been
5873     // emitted yet.
5874     for (BasicBlock::iterator I = SuccBB->begin();
5875          (PN = dyn_cast<PHINode>(I)); ++I) {
5876       // Ignore dead phi's.
5877       if (PN->use_empty()) continue;
5878
5879       unsigned Reg;
5880       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5881
5882       if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5883         unsigned &RegOut = SDL->ConstantsOut[C];
5884         if (RegOut == 0) {
5885           RegOut = FuncInfo->CreateRegForValue(C);
5886           SDL->CopyValueToVirtualRegister(C, RegOut);
5887         }
5888         Reg = RegOut;
5889       } else {
5890         Reg = FuncInfo->ValueMap[PHIOp];
5891         if (Reg == 0) {
5892           assert(isa<AllocaInst>(PHIOp) &&
5893                  FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5894                  "Didn't codegen value into a register!??");
5895           Reg = FuncInfo->CreateRegForValue(PHIOp);
5896           SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5897         }
5898       }
5899
5900       // Remember that this register needs to added to the machine PHI node as
5901       // the input for this MBB.
5902       SmallVector<MVT, 4> ValueVTs;
5903       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5904       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5905         MVT VT = ValueVTs[vti];
5906         unsigned NumRegisters = TLI.getNumRegisters(VT);
5907         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5908           SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5909         Reg += NumRegisters;
5910       }
5911     }
5912   }
5913   SDL->ConstantsOut.clear();
5914 }
5915
5916 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5917 /// supports legal types, and it emits MachineInstrs directly instead of
5918 /// creating SelectionDAG nodes.
5919 ///
5920 bool
5921 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5922                                                       FastISel *F) {
5923   TerminatorInst *TI = LLVMBB->getTerminator();
5924
5925   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5926   unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5927
5928   // Check successor nodes' PHI nodes that expect a constant to be available
5929   // from this block.
5930   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5931     BasicBlock *SuccBB = TI->getSuccessor(succ);
5932     if (!isa<PHINode>(SuccBB->begin())) continue;
5933     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5934
5935     // If this terminator has multiple identical successors (common for
5936     // switches), only handle each succ once.
5937     if (!SuccsHandled.insert(SuccMBB)) continue;
5938
5939     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5940     PHINode *PN;
5941
5942     // At this point we know that there is a 1-1 correspondence between LLVM PHI
5943     // nodes and Machine PHI nodes, but the incoming operands have not been
5944     // emitted yet.
5945     for (BasicBlock::iterator I = SuccBB->begin();
5946          (PN = dyn_cast<PHINode>(I)); ++I) {
5947       // Ignore dead phi's.
5948       if (PN->use_empty()) continue;
5949
5950       // Only handle legal types. Two interesting things to note here. First,
5951       // by bailing out early, we may leave behind some dead instructions,
5952       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5953       // own moves. Second, this check is necessary becuase FastISel doesn't
5954       // use CreateRegForValue to create registers, so it always creates
5955       // exactly one register for each non-void instruction.
5956       MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5957       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5958         // Promote MVT::i1.
5959         if (VT == MVT::i1)
5960           VT = TLI.getTypeToTransformTo(VT);
5961         else {
5962           SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5963           return false;
5964         }
5965       }
5966
5967       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5968
5969       unsigned Reg = F->getRegForValue(PHIOp);
5970       if (Reg == 0) {
5971         SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5972         return false;
5973       }
5974       SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5975     }
5976   }
5977
5978   return true;
5979 }