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