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