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