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