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