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