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