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