IR: Split Metadata from Value
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuilder.cpp
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 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GCMetadata.h"
28 #include "llvm/CodeGen/GCStrategy.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/StackMaps.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DebugInfo.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Intrinsics.h"
48 #include "llvm/IR/LLVMContext.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/IR/Statepoint.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetFrameLowering.h"
57 #include "llvm/Target/TargetInstrInfo.h"
58 #include "llvm/Target/TargetIntrinsicInfo.h"
59 #include "llvm/Target/TargetLibraryInfo.h"
60 #include "llvm/Target/TargetLowering.h"
61 #include "llvm/Target/TargetOptions.h"
62 #include "llvm/Target/TargetSelectionDAGInfo.h"
63 #include "llvm/Target/TargetSubtargetInfo.h"
64 #include <algorithm>
65 using namespace llvm;
66
67 #define DEBUG_TYPE "isel"
68
69 /// LimitFloatPrecision - Generate low-precision inline sequences for
70 /// some float libcalls (6, 8 or 12 bits).
71 static unsigned LimitFloatPrecision;
72
73 static cl::opt<unsigned, true>
74 LimitFPPrecision("limit-float-precision",
75                  cl::desc("Generate low-precision inline sequences "
76                           "for some float libcalls"),
77                  cl::location(LimitFloatPrecision),
78                  cl::init(0));
79
80 // Limit the width of DAG chains. This is important in general to prevent
81 // prevent DAG-based analysis from blowing up. For example, alias analysis and
82 // load clustering may not complete in reasonable time. It is difficult to
83 // recognize and avoid this situation within each individual analysis, and
84 // future analyses are likely to have the same behavior. Limiting DAG width is
85 // the safe approach, and will be especially important with global DAGs.
86 //
87 // MaxParallelChains default is arbitrarily high to avoid affecting
88 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
89 // sequence over this should have been converted to llvm.memcpy by the
90 // frontend. It easy to induce this behavior with .ll code such as:
91 // %buffer = alloca [4096 x i8]
92 // %data = load [4096 x i8]* %argPtr
93 // store [4096 x i8] %data, [4096 x i8]* %buffer
94 static const unsigned MaxParallelChains = 64;
95
96 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
97                                       const SDValue *Parts, unsigned NumParts,
98                                       MVT PartVT, EVT ValueVT, const Value *V);
99
100 /// getCopyFromParts - Create a value that contains the specified legal parts
101 /// combined into the value they represent.  If the parts combine to a type
102 /// larger then ValueVT then AssertOp can be used to specify whether the extra
103 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
104 /// (ISD::AssertSext).
105 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
106                                 const SDValue *Parts,
107                                 unsigned NumParts, MVT PartVT, EVT ValueVT,
108                                 const Value *V,
109                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
110   if (ValueVT.isVector())
111     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
112                                   PartVT, ValueVT, V);
113
114   assert(NumParts > 0 && "No parts to assemble!");
115   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
116   SDValue Val = Parts[0];
117
118   if (NumParts > 1) {
119     // Assemble the value from multiple parts.
120     if (ValueVT.isInteger()) {
121       unsigned PartBits = PartVT.getSizeInBits();
122       unsigned ValueBits = ValueVT.getSizeInBits();
123
124       // Assemble the power of 2 part.
125       unsigned RoundParts = NumParts & (NumParts - 1) ?
126         1 << Log2_32(NumParts) : NumParts;
127       unsigned RoundBits = PartBits * RoundParts;
128       EVT RoundVT = RoundBits == ValueBits ?
129         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
130       SDValue Lo, Hi;
131
132       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
133
134       if (RoundParts > 2) {
135         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
136                               PartVT, HalfVT, V);
137         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
138                               RoundParts / 2, PartVT, HalfVT, V);
139       } else {
140         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
141         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
142       }
143
144       if (TLI.isBigEndian())
145         std::swap(Lo, Hi);
146
147       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
148
149       if (RoundParts < NumParts) {
150         // Assemble the trailing non-power-of-2 part.
151         unsigned OddParts = NumParts - RoundParts;
152         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
153         Hi = getCopyFromParts(DAG, DL,
154                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
155
156         // Combine the round and odd parts.
157         Lo = Val;
158         if (TLI.isBigEndian())
159           std::swap(Lo, Hi);
160         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
161         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
162         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
163                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
164                                          TLI.getPointerTy()));
165         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
166         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
167       }
168     } else if (PartVT.isFloatingPoint()) {
169       // FP split into multiple FP parts (for ppcf128)
170       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
171              "Unexpected split");
172       SDValue Lo, Hi;
173       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
174       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
175       if (TLI.hasBigEndianPartOrdering(ValueVT))
176         std::swap(Lo, Hi);
177       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
178     } else {
179       // FP split into integer parts (soft fp)
180       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
181              !PartVT.isVector() && "Unexpected split");
182       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
183       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
184     }
185   }
186
187   // There is now one part, held in Val.  Correct it to match ValueVT.
188   EVT PartEVT = Val.getValueType();
189
190   if (PartEVT == ValueVT)
191     return Val;
192
193   if (PartEVT.isInteger() && ValueVT.isInteger()) {
194     if (ValueVT.bitsLT(PartEVT)) {
195       // For a truncate, see if we have any information to
196       // indicate whether the truncated bits will always be
197       // zero or sign-extension.
198       if (AssertOp != ISD::DELETED_NODE)
199         Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
200                           DAG.getValueType(ValueVT));
201       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
202     }
203     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
204   }
205
206   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
207     // FP_ROUND's are always exact here.
208     if (ValueVT.bitsLT(Val.getValueType()))
209       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
210                          DAG.getTargetConstant(1, TLI.getPointerTy()));
211
212     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
213   }
214
215   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
216     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
217
218   llvm_unreachable("Unknown mismatch!");
219 }
220
221 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
222                                               const Twine &ErrMsg) {
223   const Instruction *I = dyn_cast_or_null<Instruction>(V);
224   if (!V)
225     return Ctx.emitError(ErrMsg);
226
227   const char *AsmError = ", possible invalid constraint for vector type";
228   if (const CallInst *CI = dyn_cast<CallInst>(I))
229     if (isa<InlineAsm>(CI->getCalledValue()))
230       return Ctx.emitError(I, ErrMsg + AsmError);
231
232   return Ctx.emitError(I, ErrMsg);
233 }
234
235 /// getCopyFromPartsVector - Create a value that contains the specified legal
236 /// parts combined into the value they represent.  If the parts combine to a
237 /// type larger then ValueVT then AssertOp can be used to specify whether the
238 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
239 /// ValueVT (ISD::AssertSext).
240 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
241                                       const SDValue *Parts, unsigned NumParts,
242                                       MVT PartVT, EVT ValueVT, const Value *V) {
243   assert(ValueVT.isVector() && "Not a vector value");
244   assert(NumParts > 0 && "No parts to assemble!");
245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
246   SDValue Val = Parts[0];
247
248   // Handle a multi-element vector.
249   if (NumParts > 1) {
250     EVT IntermediateVT;
251     MVT RegisterVT;
252     unsigned NumIntermediates;
253     unsigned NumRegs =
254     TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
255                                NumIntermediates, RegisterVT);
256     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
257     NumParts = NumRegs; // Silence a compiler warning.
258     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
259     assert(RegisterVT == Parts[0].getSimpleValueType() &&
260            "Part type doesn't match part!");
261
262     // Assemble the parts into intermediate operands.
263     SmallVector<SDValue, 8> Ops(NumIntermediates);
264     if (NumIntermediates == NumParts) {
265       // If the register was not expanded, truncate or copy the value,
266       // as appropriate.
267       for (unsigned i = 0; i != NumParts; ++i)
268         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
269                                   PartVT, IntermediateVT, V);
270     } else if (NumParts > 0) {
271       // If the intermediate type was expanded, build the intermediate
272       // operands from the parts.
273       assert(NumParts % NumIntermediates == 0 &&
274              "Must expand into a divisible number of parts!");
275       unsigned Factor = NumParts / NumIntermediates;
276       for (unsigned i = 0; i != NumIntermediates; ++i)
277         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
278                                   PartVT, IntermediateVT, V);
279     }
280
281     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
282     // intermediate operands.
283     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
284                                                 : ISD::BUILD_VECTOR,
285                       DL, ValueVT, Ops);
286   }
287
288   // There is now one part, held in Val.  Correct it to match ValueVT.
289   EVT PartEVT = Val.getValueType();
290
291   if (PartEVT == ValueVT)
292     return Val;
293
294   if (PartEVT.isVector()) {
295     // If the element type of the source/dest vectors are the same, but the
296     // parts vector has more elements than the value vector, then we have a
297     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
298     // elements we want.
299     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
300       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
301              "Cannot narrow, it would be a lossy transformation");
302       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
303                          DAG.getConstant(0, TLI.getVectorIdxTy()));
304     }
305
306     // Vector/Vector bitcast.
307     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
308       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
309
310     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
311       "Cannot handle this kind of promotion");
312     // Promoted vector extract
313     bool Smaller = ValueVT.bitsLE(PartEVT);
314     return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
315                        DL, ValueVT, Val);
316
317   }
318
319   // Trivial bitcast if the types are the same size and the destination
320   // vector type is legal.
321   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
322       TLI.isTypeLegal(ValueVT))
323     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
324
325   // Handle cases such as i8 -> <1 x i1>
326   if (ValueVT.getVectorNumElements() != 1) {
327     diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
328                                       "non-trivial scalar-to-vector conversion");
329     return DAG.getUNDEF(ValueVT);
330   }
331
332   if (ValueVT.getVectorNumElements() == 1 &&
333       ValueVT.getVectorElementType() != PartEVT) {
334     bool Smaller = ValueVT.bitsLE(PartEVT);
335     Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
336                        DL, ValueVT.getScalarType(), Val);
337   }
338
339   return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
340 }
341
342 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
343                                  SDValue Val, SDValue *Parts, unsigned NumParts,
344                                  MVT PartVT, const Value *V);
345
346 /// getCopyToParts - Create a series of nodes that contain the specified value
347 /// split into legal parts.  If the parts contain more bits than Val, then, for
348 /// integers, ExtendKind can be used to specify how to generate the extra bits.
349 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
350                            SDValue Val, SDValue *Parts, unsigned NumParts,
351                            MVT PartVT, const Value *V,
352                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
353   EVT ValueVT = Val.getValueType();
354
355   // Handle the vector case separately.
356   if (ValueVT.isVector())
357     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
358
359   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
360   unsigned PartBits = PartVT.getSizeInBits();
361   unsigned OrigNumParts = NumParts;
362   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
363
364   if (NumParts == 0)
365     return;
366
367   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
368   EVT PartEVT = PartVT;
369   if (PartEVT == ValueVT) {
370     assert(NumParts == 1 && "No-op copy with multiple parts!");
371     Parts[0] = Val;
372     return;
373   }
374
375   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
376     // If the parts cover more bits than the value has, promote the value.
377     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
378       assert(NumParts == 1 && "Do not know what to promote to!");
379       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
380     } else {
381       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
382              ValueVT.isInteger() &&
383              "Unknown mismatch!");
384       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
385       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
386       if (PartVT == MVT::x86mmx)
387         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
388     }
389   } else if (PartBits == ValueVT.getSizeInBits()) {
390     // Different types of the same size.
391     assert(NumParts == 1 && PartEVT != ValueVT);
392     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
393   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
394     // If the parts cover less bits than value has, truncate the value.
395     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
396            ValueVT.isInteger() &&
397            "Unknown mismatch!");
398     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
399     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
400     if (PartVT == MVT::x86mmx)
401       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
402   }
403
404   // The value may have changed - recompute ValueVT.
405   ValueVT = Val.getValueType();
406   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
407          "Failed to tile the value with PartVT!");
408
409   if (NumParts == 1) {
410     if (PartEVT != ValueVT)
411       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
412                                         "scalar-to-vector conversion failed");
413
414     Parts[0] = Val;
415     return;
416   }
417
418   // Expand the value into multiple parts.
419   if (NumParts & (NumParts - 1)) {
420     // The number of parts is not a power of 2.  Split off and copy the tail.
421     assert(PartVT.isInteger() && ValueVT.isInteger() &&
422            "Do not know what to expand to!");
423     unsigned RoundParts = 1 << Log2_32(NumParts);
424     unsigned RoundBits = RoundParts * PartBits;
425     unsigned OddParts = NumParts - RoundParts;
426     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
427                                  DAG.getIntPtrConstant(RoundBits));
428     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
429
430     if (TLI.isBigEndian())
431       // The odd parts were reversed by getCopyToParts - unreverse them.
432       std::reverse(Parts + RoundParts, Parts + NumParts);
433
434     NumParts = RoundParts;
435     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
436     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
437   }
438
439   // The number of parts is a power of 2.  Repeatedly bisect the value using
440   // EXTRACT_ELEMENT.
441   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
442                          EVT::getIntegerVT(*DAG.getContext(),
443                                            ValueVT.getSizeInBits()),
444                          Val);
445
446   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
447     for (unsigned i = 0; i < NumParts; i += StepSize) {
448       unsigned ThisBits = StepSize * PartBits / 2;
449       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
450       SDValue &Part0 = Parts[i];
451       SDValue &Part1 = Parts[i+StepSize/2];
452
453       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
454                           ThisVT, Part0, DAG.getIntPtrConstant(1));
455       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
456                           ThisVT, Part0, DAG.getIntPtrConstant(0));
457
458       if (ThisBits == PartBits && ThisVT != PartVT) {
459         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
460         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
461       }
462     }
463   }
464
465   if (TLI.isBigEndian())
466     std::reverse(Parts, Parts + OrigNumParts);
467 }
468
469
470 /// getCopyToPartsVector - Create a series of nodes that contain the specified
471 /// value split into legal parts.
472 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
473                                  SDValue Val, SDValue *Parts, unsigned NumParts,
474                                  MVT PartVT, const Value *V) {
475   EVT ValueVT = Val.getValueType();
476   assert(ValueVT.isVector() && "Not a vector");
477   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
478
479   if (NumParts == 1) {
480     EVT PartEVT = PartVT;
481     if (PartEVT == ValueVT) {
482       // Nothing to do.
483     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
484       // Bitconvert vector->vector case.
485       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
486     } else if (PartVT.isVector() &&
487                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
488                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
489       EVT ElementVT = PartVT.getVectorElementType();
490       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
491       // undef elements.
492       SmallVector<SDValue, 16> Ops;
493       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
494         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
495                                   ElementVT, Val, DAG.getConstant(i,
496                                                   TLI.getVectorIdxTy())));
497
498       for (unsigned i = ValueVT.getVectorNumElements(),
499            e = PartVT.getVectorNumElements(); i != e; ++i)
500         Ops.push_back(DAG.getUNDEF(ElementVT));
501
502       Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
503
504       // FIXME: Use CONCAT for 2x -> 4x.
505
506       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
507       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
508     } else if (PartVT.isVector() &&
509                PartEVT.getVectorElementType().bitsGE(
510                  ValueVT.getVectorElementType()) &&
511                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
512
513       // Promoted vector extract
514       bool Smaller = PartEVT.bitsLE(ValueVT);
515       Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
516                         DL, PartVT, Val);
517     } else{
518       // Vector -> scalar conversion.
519       assert(ValueVT.getVectorNumElements() == 1 &&
520              "Only trivial vector-to-scalar conversions should get here!");
521       Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
522                         PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
523
524       bool Smaller = ValueVT.bitsLE(PartVT);
525       Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
526                          DL, PartVT, Val);
527     }
528
529     Parts[0] = Val;
530     return;
531   }
532
533   // Handle a multi-element vector.
534   EVT IntermediateVT;
535   MVT RegisterVT;
536   unsigned NumIntermediates;
537   unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
538                                                 IntermediateVT,
539                                                 NumIntermediates, RegisterVT);
540   unsigned NumElements = ValueVT.getVectorNumElements();
541
542   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
543   NumParts = NumRegs; // Silence a compiler warning.
544   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
545
546   // Split the vector into intermediate operands.
547   SmallVector<SDValue, 8> Ops(NumIntermediates);
548   for (unsigned i = 0; i != NumIntermediates; ++i) {
549     if (IntermediateVT.isVector())
550       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
551                            IntermediateVT, Val,
552                    DAG.getConstant(i * (NumElements / NumIntermediates),
553                                    TLI.getVectorIdxTy()));
554     else
555       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
556                            IntermediateVT, Val,
557                            DAG.getConstant(i, TLI.getVectorIdxTy()));
558   }
559
560   // Split the intermediate operands into legal parts.
561   if (NumParts == NumIntermediates) {
562     // If the register was not expanded, promote or copy the value,
563     // as appropriate.
564     for (unsigned i = 0; i != NumParts; ++i)
565       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
566   } else if (NumParts > 0) {
567     // If the intermediate type was expanded, split each the value into
568     // legal parts.
569     assert(NumParts % NumIntermediates == 0 &&
570            "Must expand into a divisible number of parts!");
571     unsigned Factor = NumParts / NumIntermediates;
572     for (unsigned i = 0; i != NumIntermediates; ++i)
573       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
574   }
575 }
576
577 namespace {
578   /// RegsForValue - This struct represents the registers (physical or virtual)
579   /// that a particular set of values is assigned, and the type information
580   /// about the value. The most common situation is to represent one value at a
581   /// time, but struct or array values are handled element-wise as multiple
582   /// values.  The splitting of aggregates is performed recursively, so that we
583   /// never have aggregate-typed registers. The values at this point do not
584   /// necessarily have legal types, so each value may require one or more
585   /// registers of some legal type.
586   ///
587   struct RegsForValue {
588     /// ValueVTs - The value types of the values, which may not be legal, and
589     /// may need be promoted or synthesized from one or more registers.
590     ///
591     SmallVector<EVT, 4> ValueVTs;
592
593     /// RegVTs - The value types of the registers. This is the same size as
594     /// ValueVTs and it records, for each value, what the type of the assigned
595     /// register or registers are. (Individual values are never synthesized
596     /// from more than one type of register.)
597     ///
598     /// With virtual registers, the contents of RegVTs is redundant with TLI's
599     /// getRegisterType member function, however when with physical registers
600     /// it is necessary to have a separate record of the types.
601     ///
602     SmallVector<MVT, 4> RegVTs;
603
604     /// Regs - This list holds the registers assigned to the values.
605     /// Each legal or promoted value requires one register, and each
606     /// expanded value requires multiple registers.
607     ///
608     SmallVector<unsigned, 4> Regs;
609
610     RegsForValue() {}
611
612     RegsForValue(const SmallVector<unsigned, 4> &regs,
613                  MVT regvt, EVT valuevt)
614       : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
615
616     RegsForValue(LLVMContext &Context, const TargetLowering &tli,
617                  unsigned Reg, Type *Ty) {
618       ComputeValueVTs(tli, Ty, ValueVTs);
619
620       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
621         EVT ValueVT = ValueVTs[Value];
622         unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
623         MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
624         for (unsigned i = 0; i != NumRegs; ++i)
625           Regs.push_back(Reg + i);
626         RegVTs.push_back(RegisterVT);
627         Reg += NumRegs;
628       }
629     }
630
631     /// append - Add the specified values to this one.
632     void append(const RegsForValue &RHS) {
633       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
634       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
635       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
636     }
637
638     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
639     /// this value and returns the result as a ValueVTs value.  This uses
640     /// Chain/Flag as the input and updates them for the output Chain/Flag.
641     /// If the Flag pointer is NULL, no flag is used.
642     SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
643                             SDLoc dl,
644                             SDValue &Chain, SDValue *Flag,
645                             const Value *V = nullptr) const;
646
647     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
648     /// specified value into the registers specified by this object.  This uses
649     /// Chain/Flag as the input and updates them for the output Chain/Flag.
650     /// If the Flag pointer is NULL, no flag is used.
651     void
652     getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
653                   SDValue *Flag, const Value *V,
654                   ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
655
656     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
657     /// operand list.  This adds the code marker, matching input operand index
658     /// (if applicable), and includes the number of values added into it.
659     void AddInlineAsmOperands(unsigned Kind,
660                               bool HasMatching, unsigned MatchingIdx,
661                               SelectionDAG &DAG,
662                               std::vector<SDValue> &Ops) const;
663   };
664 }
665
666 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
667 /// this value and returns the result as a ValueVT value.  This uses
668 /// Chain/Flag as the input and updates them for the output Chain/Flag.
669 /// If the Flag pointer is NULL, no flag is used.
670 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
671                                       FunctionLoweringInfo &FuncInfo,
672                                       SDLoc dl,
673                                       SDValue &Chain, SDValue *Flag,
674                                       const Value *V) const {
675   // A Value with type {} or [0 x %t] needs no registers.
676   if (ValueVTs.empty())
677     return SDValue();
678
679   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
680
681   // Assemble the legal parts into the final values.
682   SmallVector<SDValue, 4> Values(ValueVTs.size());
683   SmallVector<SDValue, 8> Parts;
684   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
685     // Copy the legal parts from the registers.
686     EVT ValueVT = ValueVTs[Value];
687     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
688     MVT RegisterVT = RegVTs[Value];
689
690     Parts.resize(NumRegs);
691     for (unsigned i = 0; i != NumRegs; ++i) {
692       SDValue P;
693       if (!Flag) {
694         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
695       } else {
696         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
697         *Flag = P.getValue(2);
698       }
699
700       Chain = P.getValue(1);
701       Parts[i] = P;
702
703       // If the source register was virtual and if we know something about it,
704       // add an assert node.
705       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
706           !RegisterVT.isInteger() || RegisterVT.isVector())
707         continue;
708
709       const FunctionLoweringInfo::LiveOutInfo *LOI =
710         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
711       if (!LOI)
712         continue;
713
714       unsigned RegSize = RegisterVT.getSizeInBits();
715       unsigned NumSignBits = LOI->NumSignBits;
716       unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
717
718       if (NumZeroBits == RegSize) {
719         // The current value is a zero.
720         // Explicitly express that as it would be easier for
721         // optimizations to kick in.
722         Parts[i] = DAG.getConstant(0, RegisterVT);
723         continue;
724       }
725
726       // FIXME: We capture more information than the dag can represent.  For
727       // now, just use the tightest assertzext/assertsext possible.
728       bool isSExt = true;
729       EVT FromVT(MVT::Other);
730       if (NumSignBits == RegSize)
731         isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
732       else if (NumZeroBits >= RegSize-1)
733         isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
734       else if (NumSignBits > RegSize-8)
735         isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
736       else if (NumZeroBits >= RegSize-8)
737         isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
738       else if (NumSignBits > RegSize-16)
739         isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
740       else if (NumZeroBits >= RegSize-16)
741         isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
742       else if (NumSignBits > RegSize-32)
743         isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
744       else if (NumZeroBits >= RegSize-32)
745         isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
746       else
747         continue;
748
749       // Add an assertion node.
750       assert(FromVT != MVT::Other);
751       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
752                              RegisterVT, P, DAG.getValueType(FromVT));
753     }
754
755     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
756                                      NumRegs, RegisterVT, ValueVT, V);
757     Part += NumRegs;
758     Parts.clear();
759   }
760
761   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
762 }
763
764 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
765 /// specified value into the registers specified by this object.  This uses
766 /// Chain/Flag as the input and updates them for the output Chain/Flag.
767 /// If the Flag pointer is NULL, no flag is used.
768 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
769                                  SDValue &Chain, SDValue *Flag, const Value *V,
770                                  ISD::NodeType PreferredExtendType) const {
771   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
772   ISD::NodeType ExtendKind = PreferredExtendType;
773
774   // Get the list of the values's legal parts.
775   unsigned NumRegs = Regs.size();
776   SmallVector<SDValue, 8> Parts(NumRegs);
777   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
778     EVT ValueVT = ValueVTs[Value];
779     unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
780     MVT RegisterVT = RegVTs[Value];
781
782     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
783       ExtendKind = ISD::ZERO_EXTEND;
784
785     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
786                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
787     Part += NumParts;
788   }
789
790   // Copy the parts into the registers.
791   SmallVector<SDValue, 8> Chains(NumRegs);
792   for (unsigned i = 0; i != NumRegs; ++i) {
793     SDValue Part;
794     if (!Flag) {
795       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
796     } else {
797       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
798       *Flag = Part.getValue(1);
799     }
800
801     Chains[i] = Part.getValue(0);
802   }
803
804   if (NumRegs == 1 || Flag)
805     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
806     // flagged to it. That is the CopyToReg nodes and the user are considered
807     // a single scheduling unit. If we create a TokenFactor and return it as
808     // chain, then the TokenFactor is both a predecessor (operand) of the
809     // user as well as a successor (the TF operands are flagged to the user).
810     // c1, f1 = CopyToReg
811     // c2, f2 = CopyToReg
812     // c3     = TokenFactor c1, c2
813     // ...
814     //        = op c3, ..., f2
815     Chain = Chains[NumRegs-1];
816   else
817     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
818 }
819
820 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
821 /// operand list.  This adds the code marker and includes the number of
822 /// values added into it.
823 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
824                                         unsigned MatchingIdx,
825                                         SelectionDAG &DAG,
826                                         std::vector<SDValue> &Ops) const {
827   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
828
829   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
830   if (HasMatching)
831     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
832   else if (!Regs.empty() &&
833            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
834     // Put the register class of the virtual registers in the flag word.  That
835     // way, later passes can recompute register class constraints for inline
836     // assembly as well as normal instructions.
837     // Don't do this for tied operands that can use the regclass information
838     // from the def.
839     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
840     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
841     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
842   }
843
844   SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
845   Ops.push_back(Res);
846
847   unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
848   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
849     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
850     MVT RegisterVT = RegVTs[Value];
851     for (unsigned i = 0; i != NumRegs; ++i) {
852       assert(Reg < Regs.size() && "Mismatch in # registers expected");
853       unsigned TheReg = Regs[Reg++];
854       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
855
856       if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
857         // If we clobbered the stack pointer, MFI should know about it.
858         assert(DAG.getMachineFunction().getFrameInfo()->
859             hasInlineAsmWithSPAdjust());
860       }
861     }
862   }
863 }
864
865 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
866                                const TargetLibraryInfo *li) {
867   AA = &aa;
868   GFI = gfi;
869   LibInfo = li;
870   DL = DAG.getSubtarget().getDataLayout();
871   Context = DAG.getContext();
872   LPadToCallSiteMap.clear();
873 }
874
875 /// clear - Clear out the current SelectionDAG and the associated
876 /// state and prepare this SelectionDAGBuilder object to be used
877 /// for a new block. This doesn't clear out information about
878 /// additional blocks that are needed to complete switch lowering
879 /// or PHI node updating; that information is cleared out as it is
880 /// consumed.
881 void SelectionDAGBuilder::clear() {
882   NodeMap.clear();
883   UnusedArgNodeMap.clear();
884   PendingLoads.clear();
885   PendingExports.clear();
886   CurInst = nullptr;
887   HasTailCall = false;
888   SDNodeOrder = LowestSDNodeOrder;
889   StatepointLowering.clear();
890 }
891
892 /// clearDanglingDebugInfo - Clear the dangling debug information
893 /// map. This function is separated from the clear so that debug
894 /// information that is dangling in a basic block can be properly
895 /// resolved in a different basic block. This allows the
896 /// SelectionDAG to resolve dangling debug information attached
897 /// to PHI nodes.
898 void SelectionDAGBuilder::clearDanglingDebugInfo() {
899   DanglingDebugInfoMap.clear();
900 }
901
902 /// getRoot - Return the current virtual root of the Selection DAG,
903 /// flushing any PendingLoad items. This must be done before emitting
904 /// a store or any other node that may need to be ordered after any
905 /// prior load instructions.
906 ///
907 SDValue SelectionDAGBuilder::getRoot() {
908   if (PendingLoads.empty())
909     return DAG.getRoot();
910
911   if (PendingLoads.size() == 1) {
912     SDValue Root = PendingLoads[0];
913     DAG.setRoot(Root);
914     PendingLoads.clear();
915     return Root;
916   }
917
918   // Otherwise, we have to make a token factor node.
919   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
920                              PendingLoads);
921   PendingLoads.clear();
922   DAG.setRoot(Root);
923   return Root;
924 }
925
926 /// getControlRoot - Similar to getRoot, but instead of flushing all the
927 /// PendingLoad items, flush all the PendingExports items. It is necessary
928 /// to do this before emitting a terminator instruction.
929 ///
930 SDValue SelectionDAGBuilder::getControlRoot() {
931   SDValue Root = DAG.getRoot();
932
933   if (PendingExports.empty())
934     return Root;
935
936   // Turn all of the CopyToReg chains into one factored node.
937   if (Root.getOpcode() != ISD::EntryToken) {
938     unsigned i = 0, e = PendingExports.size();
939     for (; i != e; ++i) {
940       assert(PendingExports[i].getNode()->getNumOperands() > 1);
941       if (PendingExports[i].getNode()->getOperand(0) == Root)
942         break;  // Don't add the root if we already indirectly depend on it.
943     }
944
945     if (i == e)
946       PendingExports.push_back(Root);
947   }
948
949   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
950                      PendingExports);
951   PendingExports.clear();
952   DAG.setRoot(Root);
953   return Root;
954 }
955
956 void SelectionDAGBuilder::visit(const Instruction &I) {
957   // Set up outgoing PHI node register values before emitting the terminator.
958   if (isa<TerminatorInst>(&I))
959     HandlePHINodesInSuccessorBlocks(I.getParent());
960
961   ++SDNodeOrder;
962
963   CurInst = &I;
964
965   visit(I.getOpcode(), I);
966
967   if (!isa<TerminatorInst>(&I) && !HasTailCall)
968     CopyToExportRegsIfNeeded(&I);
969
970   CurInst = nullptr;
971 }
972
973 void SelectionDAGBuilder::visitPHI(const PHINode &) {
974   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
975 }
976
977 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
978   // Note: this doesn't use InstVisitor, because it has to work with
979   // ConstantExpr's in addition to instructions.
980   switch (Opcode) {
981   default: llvm_unreachable("Unknown instruction type encountered!");
982     // Build the switch statement using the Instruction.def file.
983 #define HANDLE_INST(NUM, OPCODE, CLASS) \
984     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
985 #include "llvm/IR/Instruction.def"
986   }
987 }
988
989 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
990 // generate the debug data structures now that we've seen its definition.
991 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
992                                                    SDValue Val) {
993   DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
994   if (DDI.getDI()) {
995     const DbgValueInst *DI = DDI.getDI();
996     DebugLoc dl = DDI.getdl();
997     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
998     MDNode *Variable = DI->getVariable();
999     MDNode *Expr = DI->getExpression();
1000     uint64_t Offset = DI->getOffset();
1001     // A dbg.value for an alloca is always indirect.
1002     bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
1003     SDDbgValue *SDV;
1004     if (Val.getNode()) {
1005       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, Offset, IsIndirect,
1006                                     Val)) {
1007         SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
1008                               IsIndirect, Offset, dl, DbgSDNodeOrder);
1009         DAG.AddDbgValue(SDV, Val.getNode(), false);
1010       }
1011     } else
1012       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1013     DanglingDebugInfoMap[V] = DanglingDebugInfo();
1014   }
1015 }
1016
1017 /// getValue - Return an SDValue for the given Value.
1018 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1019   // If we already have an SDValue for this value, use it. It's important
1020   // to do this first, so that we don't create a CopyFromReg if we already
1021   // have a regular SDValue.
1022   SDValue &N = NodeMap[V];
1023   if (N.getNode()) return N;
1024
1025   // If there's a virtual register allocated and initialized for this
1026   // value, use it.
1027   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1028   if (It != FuncInfo.ValueMap.end()) {
1029     unsigned InReg = It->second;
1030     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
1031                      V->getType());
1032     SDValue Chain = DAG.getEntryNode();
1033     N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1034     resolveDanglingDebugInfo(V, N);
1035     return N;
1036   }
1037
1038   // Otherwise create a new SDValue and remember it.
1039   SDValue Val = getValueImpl(V);
1040   NodeMap[V] = Val;
1041   resolveDanglingDebugInfo(V, Val);
1042   return Val;
1043 }
1044
1045 /// getNonRegisterValue - Return an SDValue for the given Value, but
1046 /// don't look in FuncInfo.ValueMap for a virtual register.
1047 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1048   // If we already have an SDValue for this value, use it.
1049   SDValue &N = NodeMap[V];
1050   if (N.getNode()) return N;
1051
1052   // Otherwise create a new SDValue and remember it.
1053   SDValue Val = getValueImpl(V);
1054   NodeMap[V] = Val;
1055   resolveDanglingDebugInfo(V, Val);
1056   return Val;
1057 }
1058
1059 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1060 /// Create an SDValue for the given value.
1061 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1062   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1063
1064   if (const Constant *C = dyn_cast<Constant>(V)) {
1065     EVT VT = TLI.getValueType(V->getType(), true);
1066
1067     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1068       return DAG.getConstant(*CI, VT);
1069
1070     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1071       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1072
1073     if (isa<ConstantPointerNull>(C)) {
1074       unsigned AS = V->getType()->getPointerAddressSpace();
1075       return DAG.getConstant(0, TLI.getPointerTy(AS));
1076     }
1077
1078     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1079       return DAG.getConstantFP(*CFP, VT);
1080
1081     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1082       return DAG.getUNDEF(VT);
1083
1084     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1085       visit(CE->getOpcode(), *CE);
1086       SDValue N1 = NodeMap[V];
1087       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1088       return N1;
1089     }
1090
1091     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1092       SmallVector<SDValue, 4> Constants;
1093       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1094            OI != OE; ++OI) {
1095         SDNode *Val = getValue(*OI).getNode();
1096         // If the operand is an empty aggregate, there are no values.
1097         if (!Val) continue;
1098         // Add each leaf value from the operand to the Constants list
1099         // to form a flattened list of all the values.
1100         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1101           Constants.push_back(SDValue(Val, i));
1102       }
1103
1104       return DAG.getMergeValues(Constants, getCurSDLoc());
1105     }
1106
1107     if (const ConstantDataSequential *CDS =
1108           dyn_cast<ConstantDataSequential>(C)) {
1109       SmallVector<SDValue, 4> Ops;
1110       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1111         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1112         // Add each leaf value from the operand to the Constants list
1113         // to form a flattened list of all the values.
1114         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1115           Ops.push_back(SDValue(Val, i));
1116       }
1117
1118       if (isa<ArrayType>(CDS->getType()))
1119         return DAG.getMergeValues(Ops, getCurSDLoc());
1120       return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1121                                       VT, Ops);
1122     }
1123
1124     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1125       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1126              "Unknown struct or array constant!");
1127
1128       SmallVector<EVT, 4> ValueVTs;
1129       ComputeValueVTs(TLI, C->getType(), ValueVTs);
1130       unsigned NumElts = ValueVTs.size();
1131       if (NumElts == 0)
1132         return SDValue(); // empty struct
1133       SmallVector<SDValue, 4> Constants(NumElts);
1134       for (unsigned i = 0; i != NumElts; ++i) {
1135         EVT EltVT = ValueVTs[i];
1136         if (isa<UndefValue>(C))
1137           Constants[i] = DAG.getUNDEF(EltVT);
1138         else if (EltVT.isFloatingPoint())
1139           Constants[i] = DAG.getConstantFP(0, EltVT);
1140         else
1141           Constants[i] = DAG.getConstant(0, EltVT);
1142       }
1143
1144       return DAG.getMergeValues(Constants, getCurSDLoc());
1145     }
1146
1147     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1148       return DAG.getBlockAddress(BA, VT);
1149
1150     VectorType *VecTy = cast<VectorType>(V->getType());
1151     unsigned NumElements = VecTy->getNumElements();
1152
1153     // Now that we know the number and type of the elements, get that number of
1154     // elements into the Ops array based on what kind of constant it is.
1155     SmallVector<SDValue, 16> Ops;
1156     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1157       for (unsigned i = 0; i != NumElements; ++i)
1158         Ops.push_back(getValue(CV->getOperand(i)));
1159     } else {
1160       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1161       EVT EltVT = TLI.getValueType(VecTy->getElementType());
1162
1163       SDValue Op;
1164       if (EltVT.isFloatingPoint())
1165         Op = DAG.getConstantFP(0, EltVT);
1166       else
1167         Op = DAG.getConstant(0, EltVT);
1168       Ops.assign(NumElements, Op);
1169     }
1170
1171     // Create a BUILD_VECTOR node.
1172     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1173   }
1174
1175   // If this is a static alloca, generate it as the frameindex instead of
1176   // computation.
1177   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1178     DenseMap<const AllocaInst*, int>::iterator SI =
1179       FuncInfo.StaticAllocaMap.find(AI);
1180     if (SI != FuncInfo.StaticAllocaMap.end())
1181       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1182   }
1183
1184   // If this is an instruction which fast-isel has deferred, select it now.
1185   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1186     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1187     RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1188     SDValue Chain = DAG.getEntryNode();
1189     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1190   }
1191
1192   llvm_unreachable("Can't get register for value!");
1193 }
1194
1195 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1196   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1197   SDValue Chain = getControlRoot();
1198   SmallVector<ISD::OutputArg, 8> Outs;
1199   SmallVector<SDValue, 8> OutVals;
1200
1201   if (!FuncInfo.CanLowerReturn) {
1202     unsigned DemoteReg = FuncInfo.DemoteRegister;
1203     const Function *F = I.getParent()->getParent();
1204
1205     // Emit a store of the return value through the virtual register.
1206     // Leave Outs empty so that LowerReturn won't try to load return
1207     // registers the usual way.
1208     SmallVector<EVT, 1> PtrValueVTs;
1209     ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1210                     PtrValueVTs);
1211
1212     SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1213     SDValue RetOp = getValue(I.getOperand(0));
1214
1215     SmallVector<EVT, 4> ValueVTs;
1216     SmallVector<uint64_t, 4> Offsets;
1217     ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1218     unsigned NumValues = ValueVTs.size();
1219
1220     SmallVector<SDValue, 4> Chains(NumValues);
1221     for (unsigned i = 0; i != NumValues; ++i) {
1222       SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1223                                 RetPtr.getValueType(), RetPtr,
1224                                 DAG.getIntPtrConstant(Offsets[i]));
1225       Chains[i] =
1226         DAG.getStore(Chain, getCurSDLoc(),
1227                      SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1228                      // FIXME: better loc info would be nice.
1229                      Add, MachinePointerInfo(), false, false, 0);
1230     }
1231
1232     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1233                         MVT::Other, Chains);
1234   } else if (I.getNumOperands() != 0) {
1235     SmallVector<EVT, 4> ValueVTs;
1236     ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1237     unsigned NumValues = ValueVTs.size();
1238     if (NumValues) {
1239       SDValue RetOp = getValue(I.getOperand(0));
1240       for (unsigned j = 0, f = NumValues; j != f; ++j) {
1241         EVT VT = ValueVTs[j];
1242
1243         ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1244
1245         const Function *F = I.getParent()->getParent();
1246         if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1247                                             Attribute::SExt))
1248           ExtendKind = ISD::SIGN_EXTEND;
1249         else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1250                                                  Attribute::ZExt))
1251           ExtendKind = ISD::ZERO_EXTEND;
1252
1253         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1254           VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
1255
1256         unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1257         MVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1258         SmallVector<SDValue, 4> Parts(NumParts);
1259         getCopyToParts(DAG, getCurSDLoc(),
1260                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1261                        &Parts[0], NumParts, PartVT, &I, ExtendKind);
1262
1263         // 'inreg' on function refers to return value
1264         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1265         if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1266                                             Attribute::InReg))
1267           Flags.setInReg();
1268
1269         // Propagate extension type if any
1270         if (ExtendKind == ISD::SIGN_EXTEND)
1271           Flags.setSExt();
1272         else if (ExtendKind == ISD::ZERO_EXTEND)
1273           Flags.setZExt();
1274
1275         for (unsigned i = 0; i < NumParts; ++i) {
1276           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1277                                         VT, /*isfixed=*/true, 0, 0));
1278           OutVals.push_back(Parts[i]);
1279         }
1280       }
1281     }
1282   }
1283
1284   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1285   CallingConv::ID CallConv =
1286     DAG.getMachineFunction().getFunction()->getCallingConv();
1287   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1288       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1289
1290   // Verify that the target's LowerReturn behaved as expected.
1291   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1292          "LowerReturn didn't return a valid chain!");
1293
1294   // Update the DAG with the new chain value resulting from return lowering.
1295   DAG.setRoot(Chain);
1296 }
1297
1298 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1299 /// created for it, emit nodes to copy the value into the virtual
1300 /// registers.
1301 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1302   // Skip empty types
1303   if (V->getType()->isEmptyTy())
1304     return;
1305
1306   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1307   if (VMI != FuncInfo.ValueMap.end()) {
1308     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1309     CopyValueToVirtualRegister(V, VMI->second);
1310   }
1311 }
1312
1313 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1314 /// the current basic block, add it to ValueMap now so that we'll get a
1315 /// CopyTo/FromReg.
1316 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1317   // No need to export constants.
1318   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1319
1320   // Already exported?
1321   if (FuncInfo.isExportedInst(V)) return;
1322
1323   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1324   CopyValueToVirtualRegister(V, Reg);
1325 }
1326
1327 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1328                                                      const BasicBlock *FromBB) {
1329   // The operands of the setcc have to be in this block.  We don't know
1330   // how to export them from some other block.
1331   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1332     // Can export from current BB.
1333     if (VI->getParent() == FromBB)
1334       return true;
1335
1336     // Is already exported, noop.
1337     return FuncInfo.isExportedInst(V);
1338   }
1339
1340   // If this is an argument, we can export it if the BB is the entry block or
1341   // if it is already exported.
1342   if (isa<Argument>(V)) {
1343     if (FromBB == &FromBB->getParent()->getEntryBlock())
1344       return true;
1345
1346     // Otherwise, can only export this if it is already exported.
1347     return FuncInfo.isExportedInst(V);
1348   }
1349
1350   // Otherwise, constants can always be exported.
1351   return true;
1352 }
1353
1354 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1355 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1356                                             const MachineBasicBlock *Dst) const {
1357   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1358   if (!BPI)
1359     return 0;
1360   const BasicBlock *SrcBB = Src->getBasicBlock();
1361   const BasicBlock *DstBB = Dst->getBasicBlock();
1362   return BPI->getEdgeWeight(SrcBB, DstBB);
1363 }
1364
1365 void SelectionDAGBuilder::
1366 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1367                        uint32_t Weight /* = 0 */) {
1368   if (!Weight)
1369     Weight = getEdgeWeight(Src, Dst);
1370   Src->addSuccessor(Dst, Weight);
1371 }
1372
1373
1374 static bool InBlock(const Value *V, const BasicBlock *BB) {
1375   if (const Instruction *I = dyn_cast<Instruction>(V))
1376     return I->getParent() == BB;
1377   return true;
1378 }
1379
1380 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1381 /// This function emits a branch and is used at the leaves of an OR or an
1382 /// AND operator tree.
1383 ///
1384 void
1385 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1386                                                   MachineBasicBlock *TBB,
1387                                                   MachineBasicBlock *FBB,
1388                                                   MachineBasicBlock *CurBB,
1389                                                   MachineBasicBlock *SwitchBB,
1390                                                   uint32_t TWeight,
1391                                                   uint32_t FWeight) {
1392   const BasicBlock *BB = CurBB->getBasicBlock();
1393
1394   // If the leaf of the tree is a comparison, merge the condition into
1395   // the caseblock.
1396   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1397     // The operands of the cmp have to be in this block.  We don't know
1398     // how to export them from some other block.  If this is the first block
1399     // of the sequence, no exporting is needed.
1400     if (CurBB == SwitchBB ||
1401         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1402          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1403       ISD::CondCode Condition;
1404       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1405         Condition = getICmpCondCode(IC->getPredicate());
1406       } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1407         Condition = getFCmpCondCode(FC->getPredicate());
1408         if (TM.Options.NoNaNsFPMath)
1409           Condition = getFCmpCodeWithoutNaN(Condition);
1410       } else {
1411         Condition = ISD::SETEQ; // silence warning.
1412         llvm_unreachable("Unknown compare instruction");
1413       }
1414
1415       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1416                    TBB, FBB, CurBB, TWeight, FWeight);
1417       SwitchCases.push_back(CB);
1418       return;
1419     }
1420   }
1421
1422   // Create a CaseBlock record representing this branch.
1423   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1424                nullptr, TBB, FBB, CurBB, TWeight, FWeight);
1425   SwitchCases.push_back(CB);
1426 }
1427
1428 /// Scale down both weights to fit into uint32_t.
1429 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1430   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1431   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1432   NewTrue = NewTrue / Scale;
1433   NewFalse = NewFalse / Scale;
1434 }
1435
1436 /// FindMergedConditions - If Cond is an expression like
1437 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1438                                                MachineBasicBlock *TBB,
1439                                                MachineBasicBlock *FBB,
1440                                                MachineBasicBlock *CurBB,
1441                                                MachineBasicBlock *SwitchBB,
1442                                                unsigned Opc, uint32_t TWeight,
1443                                                uint32_t FWeight) {
1444   // If this node is not part of the or/and tree, emit it as a branch.
1445   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1446   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1447       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1448       BOp->getParent() != CurBB->getBasicBlock() ||
1449       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1450       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1451     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1452                                  TWeight, FWeight);
1453     return;
1454   }
1455
1456   //  Create TmpBB after CurBB.
1457   MachineFunction::iterator BBI = CurBB;
1458   MachineFunction &MF = DAG.getMachineFunction();
1459   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1460   CurBB->getParent()->insert(++BBI, TmpBB);
1461
1462   if (Opc == Instruction::Or) {
1463     // Codegen X | Y as:
1464     // BB1:
1465     //   jmp_if_X TBB
1466     //   jmp TmpBB
1467     // TmpBB:
1468     //   jmp_if_Y TBB
1469     //   jmp FBB
1470     //
1471
1472     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1473     // The requirement is that
1474     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1475     //     = TrueProb for orignal BB.
1476     // Assuming the orignal weights are A and B, one choice is to set BB1's
1477     // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1478     // assumes that
1479     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1480     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1481     // TmpBB, but the math is more complicated.
1482
1483     uint64_t NewTrueWeight = TWeight;
1484     uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1485     ScaleWeights(NewTrueWeight, NewFalseWeight);
1486     // Emit the LHS condition.
1487     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1488                          NewTrueWeight, NewFalseWeight);
1489
1490     NewTrueWeight = TWeight;
1491     NewFalseWeight = 2 * (uint64_t)FWeight;
1492     ScaleWeights(NewTrueWeight, NewFalseWeight);
1493     // Emit the RHS condition into TmpBB.
1494     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1495                          NewTrueWeight, NewFalseWeight);
1496   } else {
1497     assert(Opc == Instruction::And && "Unknown merge op!");
1498     // Codegen X & Y as:
1499     // BB1:
1500     //   jmp_if_X TmpBB
1501     //   jmp FBB
1502     // TmpBB:
1503     //   jmp_if_Y TBB
1504     //   jmp FBB
1505     //
1506     //  This requires creation of TmpBB after CurBB.
1507
1508     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1509     // The requirement is that
1510     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1511     //     = FalseProb for orignal BB.
1512     // Assuming the orignal weights are A and B, one choice is to set BB1's
1513     // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1514     // assumes that
1515     //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1516
1517     uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1518     uint64_t NewFalseWeight = FWeight;
1519     ScaleWeights(NewTrueWeight, NewFalseWeight);
1520     // Emit the LHS condition.
1521     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1522                          NewTrueWeight, NewFalseWeight);
1523
1524     NewTrueWeight = 2 * (uint64_t)TWeight;
1525     NewFalseWeight = FWeight;
1526     ScaleWeights(NewTrueWeight, NewFalseWeight);
1527     // Emit the RHS condition into TmpBB.
1528     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1529                          NewTrueWeight, NewFalseWeight);
1530   }
1531 }
1532
1533 /// If the set of cases should be emitted as a series of branches, return true.
1534 /// If we should emit this as a bunch of and/or'd together conditions, return
1535 /// false.
1536 bool
1537 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1538   if (Cases.size() != 2) return true;
1539
1540   // If this is two comparisons of the same values or'd or and'd together, they
1541   // will get folded into a single comparison, so don't emit two blocks.
1542   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1543        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1544       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1545        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1546     return false;
1547   }
1548
1549   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1550   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1551   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1552       Cases[0].CC == Cases[1].CC &&
1553       isa<Constant>(Cases[0].CmpRHS) &&
1554       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1555     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1556       return false;
1557     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1558       return false;
1559   }
1560
1561   return true;
1562 }
1563
1564 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1565   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1566
1567   // Update machine-CFG edges.
1568   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1569
1570   // Figure out which block is immediately after the current one.
1571   MachineBasicBlock *NextBlock = nullptr;
1572   MachineFunction::iterator BBI = BrMBB;
1573   if (++BBI != FuncInfo.MF->end())
1574     NextBlock = BBI;
1575
1576   if (I.isUnconditional()) {
1577     // Update machine-CFG edges.
1578     BrMBB->addSuccessor(Succ0MBB);
1579
1580     // If this is not a fall-through branch or optimizations are switched off,
1581     // emit the branch.
1582     if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
1583       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1584                               MVT::Other, getControlRoot(),
1585                               DAG.getBasicBlock(Succ0MBB)));
1586
1587     return;
1588   }
1589
1590   // If this condition is one of the special cases we handle, do special stuff
1591   // now.
1592   const Value *CondVal = I.getCondition();
1593   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1594
1595   // If this is a series of conditions that are or'd or and'd together, emit
1596   // this as a sequence of branches instead of setcc's with and/or operations.
1597   // As long as jumps are not expensive, this should improve performance.
1598   // For example, instead of something like:
1599   //     cmp A, B
1600   //     C = seteq
1601   //     cmp D, E
1602   //     F = setle
1603   //     or C, F
1604   //     jnz foo
1605   // Emit:
1606   //     cmp A, B
1607   //     je foo
1608   //     cmp D, E
1609   //     jle foo
1610   //
1611   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1612     if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
1613         BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1614                              BOp->getOpcode() == Instruction::Or)) {
1615       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1616                            BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1617                            getEdgeWeight(BrMBB, Succ1MBB));
1618       // If the compares in later blocks need to use values not currently
1619       // exported from this block, export them now.  This block should always
1620       // be the first entry.
1621       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1622
1623       // Allow some cases to be rejected.
1624       if (ShouldEmitAsBranches(SwitchCases)) {
1625         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1626           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1627           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1628         }
1629
1630         // Emit the branch for this block.
1631         visitSwitchCase(SwitchCases[0], BrMBB);
1632         SwitchCases.erase(SwitchCases.begin());
1633         return;
1634       }
1635
1636       // Okay, we decided not to do this, remove any inserted MBB's and clear
1637       // SwitchCases.
1638       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1639         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1640
1641       SwitchCases.clear();
1642     }
1643   }
1644
1645   // Create a CaseBlock record representing this branch.
1646   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1647                nullptr, Succ0MBB, Succ1MBB, BrMBB);
1648
1649   // Use visitSwitchCase to actually insert the fast branch sequence for this
1650   // cond branch.
1651   visitSwitchCase(CB, BrMBB);
1652 }
1653
1654 /// visitSwitchCase - Emits the necessary code to represent a single node in
1655 /// the binary search tree resulting from lowering a switch instruction.
1656 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1657                                           MachineBasicBlock *SwitchBB) {
1658   SDValue Cond;
1659   SDValue CondLHS = getValue(CB.CmpLHS);
1660   SDLoc dl = getCurSDLoc();
1661
1662   // Build the setcc now.
1663   if (!CB.CmpMHS) {
1664     // Fold "(X == true)" to X and "(X == false)" to !X to
1665     // handle common cases produced by branch lowering.
1666     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1667         CB.CC == ISD::SETEQ)
1668       Cond = CondLHS;
1669     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1670              CB.CC == ISD::SETEQ) {
1671       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1672       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1673     } else
1674       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1675   } else {
1676     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1677
1678     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1679     const APInt& High  = cast<ConstantInt>(CB.CmpRHS)->getValue();
1680
1681     SDValue CmpOp = getValue(CB.CmpMHS);
1682     EVT VT = CmpOp.getValueType();
1683
1684     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1685       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1686                           ISD::SETLE);
1687     } else {
1688       SDValue SUB = DAG.getNode(ISD::SUB, dl,
1689                                 VT, CmpOp, DAG.getConstant(Low, VT));
1690       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1691                           DAG.getConstant(High-Low, VT), ISD::SETULE);
1692     }
1693   }
1694
1695   // Update successor info
1696   addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1697   // TrueBB and FalseBB are always different unless the incoming IR is
1698   // degenerate. This only happens when running llc on weird IR.
1699   if (CB.TrueBB != CB.FalseBB)
1700     addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1701
1702   // Set NextBlock to be the MBB immediately after the current one, if any.
1703   // This is used to avoid emitting unnecessary branches to the next block.
1704   MachineBasicBlock *NextBlock = nullptr;
1705   MachineFunction::iterator BBI = SwitchBB;
1706   if (++BBI != FuncInfo.MF->end())
1707     NextBlock = BBI;
1708
1709   // If the lhs block is the next block, invert the condition so that we can
1710   // fall through to the lhs instead of the rhs block.
1711   if (CB.TrueBB == NextBlock) {
1712     std::swap(CB.TrueBB, CB.FalseBB);
1713     SDValue True = DAG.getConstant(1, Cond.getValueType());
1714     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1715   }
1716
1717   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1718                                MVT::Other, getControlRoot(), Cond,
1719                                DAG.getBasicBlock(CB.TrueBB));
1720
1721   // Insert the false branch. Do this even if it's a fall through branch,
1722   // this makes it easier to do DAG optimizations which require inverting
1723   // the branch condition.
1724   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1725                        DAG.getBasicBlock(CB.FalseBB));
1726
1727   DAG.setRoot(BrCond);
1728 }
1729
1730 /// visitJumpTable - Emit JumpTable node in the current MBB
1731 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1732   // Emit the code for the jump table
1733   assert(JT.Reg != -1U && "Should lower JT Header first!");
1734   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
1735   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1736                                      JT.Reg, PTy);
1737   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1738   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1739                                     MVT::Other, Index.getValue(1),
1740                                     Table, Index);
1741   DAG.setRoot(BrJumpTable);
1742 }
1743
1744 /// visitJumpTableHeader - This function emits necessary code to produce index
1745 /// in the JumpTable from switch case.
1746 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1747                                                JumpTableHeader &JTH,
1748                                                MachineBasicBlock *SwitchBB) {
1749   // Subtract the lowest switch case value from the value being switched on and
1750   // conditional branch to default mbb if the result is greater than the
1751   // difference between smallest and largest cases.
1752   SDValue SwitchOp = getValue(JTH.SValue);
1753   EVT VT = SwitchOp.getValueType();
1754   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1755                             DAG.getConstant(JTH.First, VT));
1756
1757   // The SDNode we just created, which holds the value being switched on minus
1758   // the smallest case value, needs to be copied to a virtual register so it
1759   // can be used as an index into the jump table in a subsequent basic block.
1760   // This value may be smaller or larger than the target's pointer type, and
1761   // therefore require extension or truncating.
1762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1763   SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
1764
1765   unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1766   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1767                                     JumpTableReg, SwitchOp);
1768   JT.Reg = JumpTableReg;
1769
1770   // Emit the range check for the jump table, and branch to the default block
1771   // for the switch statement if the value being switched on exceeds the largest
1772   // case in the switch.
1773   SDValue CMP =
1774       DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1775                                                          Sub.getValueType()),
1776                    Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
1777
1778   // Set NextBlock to be the MBB immediately after the current one, if any.
1779   // This is used to avoid emitting unnecessary branches to the next block.
1780   MachineBasicBlock *NextBlock = nullptr;
1781   MachineFunction::iterator BBI = SwitchBB;
1782
1783   if (++BBI != FuncInfo.MF->end())
1784     NextBlock = BBI;
1785
1786   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1787                                MVT::Other, CopyTo, CMP,
1788                                DAG.getBasicBlock(JT.Default));
1789
1790   if (JT.MBB != NextBlock)
1791     BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1792                          DAG.getBasicBlock(JT.MBB));
1793
1794   DAG.setRoot(BrCond);
1795 }
1796
1797 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1798 /// tail spliced into a stack protector check success bb.
1799 ///
1800 /// For a high level explanation of how this fits into the stack protector
1801 /// generation see the comment on the declaration of class
1802 /// StackProtectorDescriptor.
1803 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1804                                                   MachineBasicBlock *ParentBB) {
1805
1806   // First create the loads to the guard/stack slot for the comparison.
1807   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1808   EVT PtrTy = TLI.getPointerTy();
1809
1810   MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1811   int FI = MFI->getStackProtectorIndex();
1812
1813   const Value *IRGuard = SPD.getGuard();
1814   SDValue GuardPtr = getValue(IRGuard);
1815   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1816
1817   unsigned Align =
1818     TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1819
1820   SDValue Guard;
1821
1822   // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1823   // guard value from the virtual register holding the value. Otherwise, emit a
1824   // volatile load to retrieve the stack guard value.
1825   unsigned GuardReg = SPD.getGuardReg();
1826
1827   if (GuardReg && TLI.useLoadStackGuardNode())
1828     Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
1829                                PtrTy);
1830   else
1831     Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1832                         GuardPtr, MachinePointerInfo(IRGuard, 0),
1833                         true, false, false, Align);
1834
1835   SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1836                                   StackSlotPtr,
1837                                   MachinePointerInfo::getFixedStack(FI),
1838                                   true, false, false, Align);
1839
1840   // Perform the comparison via a subtract/getsetcc.
1841   EVT VT = Guard.getValueType();
1842   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1843
1844   SDValue Cmp =
1845       DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1846                                                          Sub.getValueType()),
1847                    Sub, DAG.getConstant(0, VT), ISD::SETNE);
1848
1849   // If the sub is not 0, then we know the guard/stackslot do not equal, so
1850   // branch to failure MBB.
1851   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1852                                MVT::Other, StackSlot.getOperand(0),
1853                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1854   // Otherwise branch to success MBB.
1855   SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1856                            MVT::Other, BrCond,
1857                            DAG.getBasicBlock(SPD.getSuccessMBB()));
1858
1859   DAG.setRoot(Br);
1860 }
1861
1862 /// Codegen the failure basic block for a stack protector check.
1863 ///
1864 /// A failure stack protector machine basic block consists simply of a call to
1865 /// __stack_chk_fail().
1866 ///
1867 /// For a high level explanation of how this fits into the stack protector
1868 /// generation see the comment on the declaration of class
1869 /// StackProtectorDescriptor.
1870 void
1871 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1872   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1873   SDValue Chain =
1874       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1875                       nullptr, 0, false, getCurSDLoc(), false, false).second;
1876   DAG.setRoot(Chain);
1877 }
1878
1879 /// visitBitTestHeader - This function emits necessary code to produce value
1880 /// suitable for "bit tests"
1881 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1882                                              MachineBasicBlock *SwitchBB) {
1883   // Subtract the minimum value
1884   SDValue SwitchOp = getValue(B.SValue);
1885   EVT VT = SwitchOp.getValueType();
1886   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1887                             DAG.getConstant(B.First, VT));
1888
1889   // Check range
1890   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1891   SDValue RangeCmp =
1892       DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1893                                                          Sub.getValueType()),
1894                    Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
1895
1896   // Determine the type of the test operands.
1897   bool UsePtrType = false;
1898   if (!TLI.isTypeLegal(VT))
1899     UsePtrType = true;
1900   else {
1901     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1902       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1903         // Switch table case range are encoded into series of masks.
1904         // Just use pointer type, it's guaranteed to fit.
1905         UsePtrType = true;
1906         break;
1907       }
1908   }
1909   if (UsePtrType) {
1910     VT = TLI.getPointerTy();
1911     Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1912   }
1913
1914   B.RegVT = VT.getSimpleVT();
1915   B.Reg = FuncInfo.CreateReg(B.RegVT);
1916   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1917                                     B.Reg, Sub);
1918
1919   // Set NextBlock to be the MBB immediately after the current one, if any.
1920   // This is used to avoid emitting unnecessary branches to the next block.
1921   MachineBasicBlock *NextBlock = nullptr;
1922   MachineFunction::iterator BBI = SwitchBB;
1923   if (++BBI != FuncInfo.MF->end())
1924     NextBlock = BBI;
1925
1926   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1927
1928   addSuccessorWithWeight(SwitchBB, B.Default);
1929   addSuccessorWithWeight(SwitchBB, MBB);
1930
1931   SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1932                                 MVT::Other, CopyTo, RangeCmp,
1933                                 DAG.getBasicBlock(B.Default));
1934
1935   if (MBB != NextBlock)
1936     BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1937                           DAG.getBasicBlock(MBB));
1938
1939   DAG.setRoot(BrRange);
1940 }
1941
1942 /// visitBitTestCase - this function produces one "bit test"
1943 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1944                                            MachineBasicBlock* NextMBB,
1945                                            uint32_t BranchWeightToNext,
1946                                            unsigned Reg,
1947                                            BitTestCase &B,
1948                                            MachineBasicBlock *SwitchBB) {
1949   MVT VT = BB.RegVT;
1950   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1951                                        Reg, VT);
1952   SDValue Cmp;
1953   unsigned PopCount = CountPopulation_64(B.Mask);
1954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1955   if (PopCount == 1) {
1956     // Testing for a single bit; just compare the shift count with what it
1957     // would need to be to shift a 1 bit in that position.
1958     Cmp = DAG.getSetCC(
1959         getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1960         DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
1961   } else if (PopCount == BB.Range) {
1962     // There is only one zero bit in the range, test for it directly.
1963     Cmp = DAG.getSetCC(
1964         getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1965         DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), ISD::SETNE);
1966   } else {
1967     // Make desired shift
1968     SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1969                                     DAG.getConstant(1, VT), ShiftOp);
1970
1971     // Emit bit tests and jumps
1972     SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1973                                 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1974     Cmp = DAG.getSetCC(getCurSDLoc(),
1975                        TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1976                        DAG.getConstant(0, VT), ISD::SETNE);
1977   }
1978
1979   // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1980   addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1981   // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1982   addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1983
1984   SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1985                               MVT::Other, getControlRoot(),
1986                               Cmp, DAG.getBasicBlock(B.TargetBB));
1987
1988   // Set NextBlock to be the MBB immediately after the current one, if any.
1989   // This is used to avoid emitting unnecessary branches to the next block.
1990   MachineBasicBlock *NextBlock = nullptr;
1991   MachineFunction::iterator BBI = SwitchBB;
1992   if (++BBI != FuncInfo.MF->end())
1993     NextBlock = BBI;
1994
1995   if (NextMBB != NextBlock)
1996     BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
1997                         DAG.getBasicBlock(NextMBB));
1998
1999   DAG.setRoot(BrAnd);
2000 }
2001
2002 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2003   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2004
2005   // Retrieve successors.
2006   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2007   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2008
2009   const Value *Callee(I.getCalledValue());
2010   const Function *Fn = dyn_cast<Function>(Callee);
2011   if (isa<InlineAsm>(Callee))
2012     visitInlineAsm(&I);
2013   else if (Fn && Fn->isIntrinsic()) {
2014     switch (Fn->getIntrinsicID()) {
2015     default:
2016       llvm_unreachable("Cannot invoke this intrinsic");
2017     case Intrinsic::donothing:
2018       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2019       break;
2020     case Intrinsic::experimental_patchpoint_void:
2021     case Intrinsic::experimental_patchpoint_i64:
2022       visitPatchpoint(&I, LandingPad);
2023       break;
2024     }
2025   } else
2026     LowerCallTo(&I, getValue(Callee), false, LandingPad);
2027
2028   // If the value of the invoke is used outside of its defining block, make it
2029   // available as a virtual register.
2030   CopyToExportRegsIfNeeded(&I);
2031
2032   // Update successor info
2033   addSuccessorWithWeight(InvokeMBB, Return);
2034   addSuccessorWithWeight(InvokeMBB, LandingPad);
2035
2036   // Drop into normal successor.
2037   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2038                           MVT::Other, getControlRoot(),
2039                           DAG.getBasicBlock(Return)));
2040 }
2041
2042 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2043   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2044 }
2045
2046 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2047   assert(FuncInfo.MBB->isLandingPad() &&
2048          "Call to landingpad not in landing pad!");
2049
2050   MachineBasicBlock *MBB = FuncInfo.MBB;
2051   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2052   AddLandingPadInfo(LP, MMI, MBB);
2053
2054   // If there aren't registers to copy the values into (e.g., during SjLj
2055   // exceptions), then don't bother to create these DAG nodes.
2056   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2057   if (TLI.getExceptionPointerRegister() == 0 &&
2058       TLI.getExceptionSelectorRegister() == 0)
2059     return;
2060
2061   SmallVector<EVT, 2> ValueVTs;
2062   ComputeValueVTs(TLI, LP.getType(), ValueVTs);
2063   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2064
2065   // Get the two live-in registers as SDValues. The physregs have already been
2066   // copied into virtual registers.
2067   SDValue Ops[2];
2068   Ops[0] = DAG.getZExtOrTrunc(
2069       DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2070                          FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2071       getCurSDLoc(), ValueVTs[0]);
2072   Ops[1] = DAG.getZExtOrTrunc(
2073       DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2074                          FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
2075       getCurSDLoc(), ValueVTs[1]);
2076
2077   // Merge into one.
2078   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2079                             DAG.getVTList(ValueVTs), Ops);
2080   setValue(&LP, Res);
2081 }
2082
2083 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2084 /// small case ranges).
2085 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2086                                                  CaseRecVector& WorkList,
2087                                                  const Value* SV,
2088                                                  MachineBasicBlock *Default,
2089                                                  MachineBasicBlock *SwitchBB) {
2090   // Size is the number of Cases represented by this range.
2091   size_t Size = CR.Range.second - CR.Range.first;
2092   if (Size > 3)
2093     return false;
2094
2095   // Get the MachineFunction which holds the current MBB.  This is used when
2096   // inserting any additional MBBs necessary to represent the switch.
2097   MachineFunction *CurMF = FuncInfo.MF;
2098
2099   // Figure out which block is immediately after the current one.
2100   MachineBasicBlock *NextBlock = nullptr;
2101   MachineFunction::iterator BBI = CR.CaseBB;
2102
2103   if (++BBI != FuncInfo.MF->end())
2104     NextBlock = BBI;
2105
2106   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2107   // If any two of the cases has the same destination, and if one value
2108   // is the same as the other, but has one bit unset that the other has set,
2109   // use bit manipulation to do two compares at once.  For example:
2110   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2111   // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2112   // TODO: Handle cases where CR.CaseBB != SwitchBB.
2113   if (Size == 2 && CR.CaseBB == SwitchBB) {
2114     Case &Small = *CR.Range.first;
2115     Case &Big = *(CR.Range.second-1);
2116
2117     if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2118       const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2119       const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2120
2121       // Check that there is only one bit different.
2122       if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2123           (SmallValue | BigValue) == BigValue) {
2124         // Isolate the common bit.
2125         APInt CommonBit = BigValue & ~SmallValue;
2126         assert((SmallValue | CommonBit) == BigValue &&
2127                CommonBit.countPopulation() == 1 && "Not a common bit?");
2128
2129         SDValue CondLHS = getValue(SV);
2130         EVT VT = CondLHS.getValueType();
2131         SDLoc DL = getCurSDLoc();
2132
2133         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2134                                  DAG.getConstant(CommonBit, VT));
2135         SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2136                                     Or, DAG.getConstant(BigValue, VT),
2137                                     ISD::SETEQ);
2138
2139         // Update successor info.
2140         // Both Small and Big will jump to Small.BB, so we sum up the weights.
2141         addSuccessorWithWeight(SwitchBB, Small.BB,
2142                                Small.ExtraWeight + Big.ExtraWeight);
2143         addSuccessorWithWeight(SwitchBB, Default,
2144           // The default destination is the first successor in IR.
2145           BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2146
2147         // Insert the true branch.
2148         SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2149                                      getControlRoot(), Cond,
2150                                      DAG.getBasicBlock(Small.BB));
2151
2152         // Insert the false branch.
2153         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2154                              DAG.getBasicBlock(Default));
2155
2156         DAG.setRoot(BrCond);
2157         return true;
2158       }
2159     }
2160   }
2161
2162   // Order cases by weight so the most likely case will be checked first.
2163   uint32_t UnhandledWeights = 0;
2164   if (BPI) {
2165     for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2166       uint32_t IWeight = I->ExtraWeight;
2167       UnhandledWeights += IWeight;
2168       for (CaseItr J = CR.Range.first; J < I; ++J) {
2169         uint32_t JWeight = J->ExtraWeight;
2170         if (IWeight > JWeight)
2171           std::swap(*I, *J);
2172       }
2173     }
2174   }
2175   // Rearrange the case blocks so that the last one falls through if possible.
2176   Case &BackCase = *(CR.Range.second-1);
2177   if (Size > 1 &&
2178       NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2179     // The last case block won't fall through into 'NextBlock' if we emit the
2180     // branches in this order.  See if rearranging a case value would help.
2181     // We start at the bottom as it's the case with the least weight.
2182     for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2183       if (I->BB == NextBlock) {
2184         std::swap(*I, BackCase);
2185         break;
2186       }
2187   }
2188
2189   // Create a CaseBlock record representing a conditional branch to
2190   // the Case's target mbb if the value being switched on SV is equal
2191   // to C.
2192   MachineBasicBlock *CurBlock = CR.CaseBB;
2193   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2194     MachineBasicBlock *FallThrough;
2195     if (I != E-1) {
2196       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2197       CurMF->insert(BBI, FallThrough);
2198
2199       // Put SV in a virtual register to make it available from the new blocks.
2200       ExportFromCurrentBlock(SV);
2201     } else {
2202       // If the last case doesn't match, go to the default block.
2203       FallThrough = Default;
2204     }
2205
2206     const Value *RHS, *LHS, *MHS;
2207     ISD::CondCode CC;
2208     if (I->High == I->Low) {
2209       // This is just small small case range :) containing exactly 1 case
2210       CC = ISD::SETEQ;
2211       LHS = SV; RHS = I->High; MHS = nullptr;
2212     } else {
2213       CC = ISD::SETLE;
2214       LHS = I->Low; MHS = SV; RHS = I->High;
2215     }
2216
2217     // The false weight should be sum of all un-handled cases.
2218     UnhandledWeights -= I->ExtraWeight;
2219     CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2220                  /* me */ CurBlock,
2221                  /* trueweight */ I->ExtraWeight,
2222                  /* falseweight */ UnhandledWeights);
2223
2224     // If emitting the first comparison, just call visitSwitchCase to emit the
2225     // code into the current block.  Otherwise, push the CaseBlock onto the
2226     // vector to be later processed by SDISel, and insert the node's MBB
2227     // before the next MBB.
2228     if (CurBlock == SwitchBB)
2229       visitSwitchCase(CB, SwitchBB);
2230     else
2231       SwitchCases.push_back(CB);
2232
2233     CurBlock = FallThrough;
2234   }
2235
2236   return true;
2237 }
2238
2239 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2240   return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2241          TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
2242 }
2243
2244 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2245   uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2246   APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2247   return (LastExt - FirstExt + 1ULL);
2248 }
2249
2250 /// handleJTSwitchCase - Emit jumptable for current switch case range
2251 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2252                                              CaseRecVector &WorkList,
2253                                              const Value *SV,
2254                                              MachineBasicBlock *Default,
2255                                              MachineBasicBlock *SwitchBB) {
2256   Case& FrontCase = *CR.Range.first;
2257   Case& BackCase  = *(CR.Range.second-1);
2258
2259   const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2260   const APInt &Last  = cast<ConstantInt>(BackCase.High)->getValue();
2261
2262   APInt TSize(First.getBitWidth(), 0);
2263   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2264     TSize += I->size();
2265
2266   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2267   if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
2268     return false;
2269
2270   APInt Range = ComputeRange(First, Last);
2271   // The density is TSize / Range. Require at least 40%.
2272   // It should not be possible for IntTSize to saturate for sane code, but make
2273   // sure we handle Range saturation correctly.
2274   uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2275   uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2276   if (IntTSize * 10 < IntRange * 4)
2277     return false;
2278
2279   DEBUG(dbgs() << "Lowering jump table\n"
2280                << "First entry: " << First << ". Last entry: " << Last << '\n'
2281                << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2282
2283   // Get the MachineFunction which holds the current MBB.  This is used when
2284   // inserting any additional MBBs necessary to represent the switch.
2285   MachineFunction *CurMF = FuncInfo.MF;
2286
2287   // Figure out which block is immediately after the current one.
2288   MachineFunction::iterator BBI = CR.CaseBB;
2289   ++BBI;
2290
2291   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2292
2293   // Create a new basic block to hold the code for loading the address
2294   // of the jump table, and jumping to it.  Update successor information;
2295   // we will either branch to the default case for the switch, or the jump
2296   // table.
2297   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2298   CurMF->insert(BBI, JumpTableBB);
2299
2300   addSuccessorWithWeight(CR.CaseBB, Default);
2301   addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2302
2303   // Build a vector of destination BBs, corresponding to each target
2304   // of the jump table. If the value of the jump table slot corresponds to
2305   // a case statement, push the case's BB onto the vector, otherwise, push
2306   // the default BB.
2307   std::vector<MachineBasicBlock*> DestBBs;
2308   APInt TEI = First;
2309   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2310     const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2311     const APInt &High = cast<ConstantInt>(I->High)->getValue();
2312
2313     if (Low.sle(TEI) && TEI.sle(High)) {
2314       DestBBs.push_back(I->BB);
2315       if (TEI==High)
2316         ++I;
2317     } else {
2318       DestBBs.push_back(Default);
2319     }
2320   }
2321
2322   // Calculate weight for each unique destination in CR.
2323   DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2324   if (FuncInfo.BPI)
2325     for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2326       DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2327           DestWeights.find(I->BB);
2328       if (Itr != DestWeights.end())
2329         Itr->second += I->ExtraWeight;
2330       else
2331         DestWeights[I->BB] = I->ExtraWeight;
2332     }
2333
2334   // Update successor info. Add one edge to each unique successor.
2335   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2336   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2337          E = DestBBs.end(); I != E; ++I) {
2338     if (!SuccsHandled[(*I)->getNumber()]) {
2339       SuccsHandled[(*I)->getNumber()] = true;
2340       DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2341           DestWeights.find(*I);
2342       addSuccessorWithWeight(JumpTableBB, *I,
2343                              Itr != DestWeights.end() ? Itr->second : 0);
2344     }
2345   }
2346
2347   // Create a jump table index for this jump table.
2348   unsigned JTEncoding = TLI.getJumpTableEncoding();
2349   unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2350                        ->createJumpTableIndex(DestBBs);
2351
2352   // Set the jump table information so that we can codegen it as a second
2353   // MachineBasicBlock
2354   JumpTable JT(-1U, JTI, JumpTableBB, Default);
2355   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2356   if (CR.CaseBB == SwitchBB)
2357     visitJumpTableHeader(JT, JTH, SwitchBB);
2358
2359   JTCases.push_back(JumpTableBlock(JTH, JT));
2360   return true;
2361 }
2362
2363 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2364 /// 2 subtrees.
2365 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2366                                                   CaseRecVector& WorkList,
2367                                                   const Value* SV,
2368                                                   MachineBasicBlock* SwitchBB) {
2369   // Get the MachineFunction which holds the current MBB.  This is used when
2370   // inserting any additional MBBs necessary to represent the switch.
2371   MachineFunction *CurMF = FuncInfo.MF;
2372
2373   // Figure out which block is immediately after the current one.
2374   MachineFunction::iterator BBI = CR.CaseBB;
2375   ++BBI;
2376
2377   Case& FrontCase = *CR.Range.first;
2378   Case& BackCase  = *(CR.Range.second-1);
2379   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2380
2381   // Size is the number of Cases represented by this range.
2382   unsigned Size = CR.Range.second - CR.Range.first;
2383
2384   const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2385   const APInt &Last  = cast<ConstantInt>(BackCase.High)->getValue();
2386   double FMetric = 0;
2387   CaseItr Pivot = CR.Range.first + Size/2;
2388
2389   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2390   // (heuristically) allow us to emit JumpTable's later.
2391   APInt TSize(First.getBitWidth(), 0);
2392   for (CaseItr I = CR.Range.first, E = CR.Range.second;
2393        I!=E; ++I)
2394     TSize += I->size();
2395
2396   APInt LSize = FrontCase.size();
2397   APInt RSize = TSize-LSize;
2398   DEBUG(dbgs() << "Selecting best pivot: \n"
2399                << "First: " << First << ", Last: " << Last <<'\n'
2400                << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2401   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2402        J!=E; ++I, ++J) {
2403     const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2404     const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2405     APInt Range = ComputeRange(LEnd, RBegin);
2406     assert((Range - 2ULL).isNonNegative() &&
2407            "Invalid case distance");
2408     // Use volatile double here to avoid excess precision issues on some hosts,
2409     // e.g. that use 80-bit X87 registers.
2410     volatile double LDensity =
2411        (double)LSize.roundToDouble() /
2412                            (LEnd - First + 1ULL).roundToDouble();
2413     volatile double RDensity =
2414       (double)RSize.roundToDouble() /
2415                            (Last - RBegin + 1ULL).roundToDouble();
2416     volatile double Metric = Range.logBase2()*(LDensity+RDensity);
2417     // Should always split in some non-trivial place
2418     DEBUG(dbgs() <<"=>Step\n"
2419                  << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2420                  << "LDensity: " << LDensity
2421                  << ", RDensity: " << RDensity << '\n'
2422                  << "Metric: " << Metric << '\n');
2423     if (FMetric < Metric) {
2424       Pivot = J;
2425       FMetric = Metric;
2426       DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2427     }
2428
2429     LSize += J->size();
2430     RSize -= J->size();
2431   }
2432
2433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2434   if (areJTsAllowed(TLI)) {
2435     // If our case is dense we *really* should handle it earlier!
2436     assert((FMetric > 0) && "Should handle dense range earlier!");
2437   } else {
2438     Pivot = CR.Range.first + Size/2;
2439   }
2440
2441   CaseRange LHSR(CR.Range.first, Pivot);
2442   CaseRange RHSR(Pivot, CR.Range.second);
2443   const Constant *C = Pivot->Low;
2444   MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
2445
2446   // We know that we branch to the LHS if the Value being switched on is
2447   // less than the Pivot value, C.  We use this to optimize our binary
2448   // tree a bit, by recognizing that if SV is greater than or equal to the
2449   // LHS's Case Value, and that Case Value is exactly one less than the
2450   // Pivot's Value, then we can branch directly to the LHS's Target,
2451   // rather than creating a leaf node for it.
2452   if ((LHSR.second - LHSR.first) == 1 &&
2453       LHSR.first->High == CR.GE &&
2454       cast<ConstantInt>(C)->getValue() ==
2455       (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2456     TrueBB = LHSR.first->BB;
2457   } else {
2458     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2459     CurMF->insert(BBI, TrueBB);
2460     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2461
2462     // Put SV in a virtual register to make it available from the new blocks.
2463     ExportFromCurrentBlock(SV);
2464   }
2465
2466   // Similar to the optimization above, if the Value being switched on is
2467   // known to be less than the Constant CR.LT, and the current Case Value
2468   // is CR.LT - 1, then we can branch directly to the target block for
2469   // the current Case Value, rather than emitting a RHS leaf node for it.
2470   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2471       cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2472       (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2473     FalseBB = RHSR.first->BB;
2474   } else {
2475     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2476     CurMF->insert(BBI, FalseBB);
2477     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2478
2479     // Put SV in a virtual register to make it available from the new blocks.
2480     ExportFromCurrentBlock(SV);
2481   }
2482
2483   // Create a CaseBlock record representing a conditional branch to
2484   // the LHS node if the value being switched on SV is less than C.
2485   // Otherwise, branch to LHS.
2486   CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
2487
2488   if (CR.CaseBB == SwitchBB)
2489     visitSwitchCase(CB, SwitchBB);
2490   else
2491     SwitchCases.push_back(CB);
2492
2493   return true;
2494 }
2495
2496 /// handleBitTestsSwitchCase - if current case range has few destination and
2497 /// range span less, than machine word bitwidth, encode case range into series
2498 /// of masks and emit bit tests with these masks.
2499 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2500                                                    CaseRecVector& WorkList,
2501                                                    const Value* SV,
2502                                                    MachineBasicBlock* Default,
2503                                                    MachineBasicBlock* SwitchBB) {
2504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2505   EVT PTy = TLI.getPointerTy();
2506   unsigned IntPtrBits = PTy.getSizeInBits();
2507
2508   Case& FrontCase = *CR.Range.first;
2509   Case& BackCase  = *(CR.Range.second-1);
2510
2511   // Get the MachineFunction which holds the current MBB.  This is used when
2512   // inserting any additional MBBs necessary to represent the switch.
2513   MachineFunction *CurMF = FuncInfo.MF;
2514
2515   // If target does not have legal shift left, do not emit bit tests at all.
2516   if (!TLI.isOperationLegal(ISD::SHL, PTy))
2517     return false;
2518
2519   size_t numCmps = 0;
2520   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2521     // Single case counts one, case range - two.
2522     numCmps += (I->Low == I->High ? 1 : 2);
2523   }
2524
2525   // Count unique destinations
2526   SmallSet<MachineBasicBlock*, 4> Dests;
2527   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2528     Dests.insert(I->BB);
2529     if (Dests.size() > 3)
2530       // Don't bother the code below, if there are too much unique destinations
2531       return false;
2532   }
2533   DEBUG(dbgs() << "Total number of unique destinations: "
2534         << Dests.size() << '\n'
2535         << "Total number of comparisons: " << numCmps << '\n');
2536
2537   // Compute span of values.
2538   const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2539   const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2540   APInt cmpRange = maxValue - minValue;
2541
2542   DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2543                << "Low bound: " << minValue << '\n'
2544                << "High bound: " << maxValue << '\n');
2545
2546   if (cmpRange.uge(IntPtrBits) ||
2547       (!(Dests.size() == 1 && numCmps >= 3) &&
2548        !(Dests.size() == 2 && numCmps >= 5) &&
2549        !(Dests.size() >= 3 && numCmps >= 6)))
2550     return false;
2551
2552   DEBUG(dbgs() << "Emitting bit tests\n");
2553   APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2554
2555   // Optimize the case where all the case values fit in a
2556   // word without having to subtract minValue. In this case,
2557   // we can optimize away the subtraction.
2558   if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2559     cmpRange = maxValue;
2560   } else {
2561     lowBound = minValue;
2562   }
2563
2564   CaseBitsVector CasesBits;
2565   unsigned i, count = 0;
2566
2567   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2568     MachineBasicBlock* Dest = I->BB;
2569     for (i = 0; i < count; ++i)
2570       if (Dest == CasesBits[i].BB)
2571         break;
2572
2573     if (i == count) {
2574       assert((count < 3) && "Too much destinations to test!");
2575       CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2576       count++;
2577     }
2578
2579     const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2580     const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2581
2582     uint64_t lo = (lowValue - lowBound).getZExtValue();
2583     uint64_t hi = (highValue - lowBound).getZExtValue();
2584     CasesBits[i].ExtraWeight += I->ExtraWeight;
2585
2586     for (uint64_t j = lo; j <= hi; j++) {
2587       CasesBits[i].Mask |=  1ULL << j;
2588       CasesBits[i].Bits++;
2589     }
2590
2591   }
2592   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2593
2594   BitTestInfo BTC;
2595
2596   // Figure out which block is immediately after the current one.
2597   MachineFunction::iterator BBI = CR.CaseBB;
2598   ++BBI;
2599
2600   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2601
2602   DEBUG(dbgs() << "Cases:\n");
2603   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2604     DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2605                  << ", Bits: " << CasesBits[i].Bits
2606                  << ", BB: " << CasesBits[i].BB << '\n');
2607
2608     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2609     CurMF->insert(BBI, CaseBB);
2610     BTC.push_back(BitTestCase(CasesBits[i].Mask,
2611                               CaseBB,
2612                               CasesBits[i].BB, CasesBits[i].ExtraWeight));
2613
2614     // Put SV in a virtual register to make it available from the new blocks.
2615     ExportFromCurrentBlock(SV);
2616   }
2617
2618   BitTestBlock BTB(lowBound, cmpRange, SV,
2619                    -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2620                    CR.CaseBB, Default, std::move(BTC));
2621
2622   if (CR.CaseBB == SwitchBB)
2623     visitBitTestHeader(BTB, SwitchBB);
2624
2625   BitTestCases.push_back(std::move(BTB));
2626
2627   return true;
2628 }
2629
2630 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2631 void SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2632                                      const SwitchInst& SI) {
2633   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2634   // Start with "simple" cases.
2635   for (SwitchInst::ConstCaseIt i : SI.cases()) {
2636     const BasicBlock *SuccBB = i.getCaseSuccessor();
2637     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2638
2639     uint32_t ExtraWeight =
2640       BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2641
2642     Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2643                          SMBB, ExtraWeight));
2644   }
2645   std::sort(Cases.begin(), Cases.end(), CaseCmp());
2646
2647   // Merge case into clusters
2648   if (Cases.size() >= 2)
2649     // Must recompute end() each iteration because it may be
2650     // invalidated by erase if we hold on to it
2651     for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
2652          J != Cases.end(); ) {
2653       const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2654       const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2655       MachineBasicBlock* nextBB = J->BB;
2656       MachineBasicBlock* currentBB = I->BB;
2657
2658       // If the two neighboring cases go to the same destination, merge them
2659       // into a single case.
2660       if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2661         I->High = J->High;
2662         I->ExtraWeight += J->ExtraWeight;
2663         J = Cases.erase(J);
2664       } else {
2665         I = J++;
2666       }
2667     }
2668
2669   DEBUG({
2670       size_t numCmps = 0;
2671       for (auto &I : Cases)
2672         // A range counts double, since it requires two compares.
2673         numCmps += I.Low != I.High ? 2 : 1;
2674
2675       dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2676              << ". Total compares: " << numCmps << '\n';
2677     });
2678 }
2679
2680 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2681                                            MachineBasicBlock *Last) {
2682   // Update JTCases.
2683   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2684     if (JTCases[i].first.HeaderBB == First)
2685       JTCases[i].first.HeaderBB = Last;
2686
2687   // Update BitTestCases.
2688   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2689     if (BitTestCases[i].Parent == First)
2690       BitTestCases[i].Parent = Last;
2691 }
2692
2693 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2694   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2695
2696   // Figure out which block is immediately after the current one.
2697   MachineBasicBlock *NextBlock = nullptr;
2698   if (SwitchMBB + 1 != FuncInfo.MF->end())
2699     NextBlock = SwitchMBB + 1;
2700
2701
2702   // Create a vector of Cases, sorted so that we can efficiently create a binary
2703   // search tree from them.
2704   CaseVector Cases;
2705   Clusterify(Cases, SI);
2706
2707   // Get the default destination MBB.
2708   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2709
2710   if (isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()) &&
2711       !Cases.empty()) {
2712     // Replace an unreachable default destination with the most popular case
2713     // destination.
2714     DenseMap<const BasicBlock *, uint64_t> Popularity;
2715     uint64_t MaxPop = 0;
2716     const BasicBlock *MaxBB = nullptr;
2717     for (auto I : SI.cases()) {
2718       const BasicBlock *BB = I.getCaseSuccessor();
2719       if (++Popularity[BB] > MaxPop) {
2720         MaxPop = Popularity[BB];
2721         MaxBB = BB;
2722       }
2723     }
2724
2725     // Set new default.
2726     assert(MaxPop > 0);
2727     assert(MaxBB);
2728     Default = FuncInfo.MBBMap[MaxBB];
2729
2730     // Remove cases that were pointing to the destination that is now the default.
2731     Cases.erase(std::remove_if(Cases.begin(), Cases.end(),
2732                                [&](const Case &C) { return C.BB == Default; }),
2733                 Cases.end());
2734   }
2735
2736   // If there is only the default destination, go there directly.
2737   if (Cases.empty()) {
2738     // Update machine-CFG edges.
2739     SwitchMBB->addSuccessor(Default);
2740
2741     // If this is not a fall-through branch, emit the branch.
2742     if (Default != NextBlock) {
2743       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2744                               getControlRoot(), DAG.getBasicBlock(Default)));
2745     }
2746     return;
2747   }
2748
2749   // Get the Value to be switched on.
2750   const Value *SV = SI.getCondition();
2751
2752   // Push the initial CaseRec onto the worklist
2753   CaseRecVector WorkList;
2754   WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
2755                              CaseRange(Cases.begin(),Cases.end())));
2756
2757   while (!WorkList.empty()) {
2758     // Grab a record representing a case range to process off the worklist
2759     CaseRec CR = WorkList.back();
2760     WorkList.pop_back();
2761
2762     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2763       continue;
2764
2765     // If the range has few cases (two or less) emit a series of specific
2766     // tests.
2767     if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2768       continue;
2769
2770     // If the switch has more than N blocks, and is at least 40% dense, and the
2771     // target supports indirect branches, then emit a jump table rather than
2772     // lowering the switch to a binary tree of conditional branches.
2773     // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2774     if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2775       continue;
2776
2777     // Emit binary tree. We need to pick a pivot, and push left and right ranges
2778     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2779     handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
2780   }
2781 }
2782
2783 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2784   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2785
2786   // Update machine-CFG edges with unique successors.
2787   SmallSet<BasicBlock*, 32> Done;
2788   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2789     BasicBlock *BB = I.getSuccessor(i);
2790     bool Inserted = Done.insert(BB).second;
2791     if (!Inserted)
2792         continue;
2793
2794     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2795     addSuccessorWithWeight(IndirectBrMBB, Succ);
2796   }
2797
2798   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2799                           MVT::Other, getControlRoot(),
2800                           getValue(I.getAddress())));
2801 }
2802
2803 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2804   if (DAG.getTarget().Options.TrapUnreachable)
2805     DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2806 }
2807
2808 void SelectionDAGBuilder::visitFSub(const User &I) {
2809   // -0.0 - X --> fneg
2810   Type *Ty = I.getType();
2811   if (isa<Constant>(I.getOperand(0)) &&
2812       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2813     SDValue Op2 = getValue(I.getOperand(1));
2814     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2815                              Op2.getValueType(), Op2));
2816     return;
2817   }
2818
2819   visitBinary(I, ISD::FSUB);
2820 }
2821
2822 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2823   SDValue Op1 = getValue(I.getOperand(0));
2824   SDValue Op2 = getValue(I.getOperand(1));
2825
2826   bool nuw = false;
2827   bool nsw = false;
2828   bool exact = false;
2829   if (const OverflowingBinaryOperator *OFBinOp =
2830           dyn_cast<const OverflowingBinaryOperator>(&I)) {
2831     nuw = OFBinOp->hasNoUnsignedWrap();
2832     nsw = OFBinOp->hasNoSignedWrap();
2833   }
2834   if (const PossiblyExactOperator *ExactOp =
2835           dyn_cast<const PossiblyExactOperator>(&I))
2836     exact = ExactOp->isExact();
2837
2838   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2839                                      Op1, Op2, nuw, nsw, exact);
2840   setValue(&I, BinNodeValue);
2841 }
2842
2843 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2844   SDValue Op1 = getValue(I.getOperand(0));
2845   SDValue Op2 = getValue(I.getOperand(1));
2846
2847   EVT ShiftTy =
2848       DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
2849
2850   // Coerce the shift amount to the right type if we can.
2851   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2852     unsigned ShiftSize = ShiftTy.getSizeInBits();
2853     unsigned Op2Size = Op2.getValueType().getSizeInBits();
2854     SDLoc DL = getCurSDLoc();
2855
2856     // If the operand is smaller than the shift count type, promote it.
2857     if (ShiftSize > Op2Size)
2858       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2859
2860     // If the operand is larger than the shift count type but the shift
2861     // count type has enough bits to represent any shift value, truncate
2862     // it now. This is a common case and it exposes the truncate to
2863     // optimization early.
2864     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2865       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2866     // Otherwise we'll need to temporarily settle for some other convenient
2867     // type.  Type legalization will make adjustments once the shiftee is split.
2868     else
2869       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2870   }
2871
2872   bool nuw = false;
2873   bool nsw = false;
2874   bool exact = false;
2875
2876   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2877
2878     if (const OverflowingBinaryOperator *OFBinOp =
2879             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2880       nuw = OFBinOp->hasNoUnsignedWrap();
2881       nsw = OFBinOp->hasNoSignedWrap();
2882     }
2883     if (const PossiblyExactOperator *ExactOp =
2884             dyn_cast<const PossiblyExactOperator>(&I))
2885       exact = ExactOp->isExact();
2886   }
2887
2888   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2889                             nuw, nsw, exact);
2890   setValue(&I, Res);
2891 }
2892
2893 void SelectionDAGBuilder::visitSDiv(const User &I) {
2894   SDValue Op1 = getValue(I.getOperand(0));
2895   SDValue Op2 = getValue(I.getOperand(1));
2896
2897   // Turn exact SDivs into multiplications.
2898   // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2899   // exact bit.
2900   if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2901       !isa<ConstantSDNode>(Op1) &&
2902       isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2903     setValue(&I, DAG.getTargetLoweringInfo()
2904                      .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
2905   else
2906     setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2907                              Op1, Op2));
2908 }
2909
2910 void SelectionDAGBuilder::visitICmp(const User &I) {
2911   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2912   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2913     predicate = IC->getPredicate();
2914   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2915     predicate = ICmpInst::Predicate(IC->getPredicate());
2916   SDValue Op1 = getValue(I.getOperand(0));
2917   SDValue Op2 = getValue(I.getOperand(1));
2918   ISD::CondCode Opcode = getICmpCondCode(predicate);
2919
2920   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2921   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2922 }
2923
2924 void SelectionDAGBuilder::visitFCmp(const User &I) {
2925   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2926   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2927     predicate = FC->getPredicate();
2928   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2929     predicate = FCmpInst::Predicate(FC->getPredicate());
2930   SDValue Op1 = getValue(I.getOperand(0));
2931   SDValue Op2 = getValue(I.getOperand(1));
2932   ISD::CondCode Condition = getFCmpCondCode(predicate);
2933   if (TM.Options.NoNaNsFPMath)
2934     Condition = getFCmpCodeWithoutNaN(Condition);
2935   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2936   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2937 }
2938
2939 void SelectionDAGBuilder::visitSelect(const User &I) {
2940   SmallVector<EVT, 4> ValueVTs;
2941   ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
2942   unsigned NumValues = ValueVTs.size();
2943   if (NumValues == 0) return;
2944
2945   SmallVector<SDValue, 4> Values(NumValues);
2946   SDValue Cond     = getValue(I.getOperand(0));
2947   SDValue TrueVal  = getValue(I.getOperand(1));
2948   SDValue FalseVal = getValue(I.getOperand(2));
2949   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2950     ISD::VSELECT : ISD::SELECT;
2951
2952   for (unsigned i = 0; i != NumValues; ++i)
2953     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2954                             TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2955                             Cond,
2956                             SDValue(TrueVal.getNode(),
2957                                     TrueVal.getResNo() + i),
2958                             SDValue(FalseVal.getNode(),
2959                                     FalseVal.getResNo() + i));
2960
2961   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2962                            DAG.getVTList(ValueVTs), Values));
2963 }
2964
2965 void SelectionDAGBuilder::visitTrunc(const User &I) {
2966   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2967   SDValue N = getValue(I.getOperand(0));
2968   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2969   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2970 }
2971
2972 void SelectionDAGBuilder::visitZExt(const User &I) {
2973   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2974   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2975   SDValue N = getValue(I.getOperand(0));
2976   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2977   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2978 }
2979
2980 void SelectionDAGBuilder::visitSExt(const User &I) {
2981   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2982   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2983   SDValue N = getValue(I.getOperand(0));
2984   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2985   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2986 }
2987
2988 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2989   // FPTrunc is never a no-op cast, no need to check
2990   SDValue N = getValue(I.getOperand(0));
2991   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2992   EVT DestVT = TLI.getValueType(I.getType());
2993   setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
2994                            DAG.getTargetConstant(0, TLI.getPointerTy())));
2995 }
2996
2997 void SelectionDAGBuilder::visitFPExt(const User &I) {
2998   // FPExt is never a no-op cast, no need to check
2999   SDValue N = getValue(I.getOperand(0));
3000   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3001   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3002 }
3003
3004 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3005   // FPToUI is never a no-op cast, no need to check
3006   SDValue N = getValue(I.getOperand(0));
3007   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3008   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3009 }
3010
3011 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3012   // FPToSI is never a no-op cast, no need to check
3013   SDValue N = getValue(I.getOperand(0));
3014   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3015   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3016 }
3017
3018 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3019   // UIToFP is never a no-op cast, no need to check
3020   SDValue N = getValue(I.getOperand(0));
3021   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3022   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3023 }
3024
3025 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3026   // SIToFP is never a no-op cast, no need to check
3027   SDValue N = getValue(I.getOperand(0));
3028   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3029   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3030 }
3031
3032 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3033   // What to do depends on the size of the integer and the size of the pointer.
3034   // We can either truncate, zero extend, or no-op, accordingly.
3035   SDValue N = getValue(I.getOperand(0));
3036   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3037   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3038 }
3039
3040 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3041   // What to do depends on the size of the integer and the size of the pointer.
3042   // We can either truncate, zero extend, or no-op, accordingly.
3043   SDValue N = getValue(I.getOperand(0));
3044   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3045   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3046 }
3047
3048 void SelectionDAGBuilder::visitBitCast(const User &I) {
3049   SDValue N = getValue(I.getOperand(0));
3050   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3051
3052   // BitCast assures us that source and destination are the same size so this is
3053   // either a BITCAST or a no-op.
3054   if (DestVT != N.getValueType())
3055     setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
3056                              DestVT, N)); // convert types.
3057   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3058   // might fold any kind of constant expression to an integer constant and that
3059   // is not what we are looking for. Only regcognize a bitcast of a genuine
3060   // constant integer as an opaque constant.
3061   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3062     setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
3063                                  /*isOpaque*/true));
3064   else
3065     setValue(&I, N);            // noop cast.
3066 }
3067
3068 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3069   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3070   const Value *SV = I.getOperand(0);
3071   SDValue N = getValue(SV);
3072   EVT DestVT = TLI.getValueType(I.getType());
3073
3074   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3075   unsigned DestAS = I.getType()->getPointerAddressSpace();
3076
3077   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3078     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3079
3080   setValue(&I, N);
3081 }
3082
3083 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3085   SDValue InVec = getValue(I.getOperand(0));
3086   SDValue InVal = getValue(I.getOperand(1));
3087   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3088                                      getCurSDLoc(), TLI.getVectorIdxTy());
3089   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3090                            TLI.getValueType(I.getType()), InVec, InVal, InIdx));
3091 }
3092
3093 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3095   SDValue InVec = getValue(I.getOperand(0));
3096   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3097                                      getCurSDLoc(), TLI.getVectorIdxTy());
3098   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3099                            TLI.getValueType(I.getType()), InVec, InIdx));
3100 }
3101
3102 // Utility for visitShuffleVector - Return true if every element in Mask,
3103 // beginning from position Pos and ending in Pos+Size, falls within the
3104 // specified sequential range [L, L+Pos). or is undef.
3105 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
3106                                 unsigned Pos, unsigned Size, int Low) {
3107   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3108     if (Mask[i] >= 0 && Mask[i] != Low)
3109       return false;
3110   return true;
3111 }
3112
3113 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3114   SDValue Src1 = getValue(I.getOperand(0));
3115   SDValue Src2 = getValue(I.getOperand(1));
3116
3117   SmallVector<int, 8> Mask;
3118   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3119   unsigned MaskNumElts = Mask.size();
3120
3121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3122   EVT VT = TLI.getValueType(I.getType());
3123   EVT SrcVT = Src1.getValueType();
3124   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3125
3126   if (SrcNumElts == MaskNumElts) {
3127     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3128                                       &Mask[0]));
3129     return;
3130   }
3131
3132   // Normalize the shuffle vector since mask and vector length don't match.
3133   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3134     // Mask is longer than the source vectors and is a multiple of the source
3135     // vectors.  We can use concatenate vector to make the mask and vectors
3136     // lengths match.
3137     if (SrcNumElts*2 == MaskNumElts) {
3138       // First check for Src1 in low and Src2 in high
3139       if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3140           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3141         // The shuffle is concatenating two vectors together.
3142         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3143                                  VT, Src1, Src2));
3144         return;
3145       }
3146       // Then check for Src2 in low and Src1 in high
3147       if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3148           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3149         // The shuffle is concatenating two vectors together.
3150         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3151                                  VT, Src2, Src1));
3152         return;
3153       }
3154     }
3155
3156     // Pad both vectors with undefs to make them the same length as the mask.
3157     unsigned NumConcat = MaskNumElts / SrcNumElts;
3158     bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3159     bool Src2U = Src2.getOpcode() == ISD::UNDEF;
3160     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3161
3162     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3163     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3164     MOps1[0] = Src1;
3165     MOps2[0] = Src2;
3166
3167     Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3168                                                   getCurSDLoc(), VT, MOps1);
3169     Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3170                                                   getCurSDLoc(), VT, MOps2);
3171
3172     // Readjust mask for new input vector length.
3173     SmallVector<int, 8> MappedOps;
3174     for (unsigned i = 0; i != MaskNumElts; ++i) {
3175       int Idx = Mask[i];
3176       if (Idx >= (int)SrcNumElts)
3177         Idx -= SrcNumElts - MaskNumElts;
3178       MappedOps.push_back(Idx);
3179     }
3180
3181     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3182                                       &MappedOps[0]));
3183     return;
3184   }
3185
3186   if (SrcNumElts > MaskNumElts) {
3187     // Analyze the access pattern of the vector to see if we can extract
3188     // two subvectors and do the shuffle. The analysis is done by calculating
3189     // the range of elements the mask access on both vectors.
3190     int MinRange[2] = { static_cast<int>(SrcNumElts),
3191                         static_cast<int>(SrcNumElts)};
3192     int MaxRange[2] = {-1, -1};
3193
3194     for (unsigned i = 0; i != MaskNumElts; ++i) {
3195       int Idx = Mask[i];
3196       unsigned Input = 0;
3197       if (Idx < 0)
3198         continue;
3199
3200       if (Idx >= (int)SrcNumElts) {
3201         Input = 1;
3202         Idx -= SrcNumElts;
3203       }
3204       if (Idx > MaxRange[Input])
3205         MaxRange[Input] = Idx;
3206       if (Idx < MinRange[Input])
3207         MinRange[Input] = Idx;
3208     }
3209
3210     // Check if the access is smaller than the vector size and can we find
3211     // a reasonable extract index.
3212     int RangeUse[2] = { -1, -1 };  // 0 = Unused, 1 = Extract, -1 = Can not
3213                                    // Extract.
3214     int StartIdx[2];  // StartIdx to extract from
3215     for (unsigned Input = 0; Input < 2; ++Input) {
3216       if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
3217         RangeUse[Input] = 0; // Unused
3218         StartIdx[Input] = 0;
3219         continue;
3220       }
3221
3222       // Find a good start index that is a multiple of the mask length. Then
3223       // see if the rest of the elements are in range.
3224       StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3225       if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3226           StartIdx[Input] + MaskNumElts <= SrcNumElts)
3227         RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3228     }
3229
3230     if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3231       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3232       return;
3233     }
3234     if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3235       // Extract appropriate subvector and generate a vector shuffle
3236       for (unsigned Input = 0; Input < 2; ++Input) {
3237         SDValue &Src = Input == 0 ? Src1 : Src2;
3238         if (RangeUse[Input] == 0)
3239           Src = DAG.getUNDEF(VT);
3240         else
3241           Src = DAG.getNode(
3242               ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT, Src,
3243               DAG.getConstant(StartIdx[Input], TLI.getVectorIdxTy()));
3244       }
3245
3246       // Calculate new mask.
3247       SmallVector<int, 8> MappedOps;
3248       for (unsigned i = 0; i != MaskNumElts; ++i) {
3249         int Idx = Mask[i];
3250         if (Idx >= 0) {
3251           if (Idx < (int)SrcNumElts)
3252             Idx -= StartIdx[0];
3253           else
3254             Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3255         }
3256         MappedOps.push_back(Idx);
3257       }
3258
3259       setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3260                                         &MappedOps[0]));
3261       return;
3262     }
3263   }
3264
3265   // We can't use either concat vectors or extract subvectors so fall back to
3266   // replacing the shuffle with extract and build vector.
3267   // to insert and build vector.
3268   EVT EltVT = VT.getVectorElementType();
3269   EVT IdxVT = TLI.getVectorIdxTy();
3270   SmallVector<SDValue,8> Ops;
3271   for (unsigned i = 0; i != MaskNumElts; ++i) {
3272     int Idx = Mask[i];
3273     SDValue Res;
3274
3275     if (Idx < 0) {
3276       Res = DAG.getUNDEF(EltVT);
3277     } else {
3278       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3279       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3280
3281       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3282                         EltVT, Src, DAG.getConstant(Idx, IdxVT));
3283     }
3284
3285     Ops.push_back(Res);
3286   }
3287
3288   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
3289 }
3290
3291 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3292   const Value *Op0 = I.getOperand(0);
3293   const Value *Op1 = I.getOperand(1);
3294   Type *AggTy = I.getType();
3295   Type *ValTy = Op1->getType();
3296   bool IntoUndef = isa<UndefValue>(Op0);
3297   bool FromUndef = isa<UndefValue>(Op1);
3298
3299   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3300
3301   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3302   SmallVector<EVT, 4> AggValueVTs;
3303   ComputeValueVTs(TLI, AggTy, AggValueVTs);
3304   SmallVector<EVT, 4> ValValueVTs;
3305   ComputeValueVTs(TLI, ValTy, ValValueVTs);
3306
3307   unsigned NumAggValues = AggValueVTs.size();
3308   unsigned NumValValues = ValValueVTs.size();
3309   SmallVector<SDValue, 4> Values(NumAggValues);
3310
3311   // Ignore an insertvalue that produces an empty object
3312   if (!NumAggValues) {
3313     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3314     return;
3315   }
3316
3317   SDValue Agg = getValue(Op0);
3318   unsigned i = 0;
3319   // Copy the beginning value(s) from the original aggregate.
3320   for (; i != LinearIndex; ++i)
3321     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3322                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3323   // Copy values from the inserted value(s).
3324   if (NumValValues) {
3325     SDValue Val = getValue(Op1);
3326     for (; i != LinearIndex + NumValValues; ++i)
3327       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3328                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3329   }
3330   // Copy remaining value(s) from the original aggregate.
3331   for (; i != NumAggValues; ++i)
3332     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3333                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3334
3335   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3336                            DAG.getVTList(AggValueVTs), Values));
3337 }
3338
3339 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3340   const Value *Op0 = I.getOperand(0);
3341   Type *AggTy = Op0->getType();
3342   Type *ValTy = I.getType();
3343   bool OutOfUndef = isa<UndefValue>(Op0);
3344
3345   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3346
3347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3348   SmallVector<EVT, 4> ValValueVTs;
3349   ComputeValueVTs(TLI, ValTy, ValValueVTs);
3350
3351   unsigned NumValValues = ValValueVTs.size();
3352
3353   // Ignore a extractvalue that produces an empty object
3354   if (!NumValValues) {
3355     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3356     return;
3357   }
3358
3359   SmallVector<SDValue, 4> Values(NumValValues);
3360
3361   SDValue Agg = getValue(Op0);
3362   // Copy out the selected value(s).
3363   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3364     Values[i - LinearIndex] =
3365       OutOfUndef ?
3366         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3367         SDValue(Agg.getNode(), Agg.getResNo() + i);
3368
3369   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3370                            DAG.getVTList(ValValueVTs), Values));
3371 }
3372
3373 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3374   Value *Op0 = I.getOperand(0);
3375   // Note that the pointer operand may be a vector of pointers. Take the scalar
3376   // element which holds a pointer.
3377   Type *Ty = Op0->getType()->getScalarType();
3378   unsigned AS = Ty->getPointerAddressSpace();
3379   SDValue N = getValue(Op0);
3380
3381   for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3382        OI != E; ++OI) {
3383     const Value *Idx = *OI;
3384     if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3385       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3386       if (Field) {
3387         // N = N + Offset
3388         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3389         N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3390                         DAG.getConstant(Offset, N.getValueType()));
3391       }
3392
3393       Ty = StTy->getElementType(Field);
3394     } else {
3395       Ty = cast<SequentialType>(Ty)->getElementType();
3396
3397       // If this is a constant subscript, handle it quickly.
3398       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3399       if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3400         if (CI->isZero()) continue;
3401         uint64_t Offs =
3402             DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3403         SDValue OffsVal;
3404         EVT PTy = TLI.getPointerTy(AS);
3405         unsigned PtrBits = PTy.getSizeInBits();
3406         if (PtrBits < 64)
3407           OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
3408                                 DAG.getConstant(Offs, MVT::i64));
3409         else
3410           OffsVal = DAG.getConstant(Offs, PTy);
3411
3412         N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3413                         OffsVal);
3414         continue;
3415       }
3416
3417       // N = N + Idx * ElementSize;
3418       APInt ElementSize =
3419           APInt(TLI.getPointerSizeInBits(AS), DL->getTypeAllocSize(Ty));
3420       SDValue IdxN = getValue(Idx);
3421
3422       // If the index is smaller or larger than intptr_t, truncate or extend
3423       // it.
3424       IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
3425
3426       // If this is a multiply by a power of two, turn it into a shl
3427       // immediately.  This is a very common case.
3428       if (ElementSize != 1) {
3429         if (ElementSize.isPowerOf2()) {
3430           unsigned Amt = ElementSize.logBase2();
3431           IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
3432                              N.getValueType(), IdxN,
3433                              DAG.getConstant(Amt, IdxN.getValueType()));
3434         } else {
3435           SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
3436           IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
3437                              N.getValueType(), IdxN, Scale);
3438         }
3439       }
3440
3441       N = DAG.getNode(ISD::ADD, getCurSDLoc(),
3442                       N.getValueType(), N, IdxN);
3443     }
3444   }
3445
3446   setValue(&I, N);
3447 }
3448
3449 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3450   // If this is a fixed sized alloca in the entry block of the function,
3451   // allocate it statically on the stack.
3452   if (FuncInfo.StaticAllocaMap.count(&I))
3453     return;   // getValue will auto-populate this.
3454
3455   Type *Ty = I.getAllocatedType();
3456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3457   uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
3458   unsigned Align =
3459       std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
3460                I.getAlignment());
3461
3462   SDValue AllocSize = getValue(I.getArraySize());
3463
3464   EVT IntPtr = TLI.getPointerTy();
3465   if (AllocSize.getValueType() != IntPtr)
3466     AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
3467
3468   AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
3469                           AllocSize,
3470                           DAG.getConstant(TySize, IntPtr));
3471
3472   // Handle alignment.  If the requested alignment is less than or equal to
3473   // the stack alignment, ignore it.  If the size is greater than or equal to
3474   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3475   unsigned StackAlign =
3476       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3477   if (Align <= StackAlign)
3478     Align = 0;
3479
3480   // Round the size of the allocation up to the stack alignment size
3481   // by add SA-1 to the size.
3482   AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
3483                           AllocSize.getValueType(), AllocSize,
3484                           DAG.getIntPtrConstant(StackAlign-1));
3485
3486   // Mask out the low bits for alignment purposes.
3487   AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
3488                           AllocSize.getValueType(), AllocSize,
3489                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3490
3491   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3492   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3493   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
3494   setValue(&I, DSA);
3495   DAG.setRoot(DSA.getValue(1));
3496
3497   assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
3498 }
3499
3500 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3501   if (I.isAtomic())
3502     return visitAtomicLoad(I);
3503
3504   const Value *SV = I.getOperand(0);
3505   SDValue Ptr = getValue(SV);
3506
3507   Type *Ty = I.getType();
3508
3509   bool isVolatile = I.isVolatile();
3510   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3511   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3512   unsigned Alignment = I.getAlignment();
3513
3514   AAMDNodes AAInfo;
3515   I.getAAMetadata(AAInfo);
3516   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3517
3518   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3519   SmallVector<EVT, 4> ValueVTs;
3520   SmallVector<uint64_t, 4> Offsets;
3521   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3522   unsigned NumValues = ValueVTs.size();
3523   if (NumValues == 0)
3524     return;
3525
3526   SDValue Root;
3527   bool ConstantMemory = false;
3528   if (isVolatile || NumValues > MaxParallelChains)
3529     // Serialize volatile loads with other side effects.
3530     Root = getRoot();
3531   else if (AA->pointsToConstantMemory(
3532              AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
3533     // Do not serialize (non-volatile) loads of constant memory with anything.
3534     Root = DAG.getEntryNode();
3535     ConstantMemory = true;
3536   } else {
3537     // Do not serialize non-volatile loads against each other.
3538     Root = DAG.getRoot();
3539   }
3540
3541   if (isVolatile)
3542     Root = TLI.prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
3543
3544   SmallVector<SDValue, 4> Values(NumValues);
3545   SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3546                                           NumValues));
3547   EVT PtrVT = Ptr.getValueType();
3548   unsigned ChainI = 0;
3549   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3550     // Serializing loads here may result in excessive register pressure, and
3551     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3552     // could recover a bit by hoisting nodes upward in the chain by recognizing
3553     // they are side-effect free or do not alias. The optimizer should really
3554     // avoid this case by converting large object/array copies to llvm.memcpy
3555     // (MaxParallelChains should always remain as failsafe).
3556     if (ChainI == MaxParallelChains) {
3557       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3558       SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3559                                   makeArrayRef(Chains.data(), ChainI));
3560       Root = Chain;
3561       ChainI = 0;
3562     }
3563     SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
3564                             PtrVT, Ptr,
3565                             DAG.getConstant(Offsets[i], PtrVT));
3566     SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
3567                             A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3568                             isNonTemporal, isInvariant, Alignment, AAInfo,
3569                             Ranges);
3570
3571     Values[i] = L;
3572     Chains[ChainI] = L.getValue(1);
3573   }
3574
3575   if (!ConstantMemory) {
3576     SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3577                                 makeArrayRef(Chains.data(), ChainI));
3578     if (isVolatile)
3579       DAG.setRoot(Chain);
3580     else
3581       PendingLoads.push_back(Chain);
3582   }
3583
3584   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3585                            DAG.getVTList(ValueVTs), Values));
3586 }
3587
3588 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3589   if (I.isAtomic())
3590     return visitAtomicStore(I);
3591
3592   const Value *SrcV = I.getOperand(0);
3593   const Value *PtrV = I.getOperand(1);
3594
3595   SmallVector<EVT, 4> ValueVTs;
3596   SmallVector<uint64_t, 4> Offsets;
3597   ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
3598                   ValueVTs, &Offsets);
3599   unsigned NumValues = ValueVTs.size();
3600   if (NumValues == 0)
3601     return;
3602
3603   // Get the lowered operands. Note that we do this after
3604   // checking if NumResults is zero, because with zero results
3605   // the operands won't have values in the map.
3606   SDValue Src = getValue(SrcV);
3607   SDValue Ptr = getValue(PtrV);
3608
3609   SDValue Root = getRoot();
3610   SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3611                                           NumValues));
3612   EVT PtrVT = Ptr.getValueType();
3613   bool isVolatile = I.isVolatile();
3614   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3615   unsigned Alignment = I.getAlignment();
3616
3617   AAMDNodes AAInfo;
3618   I.getAAMetadata(AAInfo);
3619
3620   unsigned ChainI = 0;
3621   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3622     // See visitLoad comments.
3623     if (ChainI == MaxParallelChains) {
3624       SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3625                                   makeArrayRef(Chains.data(), ChainI));
3626       Root = Chain;
3627       ChainI = 0;
3628     }
3629     SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
3630                               DAG.getConstant(Offsets[i], PtrVT));
3631     SDValue St = DAG.getStore(Root, getCurSDLoc(),
3632                               SDValue(Src.getNode(), Src.getResNo() + i),
3633                               Add, MachinePointerInfo(PtrV, Offsets[i]),
3634                               isVolatile, isNonTemporal, Alignment, AAInfo);
3635     Chains[ChainI] = St;
3636   }
3637
3638   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3639                                   makeArrayRef(Chains.data(), ChainI));
3640   DAG.setRoot(StoreNode);
3641 }
3642
3643 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
3644   SDLoc sdl = getCurSDLoc();
3645
3646   Value  *PtrOperand = I.getArgOperand(0);
3647   SDValue Ptr = getValue(PtrOperand);
3648   SDValue Src0 = getValue(I.getArgOperand(1));
3649   SDValue Mask = getValue(I.getArgOperand(3));
3650   EVT VT = Src0.getValueType();
3651   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3652   if (!Alignment)
3653     Alignment = DAG.getEVTAlignment(VT);
3654
3655   AAMDNodes AAInfo;
3656   I.getAAMetadata(AAInfo);
3657
3658   MachineMemOperand *MMO =
3659     DAG.getMachineFunction().
3660     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3661                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3662                           Alignment, AAInfo);
3663   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, MMO);
3664   DAG.setRoot(StoreNode);
3665   setValue(&I, StoreNode);
3666 }
3667
3668 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
3669   SDLoc sdl = getCurSDLoc();
3670
3671   Value  *PtrOperand = I.getArgOperand(0);
3672   SDValue Ptr = getValue(PtrOperand);
3673   SDValue Src0 = getValue(I.getArgOperand(1));
3674   SDValue Mask = getValue(I.getArgOperand(3));
3675
3676   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3677   EVT VT = TLI.getValueType(I.getType());
3678   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3679   if (!Alignment)
3680     Alignment = DAG.getEVTAlignment(VT);
3681
3682   AAMDNodes AAInfo;
3683   I.getAAMetadata(AAInfo);
3684   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3685
3686   SDValue InChain = DAG.getRoot();
3687   if (AA->pointsToConstantMemory(
3688       AliasAnalysis::Location(PtrOperand,
3689                               AA->getTypeStoreSize(I.getType()),
3690                               AAInfo))) {
3691     // Do not serialize (non-volatile) loads of constant memory with anything.
3692     InChain = DAG.getEntryNode();
3693   }
3694
3695   MachineMemOperand *MMO =
3696     DAG.getMachineFunction().
3697     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3698                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
3699                           Alignment, AAInfo, Ranges);
3700
3701   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, MMO);
3702   SDValue OutChain = Load.getValue(1);
3703   DAG.setRoot(OutChain);
3704   setValue(&I, Load);
3705 }
3706
3707 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3708   SDLoc dl = getCurSDLoc();
3709   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3710   AtomicOrdering FailureOrder = I.getFailureOrdering();
3711   SynchronizationScope Scope = I.getSynchScope();
3712
3713   SDValue InChain = getRoot();
3714
3715   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3716   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3717   SDValue L = DAG.getAtomicCmpSwap(
3718       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3719       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3720       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3721       /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3722
3723   SDValue OutChain = L.getValue(2);
3724
3725   setValue(&I, L);
3726   DAG.setRoot(OutChain);
3727 }
3728
3729 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3730   SDLoc dl = getCurSDLoc();
3731   ISD::NodeType NT;
3732   switch (I.getOperation()) {
3733   default: llvm_unreachable("Unknown atomicrmw operation");
3734   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3735   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
3736   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
3737   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
3738   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3739   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
3740   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
3741   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
3742   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
3743   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3744   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3745   }
3746   AtomicOrdering Order = I.getOrdering();
3747   SynchronizationScope Scope = I.getSynchScope();
3748
3749   SDValue InChain = getRoot();
3750
3751   SDValue L =
3752     DAG.getAtomic(NT, dl,
3753                   getValue(I.getValOperand()).getSimpleValueType(),
3754                   InChain,
3755                   getValue(I.getPointerOperand()),
3756                   getValue(I.getValOperand()),
3757                   I.getPointerOperand(),
3758                   /* Alignment=*/ 0, Order, Scope);
3759
3760   SDValue OutChain = L.getValue(1);
3761
3762   setValue(&I, L);
3763   DAG.setRoot(OutChain);
3764 }
3765
3766 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3767   SDLoc dl = getCurSDLoc();
3768   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3769   SDValue Ops[3];
3770   Ops[0] = getRoot();
3771   Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3772   Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
3773   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3774 }
3775
3776 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3777   SDLoc dl = getCurSDLoc();
3778   AtomicOrdering Order = I.getOrdering();
3779   SynchronizationScope Scope = I.getSynchScope();
3780
3781   SDValue InChain = getRoot();
3782
3783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3784   EVT VT = TLI.getValueType(I.getType());
3785
3786   if (I.getAlignment() < VT.getSizeInBits() / 8)
3787     report_fatal_error("Cannot generate unaligned atomic load");
3788
3789   MachineMemOperand *MMO =
3790       DAG.getMachineFunction().
3791       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3792                            MachineMemOperand::MOVolatile |
3793                            MachineMemOperand::MOLoad,
3794                            VT.getStoreSize(),
3795                            I.getAlignment() ? I.getAlignment() :
3796                                               DAG.getEVTAlignment(VT));
3797
3798   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3799   SDValue L =
3800       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3801                     getValue(I.getPointerOperand()), MMO,
3802                     Order, Scope);
3803
3804   SDValue OutChain = L.getValue(1);
3805
3806   setValue(&I, L);
3807   DAG.setRoot(OutChain);
3808 }
3809
3810 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3811   SDLoc dl = getCurSDLoc();
3812
3813   AtomicOrdering Order = I.getOrdering();
3814   SynchronizationScope Scope = I.getSynchScope();
3815
3816   SDValue InChain = getRoot();
3817
3818   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3819   EVT VT = TLI.getValueType(I.getValueOperand()->getType());
3820
3821   if (I.getAlignment() < VT.getSizeInBits() / 8)
3822     report_fatal_error("Cannot generate unaligned atomic store");
3823
3824   SDValue OutChain =
3825     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3826                   InChain,
3827                   getValue(I.getPointerOperand()),
3828                   getValue(I.getValueOperand()),
3829                   I.getPointerOperand(), I.getAlignment(),
3830                   Order, Scope);
3831
3832   DAG.setRoot(OutChain);
3833 }
3834
3835 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3836 /// node.
3837 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3838                                                unsigned Intrinsic) {
3839   bool HasChain = !I.doesNotAccessMemory();
3840   bool OnlyLoad = HasChain && I.onlyReadsMemory();
3841
3842   // Build the operand list.
3843   SmallVector<SDValue, 8> Ops;
3844   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
3845     if (OnlyLoad) {
3846       // We don't need to serialize loads against other loads.
3847       Ops.push_back(DAG.getRoot());
3848     } else {
3849       Ops.push_back(getRoot());
3850     }
3851   }
3852
3853   // Info is set by getTgtMemInstrinsic
3854   TargetLowering::IntrinsicInfo Info;
3855   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3856   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3857
3858   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3859   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3860       Info.opc == ISD::INTRINSIC_W_CHAIN)
3861     Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI.getPointerTy()));
3862
3863   // Add all operands of the call to the operand list.
3864   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3865     SDValue Op = getValue(I.getArgOperand(i));
3866     Ops.push_back(Op);
3867   }
3868
3869   SmallVector<EVT, 4> ValueVTs;
3870   ComputeValueVTs(TLI, I.getType(), ValueVTs);
3871
3872   if (HasChain)
3873     ValueVTs.push_back(MVT::Other);
3874
3875   SDVTList VTs = DAG.getVTList(ValueVTs);
3876
3877   // Create the node.
3878   SDValue Result;
3879   if (IsTgtIntrinsic) {
3880     // This is target intrinsic that touches memory
3881     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3882                                      VTs, Ops, Info.memVT,
3883                                    MachinePointerInfo(Info.ptrVal, Info.offset),
3884                                      Info.align, Info.vol,
3885                                      Info.readMem, Info.writeMem, Info.size);
3886   } else if (!HasChain) {
3887     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
3888   } else if (!I.getType()->isVoidTy()) {
3889     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
3890   } else {
3891     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
3892   }
3893
3894   if (HasChain) {
3895     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3896     if (OnlyLoad)
3897       PendingLoads.push_back(Chain);
3898     else
3899       DAG.setRoot(Chain);
3900   }
3901
3902   if (!I.getType()->isVoidTy()) {
3903     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3904       EVT VT = TLI.getValueType(PTy);
3905       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3906     }
3907
3908     setValue(&I, Result);
3909   }
3910 }
3911
3912 /// GetSignificand - Get the significand and build it into a floating-point
3913 /// number with exponent of 1:
3914 ///
3915 ///   Op = (Op & 0x007fffff) | 0x3f800000;
3916 ///
3917 /// where Op is the hexadecimal representation of floating point value.
3918 static SDValue
3919 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3920   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3921                            DAG.getConstant(0x007fffff, MVT::i32));
3922   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3923                            DAG.getConstant(0x3f800000, MVT::i32));
3924   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3925 }
3926
3927 /// GetExponent - Get the exponent:
3928 ///
3929 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3930 ///
3931 /// where Op is the hexadecimal representation of floating point value.
3932 static SDValue
3933 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3934             SDLoc dl) {
3935   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3936                            DAG.getConstant(0x7f800000, MVT::i32));
3937   SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3938                            DAG.getConstant(23, TLI.getPointerTy()));
3939   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3940                            DAG.getConstant(127, MVT::i32));
3941   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3942 }
3943
3944 /// getF32Constant - Get 32-bit floating point constant.
3945 static SDValue
3946 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3947   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3948                            MVT::f32);
3949 }
3950
3951 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
3952 /// limited-precision mode.
3953 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3954                          const TargetLowering &TLI) {
3955   if (Op.getValueType() == MVT::f32 &&
3956       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3957
3958     // Put the exponent in the right bit position for later addition to the
3959     // final result:
3960     //
3961     //   #define LOG2OFe 1.4426950f
3962     //   IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3963     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3964                              getF32Constant(DAG, 0x3fb8aa3b));
3965     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3966
3967     //   FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3968     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3969     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3970
3971     //   IntegerPartOfX <<= 23;
3972     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3973                                  DAG.getConstant(23, TLI.getPointerTy()));
3974
3975     SDValue TwoToFracPartOfX;
3976     if (LimitFloatPrecision <= 6) {
3977       // For floating-point precision of 6:
3978       //
3979       //   TwoToFractionalPartOfX =
3980       //     0.997535578f +
3981       //       (0.735607626f + 0.252464424f * x) * x;
3982       //
3983       // error 0.0144103317, which is 6 bits
3984       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3985                                getF32Constant(DAG, 0x3e814304));
3986       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3987                                getF32Constant(DAG, 0x3f3c50c8));
3988       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3989       TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3990                                      getF32Constant(DAG, 0x3f7f5e7e));
3991     } else if (LimitFloatPrecision <= 12) {
3992       // For floating-point precision of 12:
3993       //
3994       //   TwoToFractionalPartOfX =
3995       //     0.999892986f +
3996       //       (0.696457318f +
3997       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3998       //
3999       // 0.000107046256 error, which is 13 to 14 bits
4000       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4001                                getF32Constant(DAG, 0x3da235e3));
4002       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4003                                getF32Constant(DAG, 0x3e65b8f3));
4004       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4005       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4006                                getF32Constant(DAG, 0x3f324b07));
4007       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4008       TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4009                                      getF32Constant(DAG, 0x3f7ff8fd));
4010     } else { // LimitFloatPrecision <= 18
4011       // For floating-point precision of 18:
4012       //
4013       //   TwoToFractionalPartOfX =
4014       //     0.999999982f +
4015       //       (0.693148872f +
4016       //         (0.240227044f +
4017       //           (0.554906021e-1f +
4018       //             (0.961591928e-2f +
4019       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4020       //
4021       // error 2.47208000*10^(-7), which is better than 18 bits
4022       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4023                                getF32Constant(DAG, 0x3924b03e));
4024       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4025                                getF32Constant(DAG, 0x3ab24b87));
4026       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4027       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4028                                getF32Constant(DAG, 0x3c1d8c17));
4029       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4030       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4031                                getF32Constant(DAG, 0x3d634a1d));
4032       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4033       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4034                                getF32Constant(DAG, 0x3e75fe14));
4035       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4036       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4037                                 getF32Constant(DAG, 0x3f317234));
4038       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4039       TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4040                                      getF32Constant(DAG, 0x3f800000));
4041     }
4042
4043     // Add the exponent into the result in integer domain.
4044     SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
4045     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4046                        DAG.getNode(ISD::ADD, dl, MVT::i32,
4047                                    t13, IntegerPartOfX));
4048   }
4049
4050   // No special expansion.
4051   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4052 }
4053
4054 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4055 /// limited-precision mode.
4056 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4057                          const TargetLowering &TLI) {
4058   if (Op.getValueType() == MVT::f32 &&
4059       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4060     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4061
4062     // Scale the exponent by log(2) [0.69314718f].
4063     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4064     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4065                                         getF32Constant(DAG, 0x3f317218));
4066
4067     // Get the significand and build it into a floating-point number with
4068     // exponent of 1.
4069     SDValue X = GetSignificand(DAG, Op1, dl);
4070
4071     SDValue LogOfMantissa;
4072     if (LimitFloatPrecision <= 6) {
4073       // For floating-point precision of 6:
4074       //
4075       //   LogofMantissa =
4076       //     -1.1609546f +
4077       //       (1.4034025f - 0.23903021f * x) * x;
4078       //
4079       // error 0.0034276066, which is better than 8 bits
4080       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4081                                getF32Constant(DAG, 0xbe74c456));
4082       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4083                                getF32Constant(DAG, 0x3fb3a2b1));
4084       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4085       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4086                                   getF32Constant(DAG, 0x3f949a29));
4087     } else if (LimitFloatPrecision <= 12) {
4088       // For floating-point precision of 12:
4089       //
4090       //   LogOfMantissa =
4091       //     -1.7417939f +
4092       //       (2.8212026f +
4093       //         (-1.4699568f +
4094       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4095       //
4096       // error 0.000061011436, which is 14 bits
4097       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4098                                getF32Constant(DAG, 0xbd67b6d6));
4099       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4100                                getF32Constant(DAG, 0x3ee4f4b8));
4101       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4102       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4103                                getF32Constant(DAG, 0x3fbc278b));
4104       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4105       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4106                                getF32Constant(DAG, 0x40348e95));
4107       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4108       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4109                                   getF32Constant(DAG, 0x3fdef31a));
4110     } else { // LimitFloatPrecision <= 18
4111       // For floating-point precision of 18:
4112       //
4113       //   LogOfMantissa =
4114       //     -2.1072184f +
4115       //       (4.2372794f +
4116       //         (-3.7029485f +
4117       //           (2.2781945f +
4118       //             (-0.87823314f +
4119       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4120       //
4121       // error 0.0000023660568, which is better than 18 bits
4122       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4123                                getF32Constant(DAG, 0xbc91e5ac));
4124       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4125                                getF32Constant(DAG, 0x3e4350aa));
4126       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4127       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4128                                getF32Constant(DAG, 0x3f60d3e3));
4129       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4130       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4131                                getF32Constant(DAG, 0x4011cdf0));
4132       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4133       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4134                                getF32Constant(DAG, 0x406cfd1c));
4135       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4136       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4137                                getF32Constant(DAG, 0x408797cb));
4138       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4139       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4140                                   getF32Constant(DAG, 0x4006dcab));
4141     }
4142
4143     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4144   }
4145
4146   // No special expansion.
4147   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4148 }
4149
4150 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4151 /// limited-precision mode.
4152 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4153                           const TargetLowering &TLI) {
4154   if (Op.getValueType() == MVT::f32 &&
4155       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4156     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4157
4158     // Get the exponent.
4159     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4160
4161     // Get the significand and build it into a floating-point number with
4162     // exponent of 1.
4163     SDValue X = GetSignificand(DAG, Op1, dl);
4164
4165     // Different possible minimax approximations of significand in
4166     // floating-point for various degrees of accuracy over [1,2].
4167     SDValue Log2ofMantissa;
4168     if (LimitFloatPrecision <= 6) {
4169       // For floating-point precision of 6:
4170       //
4171       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4172       //
4173       // error 0.0049451742, which is more than 7 bits
4174       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4175                                getF32Constant(DAG, 0xbeb08fe0));
4176       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4177                                getF32Constant(DAG, 0x40019463));
4178       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4179       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4180                                    getF32Constant(DAG, 0x3fd6633d));
4181     } else if (LimitFloatPrecision <= 12) {
4182       // For floating-point precision of 12:
4183       //
4184       //   Log2ofMantissa =
4185       //     -2.51285454f +
4186       //       (4.07009056f +
4187       //         (-2.12067489f +
4188       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4189       //
4190       // error 0.0000876136000, which is better than 13 bits
4191       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4192                                getF32Constant(DAG, 0xbda7262e));
4193       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4194                                getF32Constant(DAG, 0x3f25280b));
4195       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4196       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4197                                getF32Constant(DAG, 0x4007b923));
4198       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4199       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4200                                getF32Constant(DAG, 0x40823e2f));
4201       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4202       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4203                                    getF32Constant(DAG, 0x4020d29c));
4204     } else { // LimitFloatPrecision <= 18
4205       // For floating-point precision of 18:
4206       //
4207       //   Log2ofMantissa =
4208       //     -3.0400495f +
4209       //       (6.1129976f +
4210       //         (-5.3420409f +
4211       //           (3.2865683f +
4212       //             (-1.2669343f +
4213       //               (0.27515199f -
4214       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4215       //
4216       // error 0.0000018516, which is better than 18 bits
4217       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4218                                getF32Constant(DAG, 0xbcd2769e));
4219       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4220                                getF32Constant(DAG, 0x3e8ce0b9));
4221       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4222       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4223                                getF32Constant(DAG, 0x3fa22ae7));
4224       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4225       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4226                                getF32Constant(DAG, 0x40525723));
4227       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4228       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4229                                getF32Constant(DAG, 0x40aaf200));
4230       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4231       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4232                                getF32Constant(DAG, 0x40c39dad));
4233       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4234       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4235                                    getF32Constant(DAG, 0x4042902c));
4236     }
4237
4238     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4239   }
4240
4241   // No special expansion.
4242   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4243 }
4244
4245 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4246 /// limited-precision mode.
4247 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4248                            const TargetLowering &TLI) {
4249   if (Op.getValueType() == MVT::f32 &&
4250       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4251     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4252
4253     // Scale the exponent by log10(2) [0.30102999f].
4254     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4255     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4256                                         getF32Constant(DAG, 0x3e9a209a));
4257
4258     // Get the significand and build it into a floating-point number with
4259     // exponent of 1.
4260     SDValue X = GetSignificand(DAG, Op1, dl);
4261
4262     SDValue Log10ofMantissa;
4263     if (LimitFloatPrecision <= 6) {
4264       // For floating-point precision of 6:
4265       //
4266       //   Log10ofMantissa =
4267       //     -0.50419619f +
4268       //       (0.60948995f - 0.10380950f * x) * x;
4269       //
4270       // error 0.0014886165, which is 6 bits
4271       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4272                                getF32Constant(DAG, 0xbdd49a13));
4273       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4274                                getF32Constant(DAG, 0x3f1c0789));
4275       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4276       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4277                                     getF32Constant(DAG, 0x3f011300));
4278     } else if (LimitFloatPrecision <= 12) {
4279       // For floating-point precision of 12:
4280       //
4281       //   Log10ofMantissa =
4282       //     -0.64831180f +
4283       //       (0.91751397f +
4284       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4285       //
4286       // error 0.00019228036, which is better than 12 bits
4287       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4288                                getF32Constant(DAG, 0x3d431f31));
4289       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4290                                getF32Constant(DAG, 0x3ea21fb2));
4291       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4292       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4293                                getF32Constant(DAG, 0x3f6ae232));
4294       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4295       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4296                                     getF32Constant(DAG, 0x3f25f7c3));
4297     } else { // LimitFloatPrecision <= 18
4298       // For floating-point precision of 18:
4299       //
4300       //   Log10ofMantissa =
4301       //     -0.84299375f +
4302       //       (1.5327582f +
4303       //         (-1.0688956f +
4304       //           (0.49102474f +
4305       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4306       //
4307       // error 0.0000037995730, which is better than 18 bits
4308       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4309                                getF32Constant(DAG, 0x3c5d51ce));
4310       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4311                                getF32Constant(DAG, 0x3e00685a));
4312       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4313       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4314                                getF32Constant(DAG, 0x3efb6798));
4315       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4316       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4317                                getF32Constant(DAG, 0x3f88d192));
4318       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4319       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4320                                getF32Constant(DAG, 0x3fc4316c));
4321       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4322       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4323                                     getF32Constant(DAG, 0x3f57ce70));
4324     }
4325
4326     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4327   }
4328
4329   // No special expansion.
4330   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4331 }
4332
4333 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4334 /// limited-precision mode.
4335 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4336                           const TargetLowering &TLI) {
4337   if (Op.getValueType() == MVT::f32 &&
4338       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4339     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
4340
4341     //   FractionalPartOfX = x - (float)IntegerPartOfX;
4342     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4343     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
4344
4345     //   IntegerPartOfX <<= 23;
4346     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4347                                  DAG.getConstant(23, TLI.getPointerTy()));
4348
4349     SDValue TwoToFractionalPartOfX;
4350     if (LimitFloatPrecision <= 6) {
4351       // For floating-point precision of 6:
4352       //
4353       //   TwoToFractionalPartOfX =
4354       //     0.997535578f +
4355       //       (0.735607626f + 0.252464424f * x) * x;
4356       //
4357       // error 0.0144103317, which is 6 bits
4358       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4359                                getF32Constant(DAG, 0x3e814304));
4360       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4361                                getF32Constant(DAG, 0x3f3c50c8));
4362       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4363       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4364                                            getF32Constant(DAG, 0x3f7f5e7e));
4365     } else if (LimitFloatPrecision <= 12) {
4366       // For floating-point precision of 12:
4367       //
4368       //   TwoToFractionalPartOfX =
4369       //     0.999892986f +
4370       //       (0.696457318f +
4371       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4372       //
4373       // error 0.000107046256, which is 13 to 14 bits
4374       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4375                                getF32Constant(DAG, 0x3da235e3));
4376       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4377                                getF32Constant(DAG, 0x3e65b8f3));
4378       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4379       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4380                                getF32Constant(DAG, 0x3f324b07));
4381       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4382       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4383                                            getF32Constant(DAG, 0x3f7ff8fd));
4384     } else { // LimitFloatPrecision <= 18
4385       // For floating-point precision of 18:
4386       //
4387       //   TwoToFractionalPartOfX =
4388       //     0.999999982f +
4389       //       (0.693148872f +
4390       //         (0.240227044f +
4391       //           (0.554906021e-1f +
4392       //             (0.961591928e-2f +
4393       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4394       // error 2.47208000*10^(-7), which is better than 18 bits
4395       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4396                                getF32Constant(DAG, 0x3924b03e));
4397       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4398                                getF32Constant(DAG, 0x3ab24b87));
4399       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4400       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4401                                getF32Constant(DAG, 0x3c1d8c17));
4402       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4403       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4404                                getF32Constant(DAG, 0x3d634a1d));
4405       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4406       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4407                                getF32Constant(DAG, 0x3e75fe14));
4408       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4409       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4410                                 getF32Constant(DAG, 0x3f317234));
4411       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4412       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4413                                            getF32Constant(DAG, 0x3f800000));
4414     }
4415
4416     // Add the exponent into the result in integer domain.
4417     SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4418                               TwoToFractionalPartOfX);
4419     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4420                        DAG.getNode(ISD::ADD, dl, MVT::i32,
4421                                    t13, IntegerPartOfX));
4422   }
4423
4424   // No special expansion.
4425   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4426 }
4427
4428 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4429 /// limited-precision mode with x == 10.0f.
4430 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4431                          SelectionDAG &DAG, const TargetLowering &TLI) {
4432   bool IsExp10 = false;
4433   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4434       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4435     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4436       APFloat Ten(10.0f);
4437       IsExp10 = LHSC->isExactlyValue(Ten);
4438     }
4439   }
4440
4441   if (IsExp10) {
4442     // Put the exponent in the right bit position for later addition to the
4443     // final result:
4444     //
4445     //   #define LOG2OF10 3.3219281f
4446     //   IntegerPartOfX = (int32_t)(x * LOG2OF10);
4447     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4448                              getF32Constant(DAG, 0x40549a78));
4449     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4450
4451     //   FractionalPartOfX = x - (float)IntegerPartOfX;
4452     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4453     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4454
4455     //   IntegerPartOfX <<= 23;
4456     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4457                                  DAG.getConstant(23, TLI.getPointerTy()));
4458
4459     SDValue TwoToFractionalPartOfX;
4460     if (LimitFloatPrecision <= 6) {
4461       // For floating-point precision of 6:
4462       //
4463       //   twoToFractionalPartOfX =
4464       //     0.997535578f +
4465       //       (0.735607626f + 0.252464424f * x) * x;
4466       //
4467       // error 0.0144103317, which is 6 bits
4468       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4469                                getF32Constant(DAG, 0x3e814304));
4470       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4471                                getF32Constant(DAG, 0x3f3c50c8));
4472       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4473       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4474                                            getF32Constant(DAG, 0x3f7f5e7e));
4475     } else if (LimitFloatPrecision <= 12) {
4476       // For floating-point precision of 12:
4477       //
4478       //   TwoToFractionalPartOfX =
4479       //     0.999892986f +
4480       //       (0.696457318f +
4481       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4482       //
4483       // error 0.000107046256, which is 13 to 14 bits
4484       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4485                                getF32Constant(DAG, 0x3da235e3));
4486       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4487                                getF32Constant(DAG, 0x3e65b8f3));
4488       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4489       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4490                                getF32Constant(DAG, 0x3f324b07));
4491       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4492       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4493                                            getF32Constant(DAG, 0x3f7ff8fd));
4494     } else { // LimitFloatPrecision <= 18
4495       // For floating-point precision of 18:
4496       //
4497       //   TwoToFractionalPartOfX =
4498       //     0.999999982f +
4499       //       (0.693148872f +
4500       //         (0.240227044f +
4501       //           (0.554906021e-1f +
4502       //             (0.961591928e-2f +
4503       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4504       // error 2.47208000*10^(-7), which is better than 18 bits
4505       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4506                                getF32Constant(DAG, 0x3924b03e));
4507       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4508                                getF32Constant(DAG, 0x3ab24b87));
4509       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4510       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4511                                getF32Constant(DAG, 0x3c1d8c17));
4512       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4513       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4514                                getF32Constant(DAG, 0x3d634a1d));
4515       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4516       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4517                                getF32Constant(DAG, 0x3e75fe14));
4518       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4519       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4520                                 getF32Constant(DAG, 0x3f317234));
4521       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4522       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4523                                            getF32Constant(DAG, 0x3f800000));
4524     }
4525
4526     SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
4527     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4528                        DAG.getNode(ISD::ADD, dl, MVT::i32,
4529                                    t13, IntegerPartOfX));
4530   }
4531
4532   // No special expansion.
4533   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4534 }
4535
4536
4537 /// ExpandPowI - Expand a llvm.powi intrinsic.
4538 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4539                           SelectionDAG &DAG) {
4540   // If RHS is a constant, we can expand this out to a multiplication tree,
4541   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4542   // optimizing for size, we only want to do this if the expansion would produce
4543   // a small number of multiplies, otherwise we do the full expansion.
4544   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4545     // Get the exponent as a positive value.
4546     unsigned Val = RHSC->getSExtValue();
4547     if ((int)Val < 0) Val = -Val;
4548
4549     // powi(x, 0) -> 1.0
4550     if (Val == 0)
4551       return DAG.getConstantFP(1.0, LHS.getValueType());
4552
4553     const Function *F = DAG.getMachineFunction().getFunction();
4554     if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4555                                          Attribute::OptimizeForSize) ||
4556         // If optimizing for size, don't insert too many multiplies.  This
4557         // inserts up to 5 multiplies.
4558         CountPopulation_32(Val)+Log2_32(Val) < 7) {
4559       // We use the simple binary decomposition method to generate the multiply
4560       // sequence.  There are more optimal ways to do this (for example,
4561       // powi(x,15) generates one more multiply than it should), but this has
4562       // the benefit of being both really simple and much better than a libcall.
4563       SDValue Res;  // Logically starts equal to 1.0
4564       SDValue CurSquare = LHS;
4565       while (Val) {
4566         if (Val & 1) {
4567           if (Res.getNode())
4568             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4569           else
4570             Res = CurSquare;  // 1.0*CurSquare.
4571         }
4572
4573         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4574                                 CurSquare, CurSquare);
4575         Val >>= 1;
4576       }
4577
4578       // If the original was negative, invert the result, producing 1/(x*x*x).
4579       if (RHSC->getSExtValue() < 0)
4580         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4581                           DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4582       return Res;
4583     }
4584   }
4585
4586   // Otherwise, expand to a libcall.
4587   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4588 }
4589
4590 // getTruncatedArgReg - Find underlying register used for an truncated
4591 // argument.
4592 static unsigned getTruncatedArgReg(const SDValue &N) {
4593   if (N.getOpcode() != ISD::TRUNCATE)
4594     return 0;
4595
4596   const SDValue &Ext = N.getOperand(0);
4597   if (Ext.getOpcode() == ISD::AssertZext ||
4598       Ext.getOpcode() == ISD::AssertSext) {
4599     const SDValue &CFR = Ext.getOperand(0);
4600     if (CFR.getOpcode() == ISD::CopyFromReg)
4601       return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4602     if (CFR.getOpcode() == ISD::TRUNCATE)
4603       return getTruncatedArgReg(CFR);
4604   }
4605   return 0;
4606 }
4607
4608 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4609 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4610 /// At the end of instruction selection, they will be inserted to the entry BB.
4611 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V,
4612                                                    MDNode *Variable,
4613                                                    MDNode *Expr, int64_t Offset,
4614                                                    bool IsIndirect,
4615                                                    const SDValue &N) {
4616   const Argument *Arg = dyn_cast<Argument>(V);
4617   if (!Arg)
4618     return false;
4619
4620   MachineFunction &MF = DAG.getMachineFunction();
4621   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4622
4623   // Ignore inlined function arguments here.
4624   DIVariable DV(Variable);
4625   if (DV.isInlinedFnArgument(MF.getFunction()))
4626     return false;
4627
4628   Optional<MachineOperand> Op;
4629   // Some arguments' frame index is recorded during argument lowering.
4630   if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4631     Op = MachineOperand::CreateFI(FI);
4632
4633   if (!Op && N.getNode()) {
4634     unsigned Reg;
4635     if (N.getOpcode() == ISD::CopyFromReg)
4636       Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4637     else
4638       Reg = getTruncatedArgReg(N);
4639     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4640       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4641       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4642       if (PR)
4643         Reg = PR;
4644     }
4645     if (Reg)
4646       Op = MachineOperand::CreateReg(Reg, false);
4647   }
4648
4649   if (!Op) {
4650     // Check if ValueMap has reg number.
4651     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4652     if (VMI != FuncInfo.ValueMap.end())
4653       Op = MachineOperand::CreateReg(VMI->second, false);
4654   }
4655
4656   if (!Op && N.getNode())
4657     // Check if frame index is available.
4658     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4659       if (FrameIndexSDNode *FINode =
4660           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4661         Op = MachineOperand::CreateFI(FINode->getIndex());
4662
4663   if (!Op)
4664     return false;
4665
4666   if (Op->isReg())
4667     FuncInfo.ArgDbgValues.push_back(
4668         BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE),
4669                 IsIndirect, Op->getReg(), Offset, Variable, Expr));
4670   else
4671     FuncInfo.ArgDbgValues.push_back(
4672         BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4673             .addOperand(*Op)
4674             .addImm(Offset)
4675             .addMetadata(Variable)
4676             .addMetadata(Expr));
4677
4678   return true;
4679 }
4680
4681 // VisualStudio defines setjmp as _setjmp
4682 #if defined(_MSC_VER) && defined(setjmp) && \
4683                          !defined(setjmp_undefined_for_msvc)
4684 #  pragma push_macro("setjmp")
4685 #  undef setjmp
4686 #  define setjmp_undefined_for_msvc
4687 #endif
4688
4689 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
4690 /// we want to emit this as a call to a named external function, return the name
4691 /// otherwise lower it and return null.
4692 const char *
4693 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4695   SDLoc sdl = getCurSDLoc();
4696   DebugLoc dl = getCurDebugLoc();
4697   SDValue Res;
4698
4699   switch (Intrinsic) {
4700   default:
4701     // By default, turn this into a target intrinsic node.
4702     visitTargetIntrinsic(I, Intrinsic);
4703     return nullptr;
4704   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
4705   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
4706   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
4707   case Intrinsic::returnaddress:
4708     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI.getPointerTy(),
4709                              getValue(I.getArgOperand(0))));
4710     return nullptr;
4711   case Intrinsic::frameaddress:
4712     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4713                              getValue(I.getArgOperand(0))));
4714     return nullptr;
4715   case Intrinsic::read_register: {
4716     Value *Reg = I.getArgOperand(0);
4717     SDValue RegName =
4718         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4719     EVT VT = TLI.getValueType(I.getType());
4720     setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
4721     return nullptr;
4722   }
4723   case Intrinsic::write_register: {
4724     Value *Reg = I.getArgOperand(0);
4725     Value *RegValue = I.getArgOperand(1);
4726     SDValue Chain = getValue(RegValue).getOperand(0);
4727     SDValue RegName =
4728         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4729     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4730                             RegName, getValue(RegValue)));
4731     return nullptr;
4732   }
4733   case Intrinsic::setjmp:
4734     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
4735   case Intrinsic::longjmp:
4736     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
4737   case Intrinsic::memcpy: {
4738     // Assert for address < 256 since we support only user defined address
4739     // spaces.
4740     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4741            < 256 &&
4742            cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4743            < 256 &&
4744            "Unknown address space");
4745     SDValue Op1 = getValue(I.getArgOperand(0));
4746     SDValue Op2 = getValue(I.getArgOperand(1));
4747     SDValue Op3 = getValue(I.getArgOperand(2));
4748     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4749     if (!Align)
4750       Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4751     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4752     DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
4753                               MachinePointerInfo(I.getArgOperand(0)),
4754                               MachinePointerInfo(I.getArgOperand(1))));
4755     return nullptr;
4756   }
4757   case Intrinsic::memset: {
4758     // Assert for address < 256 since we support only user defined address
4759     // spaces.
4760     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4761            < 256 &&
4762            "Unknown address space");
4763     SDValue Op1 = getValue(I.getArgOperand(0));
4764     SDValue Op2 = getValue(I.getArgOperand(1));
4765     SDValue Op3 = getValue(I.getArgOperand(2));
4766     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4767     if (!Align)
4768       Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4769     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4770     DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4771                               MachinePointerInfo(I.getArgOperand(0))));
4772     return nullptr;
4773   }
4774   case Intrinsic::memmove: {
4775     // Assert for address < 256 since we support only user defined address
4776     // spaces.
4777     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4778            < 256 &&
4779            cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4780            < 256 &&
4781            "Unknown address space");
4782     SDValue Op1 = getValue(I.getArgOperand(0));
4783     SDValue Op2 = getValue(I.getArgOperand(1));
4784     SDValue Op3 = getValue(I.getArgOperand(2));
4785     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4786     if (!Align)
4787       Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4788     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4789     DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4790                                MachinePointerInfo(I.getArgOperand(0)),
4791                                MachinePointerInfo(I.getArgOperand(1))));
4792     return nullptr;
4793   }
4794   case Intrinsic::dbg_declare: {
4795     const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4796     MDNode *Variable = DI.getVariable();
4797     MDNode *Expression = DI.getExpression();
4798     const Value *Address = DI.getAddress();
4799     DIVariable DIVar(Variable);
4800     assert((!DIVar || DIVar.isVariable()) &&
4801       "Variable in DbgDeclareInst should be either null or a DIVariable.");
4802     if (!Address || !DIVar) {
4803       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4804       return nullptr;
4805     }
4806
4807     // Check if address has undef value.
4808     if (isa<UndefValue>(Address) ||
4809         (Address->use_empty() && !isa<Argument>(Address))) {
4810       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4811       return nullptr;
4812     }
4813
4814     SDValue &N = NodeMap[Address];
4815     if (!N.getNode() && isa<Argument>(Address))
4816       // Check unused arguments map.
4817       N = UnusedArgNodeMap[Address];
4818     SDDbgValue *SDV;
4819     if (N.getNode()) {
4820       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4821         Address = BCI->getOperand(0);
4822       // Parameters are handled specially.
4823       bool isParameter =
4824         (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4825          isa<Argument>(Address));
4826
4827       const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4828
4829       if (isParameter && !AI) {
4830         FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4831         if (FINode)
4832           // Byval parameter.  We have a frame index at this point.
4833           SDV = DAG.getFrameIndexDbgValue(
4834               Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
4835         else {
4836           // Address is an argument, so try to emit its dbg value using
4837           // virtual register info from the FuncInfo.ValueMap.
4838           EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false, N);
4839           return nullptr;
4840         }
4841       } else if (AI)
4842         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4843                               true, 0, dl, SDNodeOrder);
4844       else {
4845         // Can't do anything with other non-AI cases yet.
4846         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4847         DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4848         DEBUG(Address->dump());
4849         return nullptr;
4850       }
4851       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4852     } else {
4853       // If Address is an argument then try to emit its dbg value using
4854       // virtual register info from the FuncInfo.ValueMap.
4855       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false,
4856                                     N)) {
4857         // If variable is pinned by a alloca in dominating bb then
4858         // use StaticAllocaMap.
4859         if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4860           if (AI->getParent() != DI.getParent()) {
4861             DenseMap<const AllocaInst*, int>::iterator SI =
4862               FuncInfo.StaticAllocaMap.find(AI);
4863             if (SI != FuncInfo.StaticAllocaMap.end()) {
4864               SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
4865                                               0, dl, SDNodeOrder);
4866               DAG.AddDbgValue(SDV, nullptr, false);
4867               return nullptr;
4868             }
4869           }
4870         }
4871         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4872       }
4873     }
4874     return nullptr;
4875   }
4876   case Intrinsic::dbg_value: {
4877     const DbgValueInst &DI = cast<DbgValueInst>(I);
4878     DIVariable DIVar(DI.getVariable());
4879     assert((!DIVar || DIVar.isVariable()) &&
4880       "Variable in DbgValueInst should be either null or a DIVariable.");
4881     if (!DIVar)
4882       return nullptr;
4883
4884     MDNode *Variable = DI.getVariable();
4885     MDNode *Expression = DI.getExpression();
4886     uint64_t Offset = DI.getOffset();
4887     const Value *V = DI.getValue();
4888     if (!V)
4889       return nullptr;
4890
4891     SDDbgValue *SDV;
4892     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4893       SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4894                                     SDNodeOrder);
4895       DAG.AddDbgValue(SDV, nullptr, false);
4896     } else {
4897       // Do not use getValue() in here; we don't want to generate code at
4898       // this point if it hasn't been done yet.
4899       SDValue N = NodeMap[V];
4900       if (!N.getNode() && isa<Argument>(V))
4901         // Check unused arguments map.
4902         N = UnusedArgNodeMap[V];
4903       if (N.getNode()) {
4904         // A dbg.value for an alloca is always indirect.
4905         bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
4906         if (!EmitFuncArgumentDbgValue(V, Variable, Expression, Offset,
4907                                       IsIndirect, N)) {
4908           SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4909                                 IsIndirect, Offset, dl, SDNodeOrder);
4910           DAG.AddDbgValue(SDV, N.getNode(), false);
4911         }
4912       } else if (!V->use_empty() ) {
4913         // Do not call getValue(V) yet, as we don't want to generate code.
4914         // Remember it for later.
4915         DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4916         DanglingDebugInfoMap[V] = DDI;
4917       } else {
4918         // We may expand this to cover more cases.  One case where we have no
4919         // data available is an unreferenced parameter.
4920         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4921       }
4922     }
4923
4924     // Build a debug info table entry.
4925     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4926       V = BCI->getOperand(0);
4927     const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4928     // Don't handle byval struct arguments or VLAs, for example.
4929     if (!AI) {
4930       DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
4931       DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
4932       return nullptr;
4933     }
4934     DenseMap<const AllocaInst*, int>::iterator SI =
4935       FuncInfo.StaticAllocaMap.find(AI);
4936     if (SI == FuncInfo.StaticAllocaMap.end())
4937       return nullptr; // VLAs.
4938     return nullptr;
4939   }
4940
4941   case Intrinsic::eh_typeid_for: {
4942     // Find the type id for the given typeinfo.
4943     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
4944     unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4945     Res = DAG.getConstant(TypeID, MVT::i32);
4946     setValue(&I, Res);
4947     return nullptr;
4948   }
4949
4950   case Intrinsic::eh_return_i32:
4951   case Intrinsic::eh_return_i64:
4952     DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4953     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4954                             MVT::Other,
4955                             getControlRoot(),
4956                             getValue(I.getArgOperand(0)),
4957                             getValue(I.getArgOperand(1))));
4958     return nullptr;
4959   case Intrinsic::eh_unwind_init:
4960     DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4961     return nullptr;
4962   case Intrinsic::eh_dwarf_cfa: {
4963     SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4964                                         TLI.getPointerTy());
4965     SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4966                                  CfaArg.getValueType(),
4967                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4968                                              CfaArg.getValueType()),
4969                                  CfaArg);
4970     SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4971                              DAG.getConstant(0, TLI.getPointerTy()));
4972     setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4973                              FA, Offset));
4974     return nullptr;
4975   }
4976   case Intrinsic::eh_sjlj_callsite: {
4977     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4978     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4979     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4980     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4981
4982     MMI.setCurrentCallSite(CI->getZExtValue());
4983     return nullptr;
4984   }
4985   case Intrinsic::eh_sjlj_functioncontext: {
4986     // Get and store the index of the function context.
4987     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4988     AllocaInst *FnCtx =
4989       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4990     int FI = FuncInfo.StaticAllocaMap[FnCtx];
4991     MFI->setFunctionContextIndex(FI);
4992     return nullptr;
4993   }
4994   case Intrinsic::eh_sjlj_setjmp: {
4995     SDValue Ops[2];
4996     Ops[0] = getRoot();
4997     Ops[1] = getValue(I.getArgOperand(0));
4998     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4999                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5000     setValue(&I, Op.getValue(0));
5001     DAG.setRoot(Op.getValue(1));
5002     return nullptr;
5003   }
5004   case Intrinsic::eh_sjlj_longjmp: {
5005     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5006                             getRoot(), getValue(I.getArgOperand(0))));
5007     return nullptr;
5008   }
5009
5010   case Intrinsic::masked_load:
5011     visitMaskedLoad(I);
5012     return nullptr;
5013   case Intrinsic::masked_store:
5014     visitMaskedStore(I);
5015     return nullptr;
5016   case Intrinsic::x86_mmx_pslli_w:
5017   case Intrinsic::x86_mmx_pslli_d:
5018   case Intrinsic::x86_mmx_pslli_q:
5019   case Intrinsic::x86_mmx_psrli_w:
5020   case Intrinsic::x86_mmx_psrli_d:
5021   case Intrinsic::x86_mmx_psrli_q:
5022   case Intrinsic::x86_mmx_psrai_w:
5023   case Intrinsic::x86_mmx_psrai_d: {
5024     SDValue ShAmt = getValue(I.getArgOperand(1));
5025     if (isa<ConstantSDNode>(ShAmt)) {
5026       visitTargetIntrinsic(I, Intrinsic);
5027       return nullptr;
5028     }
5029     unsigned NewIntrinsic = 0;
5030     EVT ShAmtVT = MVT::v2i32;
5031     switch (Intrinsic) {
5032     case Intrinsic::x86_mmx_pslli_w:
5033       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5034       break;
5035     case Intrinsic::x86_mmx_pslli_d:
5036       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5037       break;
5038     case Intrinsic::x86_mmx_pslli_q:
5039       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5040       break;
5041     case Intrinsic::x86_mmx_psrli_w:
5042       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5043       break;
5044     case Intrinsic::x86_mmx_psrli_d:
5045       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5046       break;
5047     case Intrinsic::x86_mmx_psrli_q:
5048       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5049       break;
5050     case Intrinsic::x86_mmx_psrai_w:
5051       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5052       break;
5053     case Intrinsic::x86_mmx_psrai_d:
5054       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5055       break;
5056     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5057     }
5058
5059     // The vector shift intrinsics with scalars uses 32b shift amounts but
5060     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5061     // to be zero.
5062     // We must do this early because v2i32 is not a legal type.
5063     SDValue ShOps[2];
5064     ShOps[0] = ShAmt;
5065     ShOps[1] = DAG.getConstant(0, MVT::i32);
5066     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
5067     EVT DestVT = TLI.getValueType(I.getType());
5068     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5069     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5070                        DAG.getConstant(NewIntrinsic, MVT::i32),
5071                        getValue(I.getArgOperand(0)), ShAmt);
5072     setValue(&I, Res);
5073     return nullptr;
5074   }
5075   case Intrinsic::x86_avx_vinsertf128_pd_256:
5076   case Intrinsic::x86_avx_vinsertf128_ps_256:
5077   case Intrinsic::x86_avx_vinsertf128_si_256:
5078   case Intrinsic::x86_avx2_vinserti128: {
5079     EVT DestVT = TLI.getValueType(I.getType());
5080     EVT ElVT = TLI.getValueType(I.getArgOperand(1)->getType());
5081     uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
5082                    ElVT.getVectorNumElements();
5083     Res =
5084         DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
5085                     getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
5086                     DAG.getConstant(Idx, TLI.getVectorIdxTy()));
5087     setValue(&I, Res);
5088     return nullptr;
5089   }
5090   case Intrinsic::x86_avx_vextractf128_pd_256:
5091   case Intrinsic::x86_avx_vextractf128_ps_256:
5092   case Intrinsic::x86_avx_vextractf128_si_256:
5093   case Intrinsic::x86_avx2_vextracti128: {
5094     EVT DestVT = TLI.getValueType(I.getType());
5095     uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
5096                    DestVT.getVectorNumElements();
5097     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
5098                       getValue(I.getArgOperand(0)),
5099                       DAG.getConstant(Idx, TLI.getVectorIdxTy()));
5100     setValue(&I, Res);
5101     return nullptr;
5102   }
5103   case Intrinsic::convertff:
5104   case Intrinsic::convertfsi:
5105   case Intrinsic::convertfui:
5106   case Intrinsic::convertsif:
5107   case Intrinsic::convertuif:
5108   case Intrinsic::convertss:
5109   case Intrinsic::convertsu:
5110   case Intrinsic::convertus:
5111   case Intrinsic::convertuu: {
5112     ISD::CvtCode Code = ISD::CVT_INVALID;
5113     switch (Intrinsic) {
5114     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5115     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
5116     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
5117     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
5118     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
5119     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
5120     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
5121     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
5122     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
5123     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
5124     }
5125     EVT DestVT = TLI.getValueType(I.getType());
5126     const Value *Op1 = I.getArgOperand(0);
5127     Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
5128                                DAG.getValueType(DestVT),
5129                                DAG.getValueType(getValue(Op1).getValueType()),
5130                                getValue(I.getArgOperand(1)),
5131                                getValue(I.getArgOperand(2)),
5132                                Code);
5133     setValue(&I, Res);
5134     return nullptr;
5135   }
5136   case Intrinsic::powi:
5137     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5138                             getValue(I.getArgOperand(1)), DAG));
5139     return nullptr;
5140   case Intrinsic::log:
5141     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5142     return nullptr;
5143   case Intrinsic::log2:
5144     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5145     return nullptr;
5146   case Intrinsic::log10:
5147     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5148     return nullptr;
5149   case Intrinsic::exp:
5150     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5151     return nullptr;
5152   case Intrinsic::exp2:
5153     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5154     return nullptr;
5155   case Intrinsic::pow:
5156     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5157                            getValue(I.getArgOperand(1)), DAG, TLI));
5158     return nullptr;
5159   case Intrinsic::sqrt:
5160   case Intrinsic::fabs:
5161   case Intrinsic::sin:
5162   case Intrinsic::cos:
5163   case Intrinsic::floor:
5164   case Intrinsic::ceil:
5165   case Intrinsic::trunc:
5166   case Intrinsic::rint:
5167   case Intrinsic::nearbyint:
5168   case Intrinsic::round: {
5169     unsigned Opcode;
5170     switch (Intrinsic) {
5171     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5172     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5173     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5174     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5175     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5176     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5177     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5178     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5179     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5180     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5181     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5182     }
5183
5184     setValue(&I, DAG.getNode(Opcode, sdl,
5185                              getValue(I.getArgOperand(0)).getValueType(),
5186                              getValue(I.getArgOperand(0))));
5187     return nullptr;
5188   }
5189   case Intrinsic::minnum:
5190     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
5191                              getValue(I.getArgOperand(0)).getValueType(),
5192                              getValue(I.getArgOperand(0)),
5193                              getValue(I.getArgOperand(1))));
5194     return nullptr;
5195   case Intrinsic::maxnum:
5196     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
5197                              getValue(I.getArgOperand(0)).getValueType(),
5198                              getValue(I.getArgOperand(0)),
5199                              getValue(I.getArgOperand(1))));
5200     return nullptr;
5201   case Intrinsic::copysign:
5202     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5203                              getValue(I.getArgOperand(0)).getValueType(),
5204                              getValue(I.getArgOperand(0)),
5205                              getValue(I.getArgOperand(1))));
5206     return nullptr;
5207   case Intrinsic::fma:
5208     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5209                              getValue(I.getArgOperand(0)).getValueType(),
5210                              getValue(I.getArgOperand(0)),
5211                              getValue(I.getArgOperand(1)),
5212                              getValue(I.getArgOperand(2))));
5213     return nullptr;
5214   case Intrinsic::fmuladd: {
5215     EVT VT = TLI.getValueType(I.getType());
5216     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5217         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5218       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5219                                getValue(I.getArgOperand(0)).getValueType(),
5220                                getValue(I.getArgOperand(0)),
5221                                getValue(I.getArgOperand(1)),
5222                                getValue(I.getArgOperand(2))));
5223     } else {
5224       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5225                                 getValue(I.getArgOperand(0)).getValueType(),
5226                                 getValue(I.getArgOperand(0)),
5227                                 getValue(I.getArgOperand(1)));
5228       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5229                                 getValue(I.getArgOperand(0)).getValueType(),
5230                                 Mul,
5231                                 getValue(I.getArgOperand(2)));
5232       setValue(&I, Add);
5233     }
5234     return nullptr;
5235   }
5236   case Intrinsic::convert_to_fp16:
5237     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5238                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5239                                          getValue(I.getArgOperand(0)),
5240                                          DAG.getTargetConstant(0, MVT::i32))));
5241     return nullptr;
5242   case Intrinsic::convert_from_fp16:
5243     setValue(&I,
5244              DAG.getNode(ISD::FP_EXTEND, sdl, TLI.getValueType(I.getType()),
5245                          DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5246                                      getValue(I.getArgOperand(0)))));
5247     return nullptr;
5248   case Intrinsic::pcmarker: {
5249     SDValue Tmp = getValue(I.getArgOperand(0));
5250     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5251     return nullptr;
5252   }
5253   case Intrinsic::readcyclecounter: {
5254     SDValue Op = getRoot();
5255     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5256                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5257     setValue(&I, Res);
5258     DAG.setRoot(Res.getValue(1));
5259     return nullptr;
5260   }
5261   case Intrinsic::bswap:
5262     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5263                              getValue(I.getArgOperand(0)).getValueType(),
5264                              getValue(I.getArgOperand(0))));
5265     return nullptr;
5266   case Intrinsic::cttz: {
5267     SDValue Arg = getValue(I.getArgOperand(0));
5268     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5269     EVT Ty = Arg.getValueType();
5270     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5271                              sdl, Ty, Arg));
5272     return nullptr;
5273   }
5274   case Intrinsic::ctlz: {
5275     SDValue Arg = getValue(I.getArgOperand(0));
5276     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5277     EVT Ty = Arg.getValueType();
5278     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5279                              sdl, Ty, Arg));
5280     return nullptr;
5281   }
5282   case Intrinsic::ctpop: {
5283     SDValue Arg = getValue(I.getArgOperand(0));
5284     EVT Ty = Arg.getValueType();
5285     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5286     return nullptr;
5287   }
5288   case Intrinsic::stacksave: {
5289     SDValue Op = getRoot();
5290     Res = DAG.getNode(ISD::STACKSAVE, sdl,
5291                       DAG.getVTList(TLI.getPointerTy(), MVT::Other), Op);
5292     setValue(&I, Res);
5293     DAG.setRoot(Res.getValue(1));
5294     return nullptr;
5295   }
5296   case Intrinsic::stackrestore: {
5297     Res = getValue(I.getArgOperand(0));
5298     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5299     return nullptr;
5300   }
5301   case Intrinsic::stackprotector: {
5302     // Emit code into the DAG to store the stack guard onto the stack.
5303     MachineFunction &MF = DAG.getMachineFunction();
5304     MachineFrameInfo *MFI = MF.getFrameInfo();
5305     EVT PtrTy = TLI.getPointerTy();
5306     SDValue Src, Chain = getRoot();
5307     const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
5308     const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
5309
5310     // See if Ptr is a bitcast. If it is, look through it and see if we can get
5311     // global variable __stack_chk_guard.
5312     if (!GV)
5313       if (const Operator *BC = dyn_cast<Operator>(Ptr))
5314         if (BC->getOpcode() == Instruction::BitCast)
5315           GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
5316
5317     if (GV && TLI.useLoadStackGuardNode()) {
5318       // Emit a LOAD_STACK_GUARD node.
5319       MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
5320                                                sdl, PtrTy, Chain);
5321       MachinePointerInfo MPInfo(GV);
5322       MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
5323       unsigned Flags = MachineMemOperand::MOLoad |
5324                        MachineMemOperand::MOInvariant;
5325       *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
5326                                          PtrTy.getSizeInBits() / 8,
5327                                          DAG.getEVTAlignment(PtrTy));
5328       Node->setMemRefs(MemRefs, MemRefs + 1);
5329
5330       // Copy the guard value to a virtual register so that it can be
5331       // retrieved in the epilogue.
5332       Src = SDValue(Node, 0);
5333       const TargetRegisterClass *RC =
5334           TLI.getRegClassFor(Src.getSimpleValueType());
5335       unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
5336
5337       SPDescriptor.setGuardReg(Reg);
5338       Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
5339     } else {
5340       Src = getValue(I.getArgOperand(0));   // The guard's value.
5341     }
5342
5343     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5344
5345     int FI = FuncInfo.StaticAllocaMap[Slot];
5346     MFI->setStackProtectorIndex(FI);
5347
5348     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5349
5350     // Store the stack protector onto the stack.
5351     Res = DAG.getStore(Chain, sdl, Src, FIN,
5352                        MachinePointerInfo::getFixedStack(FI),
5353                        true, false, 0);
5354     setValue(&I, Res);
5355     DAG.setRoot(Res);
5356     return nullptr;
5357   }
5358   case Intrinsic::objectsize: {
5359     // If we don't know by now, we're never going to know.
5360     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5361
5362     assert(CI && "Non-constant type in __builtin_object_size?");
5363
5364     SDValue Arg = getValue(I.getCalledValue());
5365     EVT Ty = Arg.getValueType();
5366
5367     if (CI->isZero())
5368       Res = DAG.getConstant(-1ULL, Ty);
5369     else
5370       Res = DAG.getConstant(0, Ty);
5371
5372     setValue(&I, Res);
5373     return nullptr;
5374   }
5375   case Intrinsic::annotation:
5376   case Intrinsic::ptr_annotation:
5377     // Drop the intrinsic, but forward the value
5378     setValue(&I, getValue(I.getOperand(0)));
5379     return nullptr;
5380   case Intrinsic::assume:
5381   case Intrinsic::var_annotation:
5382     // Discard annotate attributes and assumptions
5383     return nullptr;
5384
5385   case Intrinsic::init_trampoline: {
5386     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5387
5388     SDValue Ops[6];
5389     Ops[0] = getRoot();
5390     Ops[1] = getValue(I.getArgOperand(0));
5391     Ops[2] = getValue(I.getArgOperand(1));
5392     Ops[3] = getValue(I.getArgOperand(2));
5393     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5394     Ops[5] = DAG.getSrcValue(F);
5395
5396     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5397
5398     DAG.setRoot(Res);
5399     return nullptr;
5400   }
5401   case Intrinsic::adjust_trampoline: {
5402     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5403                              TLI.getPointerTy(),
5404                              getValue(I.getArgOperand(0))));
5405     return nullptr;
5406   }
5407   case Intrinsic::gcroot:
5408     if (GFI) {
5409       const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5410       const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5411
5412       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5413       GFI->addStackRoot(FI->getIndex(), TypeMap);
5414     }
5415     return nullptr;
5416   case Intrinsic::gcread:
5417   case Intrinsic::gcwrite:
5418     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5419   case Intrinsic::flt_rounds:
5420     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5421     return nullptr;
5422
5423   case Intrinsic::expect: {
5424     // Just replace __builtin_expect(exp, c) with EXP.
5425     setValue(&I, getValue(I.getArgOperand(0)));
5426     return nullptr;
5427   }
5428
5429   case Intrinsic::debugtrap:
5430   case Intrinsic::trap: {
5431     StringRef TrapFuncName = TM.Options.getTrapFunctionName();
5432     if (TrapFuncName.empty()) {
5433       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5434         ISD::TRAP : ISD::DEBUGTRAP;
5435       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5436       return nullptr;
5437     }
5438     TargetLowering::ArgListTy Args;
5439
5440     TargetLowering::CallLoweringInfo CLI(DAG);
5441     CLI.setDebugLoc(sdl).setChain(getRoot())
5442       .setCallee(CallingConv::C, I.getType(),
5443                  DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
5444                  std::move(Args), 0);
5445
5446     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5447     DAG.setRoot(Result.second);
5448     return nullptr;
5449   }
5450
5451   case Intrinsic::uadd_with_overflow:
5452   case Intrinsic::sadd_with_overflow:
5453   case Intrinsic::usub_with_overflow:
5454   case Intrinsic::ssub_with_overflow:
5455   case Intrinsic::umul_with_overflow:
5456   case Intrinsic::smul_with_overflow: {
5457     ISD::NodeType Op;
5458     switch (Intrinsic) {
5459     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5460     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5461     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5462     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5463     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5464     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5465     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5466     }
5467     SDValue Op1 = getValue(I.getArgOperand(0));
5468     SDValue Op2 = getValue(I.getArgOperand(1));
5469
5470     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5471     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5472     return nullptr;
5473   }
5474   case Intrinsic::prefetch: {
5475     SDValue Ops[5];
5476     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5477     Ops[0] = getRoot();
5478     Ops[1] = getValue(I.getArgOperand(0));
5479     Ops[2] = getValue(I.getArgOperand(1));
5480     Ops[3] = getValue(I.getArgOperand(2));
5481     Ops[4] = getValue(I.getArgOperand(3));
5482     DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5483                                         DAG.getVTList(MVT::Other), Ops,
5484                                         EVT::getIntegerVT(*Context, 8),
5485                                         MachinePointerInfo(I.getArgOperand(0)),
5486                                         0, /* align */
5487                                         false, /* volatile */
5488                                         rw==0, /* read */
5489                                         rw==1)); /* write */
5490     return nullptr;
5491   }
5492   case Intrinsic::lifetime_start:
5493   case Intrinsic::lifetime_end: {
5494     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5495     // Stack coloring is not enabled in O0, discard region information.
5496     if (TM.getOptLevel() == CodeGenOpt::None)
5497       return nullptr;
5498
5499     SmallVector<Value *, 4> Allocas;
5500     GetUnderlyingObjects(I.getArgOperand(1), Allocas, DL);
5501
5502     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5503            E = Allocas.end(); Object != E; ++Object) {
5504       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5505
5506       // Could not find an Alloca.
5507       if (!LifetimeObject)
5508         continue;
5509
5510       // First check that the Alloca is static, otherwise it won't have a
5511       // valid frame index.
5512       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5513       if (SI == FuncInfo.StaticAllocaMap.end())
5514         return nullptr;
5515
5516       int FI = SI->second;
5517
5518       SDValue Ops[2];
5519       Ops[0] = getRoot();
5520       Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
5521       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5522
5523       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5524       DAG.setRoot(Res);
5525     }
5526     return nullptr;
5527   }
5528   case Intrinsic::invariant_start:
5529     // Discard region information.
5530     setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
5531     return nullptr;
5532   case Intrinsic::invariant_end:
5533     // Discard region information.
5534     return nullptr;
5535   case Intrinsic::stackprotectorcheck: {
5536     // Do not actually emit anything for this basic block. Instead we initialize
5537     // the stack protector descriptor and export the guard variable so we can
5538     // access it in FinishBasicBlock.
5539     const BasicBlock *BB = I.getParent();
5540     SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5541     ExportFromCurrentBlock(SPDescriptor.getGuard());
5542
5543     // Flush our exports since we are going to process a terminator.
5544     (void)getControlRoot();
5545     return nullptr;
5546   }
5547   case Intrinsic::clear_cache:
5548     return TLI.getClearCacheBuiltinName();
5549   case Intrinsic::donothing:
5550     // ignore
5551     return nullptr;
5552   case Intrinsic::experimental_stackmap: {
5553     visitStackmap(I);
5554     return nullptr;
5555   }
5556   case Intrinsic::experimental_patchpoint_void:
5557   case Intrinsic::experimental_patchpoint_i64: {
5558     visitPatchpoint(&I);
5559     return nullptr;
5560   }
5561   case Intrinsic::experimental_gc_statepoint: {
5562     visitStatepoint(I);
5563     return nullptr;
5564   }
5565   case Intrinsic::experimental_gc_result_int:
5566   case Intrinsic::experimental_gc_result_float:
5567   case Intrinsic::experimental_gc_result_ptr: {
5568     visitGCResult(I);
5569     return nullptr;
5570   }
5571   case Intrinsic::experimental_gc_relocate: {
5572     visitGCRelocate(I);
5573     return nullptr;
5574   }
5575   case Intrinsic::instrprof_increment:
5576     llvm_unreachable("instrprof failed to lower an increment");
5577   }
5578 }
5579
5580 std::pair<SDValue, SDValue>
5581 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5582                                     MachineBasicBlock *LandingPad) {
5583   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5584   MCSymbol *BeginLabel = nullptr;
5585
5586   if (LandingPad) {
5587     // Insert a label before the invoke call to mark the try range.  This can be
5588     // used to detect deletion of the invoke via the MachineModuleInfo.
5589     BeginLabel = MMI.getContext().CreateTempSymbol();
5590
5591     // For SjLj, keep track of which landing pads go with which invokes
5592     // so as to maintain the ordering of pads in the LSDA.
5593     unsigned CallSiteIndex = MMI.getCurrentCallSite();
5594     if (CallSiteIndex) {
5595       MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5596       LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5597
5598       // Now that the call site is handled, stop tracking it.
5599       MMI.setCurrentCallSite(0);
5600     }
5601
5602     // Both PendingLoads and PendingExports must be flushed here;
5603     // this call might not return.
5604     (void)getRoot();
5605     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5606
5607     CLI.setChain(getRoot());
5608   }
5609
5610   const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
5611   std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
5612
5613   assert((CLI.IsTailCall || Result.second.getNode()) &&
5614          "Non-null chain expected with non-tail call!");
5615   assert((Result.second.getNode() || !Result.first.getNode()) &&
5616          "Null value expected with tail call!");
5617
5618   if (!Result.second.getNode()) {
5619     // As a special case, a null chain means that a tail call has been emitted
5620     // and the DAG root is already updated.
5621     HasTailCall = true;
5622
5623     // Since there's no actual continuation from this block, nothing can be
5624     // relying on us setting vregs for them.
5625     PendingExports.clear();
5626   } else {
5627     DAG.setRoot(Result.second);
5628   }
5629
5630   if (LandingPad) {
5631     // Insert a label at the end of the invoke call to mark the try range.  This
5632     // can be used to detect deletion of the invoke via the MachineModuleInfo.
5633     MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5634     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5635
5636     // Inform MachineModuleInfo of range.
5637     MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5638   }
5639
5640   return Result;
5641 }
5642
5643 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5644                                       bool isTailCall,
5645                                       MachineBasicBlock *LandingPad) {
5646   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5647   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5648   Type *RetTy = FTy->getReturnType();
5649
5650   TargetLowering::ArgListTy Args;
5651   TargetLowering::ArgListEntry Entry;
5652   Args.reserve(CS.arg_size());
5653
5654   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5655        i != e; ++i) {
5656     const Value *V = *i;
5657
5658     // Skip empty types
5659     if (V->getType()->isEmptyTy())
5660       continue;
5661
5662     SDValue ArgNode = getValue(V);
5663     Entry.Node = ArgNode; Entry.Ty = V->getType();
5664
5665     // Skip the first return-type Attribute to get to params.
5666     Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5667     Args.push_back(Entry);
5668   }
5669
5670   // Check if target-independent constraints permit a tail call here.
5671   // Target-dependent constraints are checked within TLI->LowerCallTo.
5672   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5673     isTailCall = false;
5674
5675   TargetLowering::CallLoweringInfo CLI(DAG);
5676   CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
5677     .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5678     .setTailCall(isTailCall);
5679   std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad);
5680
5681   if (Result.first.getNode())
5682     setValue(CS.getInstruction(), Result.first);
5683 }
5684
5685 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5686 /// value is equal or not-equal to zero.
5687 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5688   for (const User *U : V->users()) {
5689     if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5690       if (IC->isEquality())
5691         if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5692           if (C->isNullValue())
5693             continue;
5694     // Unknown instruction.
5695     return false;
5696   }
5697   return true;
5698 }
5699
5700 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5701                              Type *LoadTy,
5702                              SelectionDAGBuilder &Builder) {
5703
5704   // Check to see if this load can be trivially constant folded, e.g. if the
5705   // input is from a string literal.
5706   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5707     // Cast pointer to the type we really want to load.
5708     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5709                                          PointerType::getUnqual(LoadTy));
5710
5711     if (const Constant *LoadCst =
5712           ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5713                                        Builder.DL))
5714       return Builder.getValue(LoadCst);
5715   }
5716
5717   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
5718   // still constant memory, the input chain can be the entry node.
5719   SDValue Root;
5720   bool ConstantMemory = false;
5721
5722   // Do not serialize (non-volatile) loads of constant memory with anything.
5723   if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5724     Root = Builder.DAG.getEntryNode();
5725     ConstantMemory = true;
5726   } else {
5727     // Do not serialize non-volatile loads against each other.
5728     Root = Builder.DAG.getRoot();
5729   }
5730
5731   SDValue Ptr = Builder.getValue(PtrVal);
5732   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5733                                         Ptr, MachinePointerInfo(PtrVal),
5734                                         false /*volatile*/,
5735                                         false /*nontemporal*/,
5736                                         false /*isinvariant*/, 1 /* align=1 */);
5737
5738   if (!ConstantMemory)
5739     Builder.PendingLoads.push_back(LoadVal.getValue(1));
5740   return LoadVal;
5741 }
5742
5743 /// processIntegerCallValue - Record the value for an instruction that
5744 /// produces an integer result, converting the type where necessary.
5745 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5746                                                   SDValue Value,
5747                                                   bool IsSigned) {
5748   EVT VT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
5749   if (IsSigned)
5750     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5751   else
5752     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5753   setValue(&I, Value);
5754 }
5755
5756 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5757 /// If so, return true and lower it, otherwise return false and it will be
5758 /// lowered like a normal call.
5759 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5760   // Verify that the prototype makes sense.  int memcmp(void*,void*,size_t)
5761   if (I.getNumArgOperands() != 3)
5762     return false;
5763
5764   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5765   if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5766       !I.getArgOperand(2)->getType()->isIntegerTy() ||
5767       !I.getType()->isIntegerTy())
5768     return false;
5769
5770   const Value *Size = I.getArgOperand(2);
5771   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5772   if (CSize && CSize->getZExtValue() == 0) {
5773     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
5774     setValue(&I, DAG.getConstant(0, CallVT));
5775     return true;
5776   }
5777
5778   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5779   std::pair<SDValue, SDValue> Res =
5780     TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5781                                 getValue(LHS), getValue(RHS), getValue(Size),
5782                                 MachinePointerInfo(LHS),
5783                                 MachinePointerInfo(RHS));
5784   if (Res.first.getNode()) {
5785     processIntegerCallValue(I, Res.first, true);
5786     PendingLoads.push_back(Res.second);
5787     return true;
5788   }
5789
5790   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
5791   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
5792   if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5793     bool ActuallyDoIt = true;
5794     MVT LoadVT;
5795     Type *LoadTy;
5796     switch (CSize->getZExtValue()) {
5797     default:
5798       LoadVT = MVT::Other;
5799       LoadTy = nullptr;
5800       ActuallyDoIt = false;
5801       break;
5802     case 2:
5803       LoadVT = MVT::i16;
5804       LoadTy = Type::getInt16Ty(CSize->getContext());
5805       break;
5806     case 4:
5807       LoadVT = MVT::i32;
5808       LoadTy = Type::getInt32Ty(CSize->getContext());
5809       break;
5810     case 8:
5811       LoadVT = MVT::i64;
5812       LoadTy = Type::getInt64Ty(CSize->getContext());
5813       break;
5814         /*
5815     case 16:
5816       LoadVT = MVT::v4i32;
5817       LoadTy = Type::getInt32Ty(CSize->getContext());
5818       LoadTy = VectorType::get(LoadTy, 4);
5819       break;
5820          */
5821     }
5822
5823     // This turns into unaligned loads.  We only do this if the target natively
5824     // supports the MVT we'll be loading or if it is small enough (<= 4) that
5825     // we'll only produce a small number of byte loads.
5826
5827     // Require that we can find a legal MVT, and only do this if the target
5828     // supports unaligned loads of that type.  Expanding into byte loads would
5829     // bloat the code.
5830     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5831     if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5832       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5833       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5834       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5835       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5836       // TODO: Check alignment of src and dest ptrs.
5837       if (!TLI.isTypeLegal(LoadVT) ||
5838           !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5839           !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
5840         ActuallyDoIt = false;
5841     }
5842
5843     if (ActuallyDoIt) {
5844       SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5845       SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5846
5847       SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5848                                  ISD::SETNE);
5849       processIntegerCallValue(I, Res, false);
5850       return true;
5851     }
5852   }
5853
5854
5855   return false;
5856 }
5857
5858 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5859 /// form.  If so, return true and lower it, otherwise return false and it
5860 /// will be lowered like a normal call.
5861 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5862   // Verify that the prototype makes sense.  void *memchr(void *, int, size_t)
5863   if (I.getNumArgOperands() != 3)
5864     return false;
5865
5866   const Value *Src = I.getArgOperand(0);
5867   const Value *Char = I.getArgOperand(1);
5868   const Value *Length = I.getArgOperand(2);
5869   if (!Src->getType()->isPointerTy() ||
5870       !Char->getType()->isIntegerTy() ||
5871       !Length->getType()->isIntegerTy() ||
5872       !I.getType()->isPointerTy())
5873     return false;
5874
5875   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5876   std::pair<SDValue, SDValue> Res =
5877     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5878                                 getValue(Src), getValue(Char), getValue(Length),
5879                                 MachinePointerInfo(Src));
5880   if (Res.first.getNode()) {
5881     setValue(&I, Res.first);
5882     PendingLoads.push_back(Res.second);
5883     return true;
5884   }
5885
5886   return false;
5887 }
5888
5889 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5890 /// optimized form.  If so, return true and lower it, otherwise return false
5891 /// and it will be lowered like a normal call.
5892 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5893   // Verify that the prototype makes sense.  char *strcpy(char *, char *)
5894   if (I.getNumArgOperands() != 2)
5895     return false;
5896
5897   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5898   if (!Arg0->getType()->isPointerTy() ||
5899       !Arg1->getType()->isPointerTy() ||
5900       !I.getType()->isPointerTy())
5901     return false;
5902
5903   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5904   std::pair<SDValue, SDValue> Res =
5905     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5906                                 getValue(Arg0), getValue(Arg1),
5907                                 MachinePointerInfo(Arg0),
5908                                 MachinePointerInfo(Arg1), isStpcpy);
5909   if (Res.first.getNode()) {
5910     setValue(&I, Res.first);
5911     DAG.setRoot(Res.second);
5912     return true;
5913   }
5914
5915   return false;
5916 }
5917
5918 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5919 /// If so, return true and lower it, otherwise return false and it will be
5920 /// lowered like a normal call.
5921 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5922   // Verify that the prototype makes sense.  int strcmp(void*,void*)
5923   if (I.getNumArgOperands() != 2)
5924     return false;
5925
5926   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5927   if (!Arg0->getType()->isPointerTy() ||
5928       !Arg1->getType()->isPointerTy() ||
5929       !I.getType()->isIntegerTy())
5930     return false;
5931
5932   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5933   std::pair<SDValue, SDValue> Res =
5934     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5935                                 getValue(Arg0), getValue(Arg1),
5936                                 MachinePointerInfo(Arg0),
5937                                 MachinePointerInfo(Arg1));
5938   if (Res.first.getNode()) {
5939     processIntegerCallValue(I, Res.first, true);
5940     PendingLoads.push_back(Res.second);
5941     return true;
5942   }
5943
5944   return false;
5945 }
5946
5947 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5948 /// form.  If so, return true and lower it, otherwise return false and it
5949 /// will be lowered like a normal call.
5950 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5951   // Verify that the prototype makes sense.  size_t strlen(char *)
5952   if (I.getNumArgOperands() != 1)
5953     return false;
5954
5955   const Value *Arg0 = I.getArgOperand(0);
5956   if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5957     return false;
5958
5959   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5960   std::pair<SDValue, SDValue> Res =
5961     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5962                                 getValue(Arg0), MachinePointerInfo(Arg0));
5963   if (Res.first.getNode()) {
5964     processIntegerCallValue(I, Res.first, false);
5965     PendingLoads.push_back(Res.second);
5966     return true;
5967   }
5968
5969   return false;
5970 }
5971
5972 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5973 /// form.  If so, return true and lower it, otherwise return false and it
5974 /// will be lowered like a normal call.
5975 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5976   // Verify that the prototype makes sense.  size_t strnlen(char *, size_t)
5977   if (I.getNumArgOperands() != 2)
5978     return false;
5979
5980   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5981   if (!Arg0->getType()->isPointerTy() ||
5982       !Arg1->getType()->isIntegerTy() ||
5983       !I.getType()->isIntegerTy())
5984     return false;
5985
5986   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5987   std::pair<SDValue, SDValue> Res =
5988     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5989                                  getValue(Arg0), getValue(Arg1),
5990                                  MachinePointerInfo(Arg0));
5991   if (Res.first.getNode()) {
5992     processIntegerCallValue(I, Res.first, false);
5993     PendingLoads.push_back(Res.second);
5994     return true;
5995   }
5996
5997   return false;
5998 }
5999
6000 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
6001 /// operation (as expected), translate it to an SDNode with the specified opcode
6002 /// and return true.
6003 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6004                                               unsigned Opcode) {
6005   // Sanity check that it really is a unary floating-point call.
6006   if (I.getNumArgOperands() != 1 ||
6007       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
6008       I.getType() != I.getArgOperand(0)->getType() ||
6009       !I.onlyReadsMemory())
6010     return false;
6011
6012   SDValue Tmp = getValue(I.getArgOperand(0));
6013   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6014   return true;
6015 }
6016
6017 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
6018 /// operation (as expected), translate it to an SDNode with the specified opcode
6019 /// and return true.
6020 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6021                                                unsigned Opcode) {
6022   // Sanity check that it really is a binary floating-point call.
6023   if (I.getNumArgOperands() != 2 ||
6024       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
6025       I.getType() != I.getArgOperand(0)->getType() ||
6026       I.getType() != I.getArgOperand(1)->getType() ||
6027       !I.onlyReadsMemory())
6028     return false;
6029
6030   SDValue Tmp0 = getValue(I.getArgOperand(0));
6031   SDValue Tmp1 = getValue(I.getArgOperand(1));
6032   EVT VT = Tmp0.getValueType();
6033   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6034   return true;
6035 }
6036
6037 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6038   // Handle inline assembly differently.
6039   if (isa<InlineAsm>(I.getCalledValue())) {
6040     visitInlineAsm(&I);
6041     return;
6042   }
6043
6044   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6045   ComputeUsesVAFloatArgument(I, &MMI);
6046
6047   const char *RenameFn = nullptr;
6048   if (Function *F = I.getCalledFunction()) {
6049     if (F->isDeclaration()) {
6050       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
6051         if (unsigned IID = II->getIntrinsicID(F)) {
6052           RenameFn = visitIntrinsicCall(I, IID);
6053           if (!RenameFn)
6054             return;
6055         }
6056       }
6057       if (unsigned IID = F->getIntrinsicID()) {
6058         RenameFn = visitIntrinsicCall(I, IID);
6059         if (!RenameFn)
6060           return;
6061       }
6062     }
6063
6064     // Check for well-known libc/libm calls.  If the function is internal, it
6065     // can't be a library call.
6066     LibFunc::Func Func;
6067     if (!F->hasLocalLinkage() && F->hasName() &&
6068         LibInfo->getLibFunc(F->getName(), Func) &&
6069         LibInfo->hasOptimizedCodeGen(Func)) {
6070       switch (Func) {
6071       default: break;
6072       case LibFunc::copysign:
6073       case LibFunc::copysignf:
6074       case LibFunc::copysignl:
6075         if (I.getNumArgOperands() == 2 &&   // Basic sanity checks.
6076             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
6077             I.getType() == I.getArgOperand(0)->getType() &&
6078             I.getType() == I.getArgOperand(1)->getType() &&
6079             I.onlyReadsMemory()) {
6080           SDValue LHS = getValue(I.getArgOperand(0));
6081           SDValue RHS = getValue(I.getArgOperand(1));
6082           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6083                                    LHS.getValueType(), LHS, RHS));
6084           return;
6085         }
6086         break;
6087       case LibFunc::fabs:
6088       case LibFunc::fabsf:
6089       case LibFunc::fabsl:
6090         if (visitUnaryFloatCall(I, ISD::FABS))
6091           return;
6092         break;
6093       case LibFunc::fmin:
6094       case LibFunc::fminf:
6095       case LibFunc::fminl:
6096         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6097           return;
6098         break;
6099       case LibFunc::fmax:
6100       case LibFunc::fmaxf:
6101       case LibFunc::fmaxl:
6102         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6103           return;
6104         break;
6105       case LibFunc::sin:
6106       case LibFunc::sinf:
6107       case LibFunc::sinl:
6108         if (visitUnaryFloatCall(I, ISD::FSIN))
6109           return;
6110         break;
6111       case LibFunc::cos:
6112       case LibFunc::cosf:
6113       case LibFunc::cosl:
6114         if (visitUnaryFloatCall(I, ISD::FCOS))
6115           return;
6116         break;
6117       case LibFunc::sqrt:
6118       case LibFunc::sqrtf:
6119       case LibFunc::sqrtl:
6120       case LibFunc::sqrt_finite:
6121       case LibFunc::sqrtf_finite:
6122       case LibFunc::sqrtl_finite:
6123         if (visitUnaryFloatCall(I, ISD::FSQRT))
6124           return;
6125         break;
6126       case LibFunc::floor:
6127       case LibFunc::floorf:
6128       case LibFunc::floorl:
6129         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6130           return;
6131         break;
6132       case LibFunc::nearbyint:
6133       case LibFunc::nearbyintf:
6134       case LibFunc::nearbyintl:
6135         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6136           return;
6137         break;
6138       case LibFunc::ceil:
6139       case LibFunc::ceilf:
6140       case LibFunc::ceill:
6141         if (visitUnaryFloatCall(I, ISD::FCEIL))
6142           return;
6143         break;
6144       case LibFunc::rint:
6145       case LibFunc::rintf:
6146       case LibFunc::rintl:
6147         if (visitUnaryFloatCall(I, ISD::FRINT))
6148           return;
6149         break;
6150       case LibFunc::round:
6151       case LibFunc::roundf:
6152       case LibFunc::roundl:
6153         if (visitUnaryFloatCall(I, ISD::FROUND))
6154           return;
6155         break;
6156       case LibFunc::trunc:
6157       case LibFunc::truncf:
6158       case LibFunc::truncl:
6159         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6160           return;
6161         break;
6162       case LibFunc::log2:
6163       case LibFunc::log2f:
6164       case LibFunc::log2l:
6165         if (visitUnaryFloatCall(I, ISD::FLOG2))
6166           return;
6167         break;
6168       case LibFunc::exp2:
6169       case LibFunc::exp2f:
6170       case LibFunc::exp2l:
6171         if (visitUnaryFloatCall(I, ISD::FEXP2))
6172           return;
6173         break;
6174       case LibFunc::memcmp:
6175         if (visitMemCmpCall(I))
6176           return;
6177         break;
6178       case LibFunc::memchr:
6179         if (visitMemChrCall(I))
6180           return;
6181         break;
6182       case LibFunc::strcpy:
6183         if (visitStrCpyCall(I, false))
6184           return;
6185         break;
6186       case LibFunc::stpcpy:
6187         if (visitStrCpyCall(I, true))
6188           return;
6189         break;
6190       case LibFunc::strcmp:
6191         if (visitStrCmpCall(I))
6192           return;
6193         break;
6194       case LibFunc::strlen:
6195         if (visitStrLenCall(I))
6196           return;
6197         break;
6198       case LibFunc::strnlen:
6199         if (visitStrNLenCall(I))
6200           return;
6201         break;
6202       }
6203     }
6204   }
6205
6206   SDValue Callee;
6207   if (!RenameFn)
6208     Callee = getValue(I.getCalledValue());
6209   else
6210     Callee = DAG.getExternalSymbol(RenameFn,
6211                                    DAG.getTargetLoweringInfo().getPointerTy());
6212
6213   // Check if we can potentially perform a tail call. More detailed checking is
6214   // be done within LowerCallTo, after more information about the call is known.
6215   LowerCallTo(&I, Callee, I.isTailCall());
6216 }
6217
6218 namespace {
6219
6220 /// AsmOperandInfo - This contains information for each constraint that we are
6221 /// lowering.
6222 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6223 public:
6224   /// CallOperand - If this is the result output operand or a clobber
6225   /// this is null, otherwise it is the incoming operand to the CallInst.
6226   /// This gets modified as the asm is processed.
6227   SDValue CallOperand;
6228
6229   /// AssignedRegs - If this is a register or register class operand, this
6230   /// contains the set of register corresponding to the operand.
6231   RegsForValue AssignedRegs;
6232
6233   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6234     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
6235   }
6236
6237   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6238   /// corresponds to.  If there is no Value* for this operand, it returns
6239   /// MVT::Other.
6240   EVT getCallOperandValEVT(LLVMContext &Context,
6241                            const TargetLowering &TLI,
6242                            const DataLayout *DL) const {
6243     if (!CallOperandVal) return MVT::Other;
6244
6245     if (isa<BasicBlock>(CallOperandVal))
6246       return TLI.getPointerTy();
6247
6248     llvm::Type *OpTy = CallOperandVal->getType();
6249
6250     // FIXME: code duplicated from TargetLowering::ParseConstraints().
6251     // If this is an indirect operand, the operand is a pointer to the
6252     // accessed type.
6253     if (isIndirect) {
6254       llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6255       if (!PtrTy)
6256         report_fatal_error("Indirect operand for inline asm not a pointer!");
6257       OpTy = PtrTy->getElementType();
6258     }
6259
6260     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6261     if (StructType *STy = dyn_cast<StructType>(OpTy))
6262       if (STy->getNumElements() == 1)
6263         OpTy = STy->getElementType(0);
6264
6265     // If OpTy is not a single value, it may be a struct/union that we
6266     // can tile with integers.
6267     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6268       unsigned BitSize = DL->getTypeSizeInBits(OpTy);
6269       switch (BitSize) {
6270       default: break;
6271       case 1:
6272       case 8:
6273       case 16:
6274       case 32:
6275       case 64:
6276       case 128:
6277         OpTy = IntegerType::get(Context, BitSize);
6278         break;
6279       }
6280     }
6281
6282     return TLI.getValueType(OpTy, true);
6283   }
6284 };
6285
6286 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6287
6288 } // end anonymous namespace
6289
6290 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6291 /// specified operand.  We prefer to assign virtual registers, to allow the
6292 /// register allocator to handle the assignment process.  However, if the asm
6293 /// uses features that we can't model on machineinstrs, we have SDISel do the
6294 /// allocation.  This produces generally horrible, but correct, code.
6295 ///
6296 ///   OpInfo describes the operand.
6297 ///
6298 static void GetRegistersForValue(SelectionDAG &DAG,
6299                                  const TargetLowering &TLI,
6300                                  SDLoc DL,
6301                                  SDISelAsmOperandInfo &OpInfo) {
6302   LLVMContext &Context = *DAG.getContext();
6303
6304   MachineFunction &MF = DAG.getMachineFunction();
6305   SmallVector<unsigned, 4> Regs;
6306
6307   // If this is a constraint for a single physreg, or a constraint for a
6308   // register class, find it.
6309   std::pair<unsigned, const TargetRegisterClass*> PhysReg =
6310     TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6311                                      OpInfo.ConstraintVT);
6312
6313   unsigned NumRegs = 1;
6314   if (OpInfo.ConstraintVT != MVT::Other) {
6315     // If this is a FP input in an integer register (or visa versa) insert a bit
6316     // cast of the input value.  More generally, handle any case where the input
6317     // value disagrees with the register class we plan to stick this in.
6318     if (OpInfo.Type == InlineAsm::isInput &&
6319         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6320       // Try to convert to the first EVT that the reg class contains.  If the
6321       // types are identical size, use a bitcast to convert (e.g. two differing
6322       // vector types).
6323       MVT RegVT = *PhysReg.second->vt_begin();
6324       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6325         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6326                                          RegVT, OpInfo.CallOperand);
6327         OpInfo.ConstraintVT = RegVT;
6328       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6329         // If the input is a FP value and we want it in FP registers, do a
6330         // bitcast to the corresponding integer type.  This turns an f64 value
6331         // into i64, which can be passed with two i32 values on a 32-bit
6332         // machine.
6333         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6334         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6335                                          RegVT, OpInfo.CallOperand);
6336         OpInfo.ConstraintVT = RegVT;
6337       }
6338     }
6339
6340     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6341   }
6342
6343   MVT RegVT;
6344   EVT ValueVT = OpInfo.ConstraintVT;
6345
6346   // If this is a constraint for a specific physical register, like {r17},
6347   // assign it now.
6348   if (unsigned AssignedReg = PhysReg.first) {
6349     const TargetRegisterClass *RC = PhysReg.second;
6350     if (OpInfo.ConstraintVT == MVT::Other)
6351       ValueVT = *RC->vt_begin();
6352
6353     // Get the actual register value type.  This is important, because the user
6354     // may have asked for (e.g.) the AX register in i32 type.  We need to
6355     // remember that AX is actually i16 to get the right extension.
6356     RegVT = *RC->vt_begin();
6357
6358     // This is a explicit reference to a physical register.
6359     Regs.push_back(AssignedReg);
6360
6361     // If this is an expanded reference, add the rest of the regs to Regs.
6362     if (NumRegs != 1) {
6363       TargetRegisterClass::iterator I = RC->begin();
6364       for (; *I != AssignedReg; ++I)
6365         assert(I != RC->end() && "Didn't find reg!");
6366
6367       // Already added the first reg.
6368       --NumRegs; ++I;
6369       for (; NumRegs; --NumRegs, ++I) {
6370         assert(I != RC->end() && "Ran out of registers to allocate!");
6371         Regs.push_back(*I);
6372       }
6373     }
6374
6375     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6376     return;
6377   }
6378
6379   // Otherwise, if this was a reference to an LLVM register class, create vregs
6380   // for this reference.
6381   if (const TargetRegisterClass *RC = PhysReg.second) {
6382     RegVT = *RC->vt_begin();
6383     if (OpInfo.ConstraintVT == MVT::Other)
6384       ValueVT = RegVT;
6385
6386     // Create the appropriate number of virtual registers.
6387     MachineRegisterInfo &RegInfo = MF.getRegInfo();
6388     for (; NumRegs; --NumRegs)
6389       Regs.push_back(RegInfo.createVirtualRegister(RC));
6390
6391     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6392     return;
6393   }
6394
6395   // Otherwise, we couldn't allocate enough registers for this.
6396 }
6397
6398 /// visitInlineAsm - Handle a call to an InlineAsm object.
6399 ///
6400 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6401   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6402
6403   /// ConstraintOperands - Information about all of the constraints.
6404   SDISelAsmOperandInfoVector ConstraintOperands;
6405
6406   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6407   TargetLowering::AsmOperandInfoVector
6408     TargetConstraints = TLI.ParseConstraints(CS);
6409
6410   bool hasMemory = false;
6411
6412   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
6413   unsigned ResNo = 0;   // ResNo - The result number of the next output.
6414   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6415     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6416     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6417
6418     MVT OpVT = MVT::Other;
6419
6420     // Compute the value type for each operand.
6421     switch (OpInfo.Type) {
6422     case InlineAsm::isOutput:
6423       // Indirect outputs just consume an argument.
6424       if (OpInfo.isIndirect) {
6425         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6426         break;
6427       }
6428
6429       // The return value of the call is this value.  As such, there is no
6430       // corresponding argument.
6431       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6432       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6433         OpVT = TLI.getSimpleValueType(STy->getElementType(ResNo));
6434       } else {
6435         assert(ResNo == 0 && "Asm only has one result!");
6436         OpVT = TLI.getSimpleValueType(CS.getType());
6437       }
6438       ++ResNo;
6439       break;
6440     case InlineAsm::isInput:
6441       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6442       break;
6443     case InlineAsm::isClobber:
6444       // Nothing to do.
6445       break;
6446     }
6447
6448     // If this is an input or an indirect output, process the call argument.
6449     // BasicBlocks are labels, currently appearing only in asm's.
6450     if (OpInfo.CallOperandVal) {
6451       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6452         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6453       } else {
6454         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6455       }
6456
6457       OpVT =
6458           OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, DL).getSimpleVT();
6459     }
6460
6461     OpInfo.ConstraintVT = OpVT;
6462
6463     // Indirect operand accesses access memory.
6464     if (OpInfo.isIndirect)
6465       hasMemory = true;
6466     else {
6467       for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6468         TargetLowering::ConstraintType
6469           CType = TLI.getConstraintType(OpInfo.Codes[j]);
6470         if (CType == TargetLowering::C_Memory) {
6471           hasMemory = true;
6472           break;
6473         }
6474       }
6475     }
6476   }
6477
6478   SDValue Chain, Flag;
6479
6480   // We won't need to flush pending loads if this asm doesn't touch
6481   // memory and is nonvolatile.
6482   if (hasMemory || IA->hasSideEffects())
6483     Chain = getRoot();
6484   else
6485     Chain = DAG.getRoot();
6486
6487   // Second pass over the constraints: compute which constraint option to use
6488   // and assign registers to constraints that want a specific physreg.
6489   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6490     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6491
6492     // If this is an output operand with a matching input operand, look up the
6493     // matching input. If their types mismatch, e.g. one is an integer, the
6494     // other is floating point, or their sizes are different, flag it as an
6495     // error.
6496     if (OpInfo.hasMatchingInput()) {
6497       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6498
6499       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6500         std::pair<unsigned, const TargetRegisterClass*> MatchRC =
6501           TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6502                                             OpInfo.ConstraintVT);
6503         std::pair<unsigned, const TargetRegisterClass*> InputRC =
6504           TLI.getRegForInlineAsmConstraint(Input.ConstraintCode,
6505                                             Input.ConstraintVT);
6506         if ((OpInfo.ConstraintVT.isInteger() !=
6507              Input.ConstraintVT.isInteger()) ||
6508             (MatchRC.second != InputRC.second)) {
6509           report_fatal_error("Unsupported asm: input constraint"
6510                              " with a matching output constraint of"
6511                              " incompatible type!");
6512         }
6513         Input.ConstraintVT = OpInfo.ConstraintVT;
6514       }
6515     }
6516
6517     // Compute the constraint code and ConstraintType to use.
6518     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6519
6520     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6521         OpInfo.Type == InlineAsm::isClobber)
6522       continue;
6523
6524     // If this is a memory input, and if the operand is not indirect, do what we
6525     // need to to provide an address for the memory input.
6526     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6527         !OpInfo.isIndirect) {
6528       assert((OpInfo.isMultipleAlternative ||
6529               (OpInfo.Type == InlineAsm::isInput)) &&
6530              "Can only indirectify direct input operands!");
6531
6532       // Memory operands really want the address of the value.  If we don't have
6533       // an indirect input, put it in the constpool if we can, otherwise spill
6534       // it to a stack slot.
6535       // TODO: This isn't quite right. We need to handle these according to
6536       // the addressing mode that the constraint wants. Also, this may take
6537       // an additional register for the computation and we don't want that
6538       // either.
6539
6540       // If the operand is a float, integer, or vector constant, spill to a
6541       // constant pool entry to get its address.
6542       const Value *OpVal = OpInfo.CallOperandVal;
6543       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6544           isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6545         OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6546                                                  TLI.getPointerTy());
6547       } else {
6548         // Otherwise, create a stack slot and emit a store to it before the
6549         // asm.
6550         Type *Ty = OpVal->getType();
6551         uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
6552         unsigned Align  = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
6553         MachineFunction &MF = DAG.getMachineFunction();
6554         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6555         SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
6556         Chain = DAG.getStore(Chain, getCurSDLoc(),
6557                              OpInfo.CallOperand, StackSlot,
6558                              MachinePointerInfo::getFixedStack(SSFI),
6559                              false, false, 0);
6560         OpInfo.CallOperand = StackSlot;
6561       }
6562
6563       // There is no longer a Value* corresponding to this operand.
6564       OpInfo.CallOperandVal = nullptr;
6565
6566       // It is now an indirect operand.
6567       OpInfo.isIndirect = true;
6568     }
6569
6570     // If this constraint is for a specific register, allocate it before
6571     // anything else.
6572     if (OpInfo.ConstraintType == TargetLowering::C_Register)
6573       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6574   }
6575
6576   // Second pass - Loop over all of the operands, assigning virtual or physregs
6577   // to register class operands.
6578   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6579     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6580
6581     // C_Register operands have already been allocated, Other/Memory don't need
6582     // to be.
6583     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6584       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6585   }
6586
6587   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6588   std::vector<SDValue> AsmNodeOperands;
6589   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
6590   AsmNodeOperands.push_back(
6591           DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6592                                       TLI.getPointerTy()));
6593
6594   // If we have a !srcloc metadata node associated with it, we want to attach
6595   // this to the ultimately generated inline asm machineinstr.  To do this, we
6596   // pass in the third operand as this (potentially null) inline asm MDNode.
6597   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6598   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6599
6600   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6601   // bits as operand 3.
6602   unsigned ExtraInfo = 0;
6603   if (IA->hasSideEffects())
6604     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6605   if (IA->isAlignStack())
6606     ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6607   // Set the asm dialect.
6608   ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6609
6610   // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6611   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6612     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6613
6614     // Compute the constraint code and ConstraintType to use.
6615     TLI.ComputeConstraintToUse(OpInfo, SDValue());
6616
6617     // Ideally, we would only check against memory constraints.  However, the
6618     // meaning of an other constraint can be target-specific and we can't easily
6619     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
6620     // for other constriants as well.
6621     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6622         OpInfo.ConstraintType == TargetLowering::C_Other) {
6623       if (OpInfo.Type == InlineAsm::isInput)
6624         ExtraInfo |= InlineAsm::Extra_MayLoad;
6625       else if (OpInfo.Type == InlineAsm::isOutput)
6626         ExtraInfo |= InlineAsm::Extra_MayStore;
6627       else if (OpInfo.Type == InlineAsm::isClobber)
6628         ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6629     }
6630   }
6631
6632   AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6633                                                   TLI.getPointerTy()));
6634
6635   // Loop over all of the inputs, copying the operand values into the
6636   // appropriate registers and processing the output regs.
6637   RegsForValue RetValRegs;
6638
6639   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6640   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6641
6642   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6643     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6644
6645     switch (OpInfo.Type) {
6646     case InlineAsm::isOutput: {
6647       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6648           OpInfo.ConstraintType != TargetLowering::C_Register) {
6649         // Memory output, or 'other' output (e.g. 'X' constraint).
6650         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6651
6652         // Add information to the INLINEASM node to know about this output.
6653         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6654         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
6655                                                         TLI.getPointerTy()));
6656         AsmNodeOperands.push_back(OpInfo.CallOperand);
6657         break;
6658       }
6659
6660       // Otherwise, this is a register or register class output.
6661
6662       // Copy the output from the appropriate register.  Find a register that
6663       // we can use.
6664       if (OpInfo.AssignedRegs.Regs.empty()) {
6665         LLVMContext &Ctx = *DAG.getContext();
6666         Ctx.emitError(CS.getInstruction(),
6667                       "couldn't allocate output register for constraint '" +
6668                           Twine(OpInfo.ConstraintCode) + "'");
6669         return;
6670       }
6671
6672       // If this is an indirect operand, store through the pointer after the
6673       // asm.
6674       if (OpInfo.isIndirect) {
6675         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6676                                                       OpInfo.CallOperandVal));
6677       } else {
6678         // This is the result value of the call.
6679         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6680         // Concatenate this output onto the outputs list.
6681         RetValRegs.append(OpInfo.AssignedRegs);
6682       }
6683
6684       // Add information to the INLINEASM node to know that this register is
6685       // set.
6686       OpInfo.AssignedRegs
6687           .AddInlineAsmOperands(OpInfo.isEarlyClobber
6688                                     ? InlineAsm::Kind_RegDefEarlyClobber
6689                                     : InlineAsm::Kind_RegDef,
6690                                 false, 0, DAG, AsmNodeOperands);
6691       break;
6692     }
6693     case InlineAsm::isInput: {
6694       SDValue InOperandVal = OpInfo.CallOperand;
6695
6696       if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
6697         // If this is required to match an output register we have already set,
6698         // just use its register.
6699         unsigned OperandNo = OpInfo.getMatchedOperand();
6700
6701         // Scan until we find the definition we already emitted of this operand.
6702         // When we find it, create a RegsForValue operand.
6703         unsigned CurOp = InlineAsm::Op_FirstOperand;
6704         for (; OperandNo; --OperandNo) {
6705           // Advance to the next operand.
6706           unsigned OpFlag =
6707             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6708           assert((InlineAsm::isRegDefKind(OpFlag) ||
6709                   InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6710                   InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6711           CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6712         }
6713
6714         unsigned OpFlag =
6715           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6716         if (InlineAsm::isRegDefKind(OpFlag) ||
6717             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6718           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6719           if (OpInfo.isIndirect) {
6720             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6721             LLVMContext &Ctx = *DAG.getContext();
6722             Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6723                                                " don't know how to handle tied "
6724                                                "indirect register inputs");
6725             return;
6726           }
6727
6728           RegsForValue MatchedRegs;
6729           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6730           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6731           MatchedRegs.RegVTs.push_back(RegVT);
6732           MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6733           for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6734                i != e; ++i) {
6735             if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6736               MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6737             else {
6738               LLVMContext &Ctx = *DAG.getContext();
6739               Ctx.emitError(CS.getInstruction(),
6740                             "inline asm error: This value"
6741                             " type register class is not natively supported!");
6742               return;
6743             }
6744           }
6745           // Use the produced MatchedRegs object to
6746           MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6747                                     Chain, &Flag, CS.getInstruction());
6748           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6749                                            true, OpInfo.getMatchedOperand(),
6750                                            DAG, AsmNodeOperands);
6751           break;
6752         }
6753
6754         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6755         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6756                "Unexpected number of operands");
6757         // Add information to the INLINEASM node to know about this input.
6758         // See InlineAsm.h isUseOperandTiedToDef.
6759         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6760                                                     OpInfo.getMatchedOperand());
6761         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6762                                                         TLI.getPointerTy()));
6763         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6764         break;
6765       }
6766
6767       // Treat indirect 'X' constraint as memory.
6768       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6769           OpInfo.isIndirect)
6770         OpInfo.ConstraintType = TargetLowering::C_Memory;
6771
6772       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6773         std::vector<SDValue> Ops;
6774         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6775                                           Ops, DAG);
6776         if (Ops.empty()) {
6777           LLVMContext &Ctx = *DAG.getContext();
6778           Ctx.emitError(CS.getInstruction(),
6779                         "invalid operand for inline asm constraint '" +
6780                             Twine(OpInfo.ConstraintCode) + "'");
6781           return;
6782         }
6783
6784         // Add information to the INLINEASM node to know about this input.
6785         unsigned ResOpType =
6786           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6787         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6788                                                         TLI.getPointerTy()));
6789         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6790         break;
6791       }
6792
6793       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6794         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6795         assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6796                "Memory operands expect pointer values");
6797
6798         // Add information to the INLINEASM node to know about this input.
6799         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6800         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6801                                                         TLI.getPointerTy()));
6802         AsmNodeOperands.push_back(InOperandVal);
6803         break;
6804       }
6805
6806       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6807               OpInfo.ConstraintType == TargetLowering::C_Register) &&
6808              "Unknown constraint type!");
6809
6810       // TODO: Support this.
6811       if (OpInfo.isIndirect) {
6812         LLVMContext &Ctx = *DAG.getContext();
6813         Ctx.emitError(CS.getInstruction(),
6814                       "Don't know how to handle indirect register inputs yet "
6815                       "for constraint '" +
6816                           Twine(OpInfo.ConstraintCode) + "'");
6817         return;
6818       }
6819
6820       // Copy the input into the appropriate registers.
6821       if (OpInfo.AssignedRegs.Regs.empty()) {
6822         LLVMContext &Ctx = *DAG.getContext();
6823         Ctx.emitError(CS.getInstruction(),
6824                       "couldn't allocate input reg for constraint '" +
6825                           Twine(OpInfo.ConstraintCode) + "'");
6826         return;
6827       }
6828
6829       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6830                                         Chain, &Flag, CS.getInstruction());
6831
6832       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6833                                                DAG, AsmNodeOperands);
6834       break;
6835     }
6836     case InlineAsm::isClobber: {
6837       // Add the clobbered value to the operand list, so that the register
6838       // allocator is aware that the physreg got clobbered.
6839       if (!OpInfo.AssignedRegs.Regs.empty())
6840         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6841                                                  false, 0, DAG,
6842                                                  AsmNodeOperands);
6843       break;
6844     }
6845     }
6846   }
6847
6848   // Finish up input operands.  Set the input chain and add the flag last.
6849   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6850   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6851
6852   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6853                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
6854   Flag = Chain.getValue(1);
6855
6856   // If this asm returns a register value, copy the result from that register
6857   // and set it as the value of the call.
6858   if (!RetValRegs.Regs.empty()) {
6859     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6860                                              Chain, &Flag, CS.getInstruction());
6861
6862     // FIXME: Why don't we do this for inline asms with MRVs?
6863     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6864       EVT ResultType = TLI.getValueType(CS.getType());
6865
6866       // If any of the results of the inline asm is a vector, it may have the
6867       // wrong width/num elts.  This can happen for register classes that can
6868       // contain multiple different value types.  The preg or vreg allocated may
6869       // not have the same VT as was expected.  Convert it to the right type
6870       // with bit_convert.
6871       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6872         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6873                           ResultType, Val);
6874
6875       } else if (ResultType != Val.getValueType() &&
6876                  ResultType.isInteger() && Val.getValueType().isInteger()) {
6877         // If a result value was tied to an input value, the computed result may
6878         // have a wider width than the expected result.  Extract the relevant
6879         // portion.
6880         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6881       }
6882
6883       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6884     }
6885
6886     setValue(CS.getInstruction(), Val);
6887     // Don't need to use this as a chain in this case.
6888     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6889       return;
6890   }
6891
6892   std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6893
6894   // Process indirect outputs, first output all of the flagged copies out of
6895   // physregs.
6896   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6897     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6898     const Value *Ptr = IndirectStoresToEmit[i].second;
6899     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6900                                              Chain, &Flag, IA);
6901     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6902   }
6903
6904   // Emit the non-flagged stores from the physregs.
6905   SmallVector<SDValue, 8> OutChains;
6906   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6907     SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6908                                StoresToEmit[i].first,
6909                                getValue(StoresToEmit[i].second),
6910                                MachinePointerInfo(StoresToEmit[i].second),
6911                                false, false, 0);
6912     OutChains.push_back(Val);
6913   }
6914
6915   if (!OutChains.empty())
6916     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
6917
6918   DAG.setRoot(Chain);
6919 }
6920
6921 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6922   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6923                           MVT::Other, getRoot(),
6924                           getValue(I.getArgOperand(0)),
6925                           DAG.getSrcValue(I.getArgOperand(0))));
6926 }
6927
6928 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6930   const DataLayout &DL = *TLI.getDataLayout();
6931   SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurSDLoc(),
6932                            getRoot(), getValue(I.getOperand(0)),
6933                            DAG.getSrcValue(I.getOperand(0)),
6934                            DL.getABITypeAlignment(I.getType()));
6935   setValue(&I, V);
6936   DAG.setRoot(V.getValue(1));
6937 }
6938
6939 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6940   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6941                           MVT::Other, getRoot(),
6942                           getValue(I.getArgOperand(0)),
6943                           DAG.getSrcValue(I.getArgOperand(0))));
6944 }
6945
6946 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6947   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6948                           MVT::Other, getRoot(),
6949                           getValue(I.getArgOperand(0)),
6950                           getValue(I.getArgOperand(1)),
6951                           DAG.getSrcValue(I.getArgOperand(0)),
6952                           DAG.getSrcValue(I.getArgOperand(1))));
6953 }
6954
6955 /// \brief Lower an argument list according to the target calling convention.
6956 ///
6957 /// \return A tuple of <return-value, token-chain>
6958 ///
6959 /// This is a helper for lowering intrinsics that follow a target calling
6960 /// convention or require stack pointer adjustment. Only a subset of the
6961 /// intrinsic's operands need to participate in the calling convention.
6962 std::pair<SDValue, SDValue>
6963 SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx,
6964                                        unsigned NumArgs, SDValue Callee,
6965                                        bool UseVoidTy,
6966                                        MachineBasicBlock *LandingPad) {
6967   TargetLowering::ArgListTy Args;
6968   Args.reserve(NumArgs);
6969
6970   // Populate the argument list.
6971   // Attributes for args start at offset 1, after the return attribute.
6972   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6973        ArgI != ArgE; ++ArgI) {
6974     const Value *V = CS->getOperand(ArgI);
6975
6976     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6977
6978     TargetLowering::ArgListEntry Entry;
6979     Entry.Node = getValue(V);
6980     Entry.Ty = V->getType();
6981     Entry.setAttributes(&CS, AttrI);
6982     Args.push_back(Entry);
6983   }
6984
6985   Type *retTy = UseVoidTy ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
6986   TargetLowering::CallLoweringInfo CLI(DAG);
6987   CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
6988     .setCallee(CS.getCallingConv(), retTy, Callee, std::move(Args), NumArgs)
6989     .setDiscardResult(CS->use_empty());
6990
6991   return lowerInvokable(CLI, LandingPad);
6992 }
6993
6994 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6995 /// or patchpoint target node's operand list.
6996 ///
6997 /// Constants are converted to TargetConstants purely as an optimization to
6998 /// avoid constant materialization and register allocation.
6999 ///
7000 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
7001 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
7002 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
7003 /// address materialization and register allocation, but may also be required
7004 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
7005 /// alloca in the entry block, then the runtime may assume that the alloca's
7006 /// StackMap location can be read immediately after compilation and that the
7007 /// location is valid at any point during execution (this is similar to the
7008 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
7009 /// only available in a register, then the runtime would need to trap when
7010 /// execution reaches the StackMap in order to read the alloca's location.
7011 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
7012                                 SmallVectorImpl<SDValue> &Ops,
7013                                 SelectionDAGBuilder &Builder) {
7014   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
7015     SDValue OpVal = Builder.getValue(CS.getArgument(i));
7016     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
7017       Ops.push_back(
7018         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
7019       Ops.push_back(
7020         Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
7021     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7022       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7023       Ops.push_back(
7024         Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
7025     } else
7026       Ops.push_back(OpVal);
7027   }
7028 }
7029
7030 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
7031 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7032   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7033   //                                  [live variables...])
7034
7035   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7036
7037   SDValue Chain, InFlag, Callee, NullPtr;
7038   SmallVector<SDValue, 32> Ops;
7039
7040   SDLoc DL = getCurSDLoc();
7041   Callee = getValue(CI.getCalledValue());
7042   NullPtr = DAG.getIntPtrConstant(0, true);
7043
7044   // The stackmap intrinsic only records the live variables (the arguemnts
7045   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7046   // intrinsic, this won't be lowered to a function call. This means we don't
7047   // have to worry about calling conventions and target specific lowering code.
7048   // Instead we perform the call lowering right here.
7049   //
7050   // chain, flag = CALLSEQ_START(chain, 0)
7051   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7052   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7053   //
7054   Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
7055   InFlag = Chain.getValue(1);
7056
7057   // Add the <id> and <numBytes> constants.
7058   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7059   Ops.push_back(DAG.getTargetConstant(
7060                   cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
7061   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7062   Ops.push_back(DAG.getTargetConstant(
7063                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
7064
7065   // Push live variables for the stack map.
7066   addStackMapLiveVars(&CI, 2, Ops, *this);
7067
7068   // We are not pushing any register mask info here on the operands list,
7069   // because the stackmap doesn't clobber anything.
7070
7071   // Push the chain and the glue flag.
7072   Ops.push_back(Chain);
7073   Ops.push_back(InFlag);
7074
7075   // Create the STACKMAP node.
7076   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7077   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7078   Chain = SDValue(SM, 0);
7079   InFlag = Chain.getValue(1);
7080
7081   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7082
7083   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7084
7085   // Set the root to the target-lowered call chain.
7086   DAG.setRoot(Chain);
7087
7088   // Inform the Frame Information that we have a stackmap in this function.
7089   FuncInfo.MF->getFrameInfo()->setHasStackMap();
7090 }
7091
7092 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7093 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7094                                           MachineBasicBlock *LandingPad) {
7095   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7096   //                                                 i32 <numBytes>,
7097   //                                                 i8* <target>,
7098   //                                                 i32 <numArgs>,
7099   //                                                 [Args...],
7100   //                                                 [live variables...])
7101
7102   CallingConv::ID CC = CS.getCallingConv();
7103   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7104   bool HasDef = !CS->getType()->isVoidTy();
7105   SDValue Callee = getValue(CS->getOperand(2)); // <target>
7106
7107   // Get the real number of arguments participating in the call <numArgs>
7108   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7109   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7110
7111   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7112   // Intrinsics include all meta-operands up to but not including CC.
7113   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7114   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7115          "Not enough arguments provided to the patchpoint intrinsic");
7116
7117   // For AnyRegCC the arguments are lowered later on manually.
7118   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7119   std::pair<SDValue, SDValue> Result =
7120     lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC,
7121                       LandingPad);
7122
7123   SDNode *CallEnd = Result.second.getNode();
7124   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7125     CallEnd = CallEnd->getOperand(0).getNode();
7126
7127   /// Get a call instruction from the call sequence chain.
7128   /// Tail calls are not allowed.
7129   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7130          "Expected a callseq node.");
7131   SDNode *Call = CallEnd->getOperand(0).getNode();
7132   bool HasGlue = Call->getGluedNode();
7133
7134   // Replace the target specific call node with the patchable intrinsic.
7135   SmallVector<SDValue, 8> Ops;
7136
7137   // Add the <id> and <numBytes> constants.
7138   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7139   Ops.push_back(DAG.getTargetConstant(
7140                   cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
7141   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7142   Ops.push_back(DAG.getTargetConstant(
7143                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
7144
7145   // Assume that the Callee is a constant address.
7146   // FIXME: handle function symbols in the future.
7147   Ops.push_back(
7148     DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
7149                           /*isTarget=*/true));
7150
7151   // Adjust <numArgs> to account for any arguments that have been passed on the
7152   // stack instead.
7153   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7154   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7155   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7156   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
7157
7158   // Add the calling convention
7159   Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
7160
7161   // Add the arguments we omitted previously. The register allocator should
7162   // place these in any free register.
7163   if (IsAnyRegCC)
7164     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7165       Ops.push_back(getValue(CS.getArgument(i)));
7166
7167   // Push the arguments from the call instruction up to the register mask.
7168   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7169   for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
7170     Ops.push_back(*i);
7171
7172   // Push live variables for the stack map.
7173   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, Ops, *this);
7174
7175   // Push the register mask info.
7176   if (HasGlue)
7177     Ops.push_back(*(Call->op_end()-2));
7178   else
7179     Ops.push_back(*(Call->op_end()-1));
7180
7181   // Push the chain (this is originally the first operand of the call, but
7182   // becomes now the last or second to last operand).
7183   Ops.push_back(*(Call->op_begin()));
7184
7185   // Push the glue flag (last operand).
7186   if (HasGlue)
7187     Ops.push_back(*(Call->op_end()-1));
7188
7189   SDVTList NodeTys;
7190   if (IsAnyRegCC && HasDef) {
7191     // Create the return types based on the intrinsic definition
7192     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7193     SmallVector<EVT, 3> ValueVTs;
7194     ComputeValueVTs(TLI, CS->getType(), ValueVTs);
7195     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7196
7197     // There is always a chain and a glue type at the end
7198     ValueVTs.push_back(MVT::Other);
7199     ValueVTs.push_back(MVT::Glue);
7200     NodeTys = DAG.getVTList(ValueVTs);
7201   } else
7202     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7203
7204   // Replace the target specific call node with a PATCHPOINT node.
7205   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7206                                          getCurSDLoc(), NodeTys, Ops);
7207
7208   // Update the NodeMap.
7209   if (HasDef) {
7210     if (IsAnyRegCC)
7211       setValue(CS.getInstruction(), SDValue(MN, 0));
7212     else
7213       setValue(CS.getInstruction(), Result.first);
7214   }
7215
7216   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7217   // call sequence. Furthermore the location of the chain and glue can change
7218   // when the AnyReg calling convention is used and the intrinsic returns a
7219   // value.
7220   if (IsAnyRegCC && HasDef) {
7221     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7222     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7223     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7224   } else
7225     DAG.ReplaceAllUsesWith(Call, MN);
7226   DAG.DeleteNode(Call);
7227
7228   // Inform the Frame Information that we have a patchpoint in this function.
7229   FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
7230 }
7231
7232 /// Returns an AttributeSet representing the attributes applied to the return
7233 /// value of the given call.
7234 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7235   SmallVector<Attribute::AttrKind, 2> Attrs;
7236   if (CLI.RetSExt)
7237     Attrs.push_back(Attribute::SExt);
7238   if (CLI.RetZExt)
7239     Attrs.push_back(Attribute::ZExt);
7240   if (CLI.IsInReg)
7241     Attrs.push_back(Attribute::InReg);
7242
7243   return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7244                            Attrs);
7245 }
7246
7247 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7248 /// implementation, which just calls LowerCall.
7249 /// FIXME: When all targets are
7250 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7251 std::pair<SDValue, SDValue>
7252 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7253   // Handle the incoming return values from the call.
7254   CLI.Ins.clear();
7255   Type *OrigRetTy = CLI.RetTy;
7256   SmallVector<EVT, 4> RetTys;
7257   SmallVector<uint64_t, 4> Offsets;
7258   ComputeValueVTs(*this, CLI.RetTy, RetTys, &Offsets);
7259
7260   SmallVector<ISD::OutputArg, 4> Outs;
7261   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this);
7262
7263   bool CanLowerReturn =
7264       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7265                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7266
7267   SDValue DemoteStackSlot;
7268   int DemoteStackIdx = -100;
7269   if (!CanLowerReturn) {
7270     // FIXME: equivalent assert?
7271     // assert(!CS.hasInAllocaArgument() &&
7272     //        "sret demotion is incompatible with inalloca");
7273     uint64_t TySize = getDataLayout()->getTypeAllocSize(CLI.RetTy);
7274     unsigned Align  = getDataLayout()->getPrefTypeAlignment(CLI.RetTy);
7275     MachineFunction &MF = CLI.DAG.getMachineFunction();
7276     DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
7277     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7278
7279     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy());
7280     ArgListEntry Entry;
7281     Entry.Node = DemoteStackSlot;
7282     Entry.Ty = StackSlotPtrType;
7283     Entry.isSExt = false;
7284     Entry.isZExt = false;
7285     Entry.isInReg = false;
7286     Entry.isSRet = true;
7287     Entry.isNest = false;
7288     Entry.isByVal = false;
7289     Entry.isReturned = false;
7290     Entry.Alignment = Align;
7291     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7292     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7293   } else {
7294     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7295       EVT VT = RetTys[I];
7296       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7297       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7298       for (unsigned i = 0; i != NumRegs; ++i) {
7299         ISD::InputArg MyFlags;
7300         MyFlags.VT = RegisterVT;
7301         MyFlags.ArgVT = VT;
7302         MyFlags.Used = CLI.IsReturnValueUsed;
7303         if (CLI.RetSExt)
7304           MyFlags.Flags.setSExt();
7305         if (CLI.RetZExt)
7306           MyFlags.Flags.setZExt();
7307         if (CLI.IsInReg)
7308           MyFlags.Flags.setInReg();
7309         CLI.Ins.push_back(MyFlags);
7310       }
7311     }
7312   }
7313
7314   // Handle all of the outgoing arguments.
7315   CLI.Outs.clear();
7316   CLI.OutVals.clear();
7317   ArgListTy &Args = CLI.getArgs();
7318   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7319     SmallVector<EVT, 4> ValueVTs;
7320     ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
7321     Type *FinalType = Args[i].Ty;
7322     if (Args[i].isByVal)
7323       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7324     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7325         FinalType, CLI.CallConv, CLI.IsVarArg);
7326     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7327          ++Value) {
7328       EVT VT = ValueVTs[Value];
7329       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7330       SDValue Op = SDValue(Args[i].Node.getNode(),
7331                            Args[i].Node.getResNo() + Value);
7332       ISD::ArgFlagsTy Flags;
7333       unsigned OriginalAlignment = getDataLayout()->getABITypeAlignment(ArgTy);
7334
7335       if (Args[i].isZExt)
7336         Flags.setZExt();
7337       if (Args[i].isSExt)
7338         Flags.setSExt();
7339       if (Args[i].isInReg)
7340         Flags.setInReg();
7341       if (Args[i].isSRet)
7342         Flags.setSRet();
7343       if (Args[i].isByVal)
7344         Flags.setByVal();
7345       if (Args[i].isInAlloca) {
7346         Flags.setInAlloca();
7347         // Set the byval flag for CCAssignFn callbacks that don't know about
7348         // inalloca.  This way we can know how many bytes we should've allocated
7349         // and how many bytes a callee cleanup function will pop.  If we port
7350         // inalloca to more targets, we'll have to add custom inalloca handling
7351         // in the various CC lowering callbacks.
7352         Flags.setByVal();
7353       }
7354       if (Args[i].isByVal || Args[i].isInAlloca) {
7355         PointerType *Ty = cast<PointerType>(Args[i].Ty);
7356         Type *ElementTy = Ty->getElementType();
7357         Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
7358         // For ByVal, alignment should come from FE.  BE will guess if this
7359         // info is not there but there are cases it cannot get right.
7360         unsigned FrameAlign;
7361         if (Args[i].Alignment)
7362           FrameAlign = Args[i].Alignment;
7363         else
7364           FrameAlign = getByValTypeAlignment(ElementTy);
7365         Flags.setByValAlign(FrameAlign);
7366       }
7367       if (Args[i].isNest)
7368         Flags.setNest();
7369       if (NeedsRegBlock) {
7370         Flags.setInConsecutiveRegs();
7371         if (Value == NumValues - 1)
7372           Flags.setInConsecutiveRegsLast();
7373       }
7374       Flags.setOrigAlign(OriginalAlignment);
7375
7376       MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7377       unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7378       SmallVector<SDValue, 4> Parts(NumParts);
7379       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7380
7381       if (Args[i].isSExt)
7382         ExtendKind = ISD::SIGN_EXTEND;
7383       else if (Args[i].isZExt)
7384         ExtendKind = ISD::ZERO_EXTEND;
7385
7386       // Conservatively only handle 'returned' on non-vectors for now
7387       if (Args[i].isReturned && !Op.getValueType().isVector()) {
7388         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7389                "unexpected use of 'returned'");
7390         // Before passing 'returned' to the target lowering code, ensure that
7391         // either the register MVT and the actual EVT are the same size or that
7392         // the return value and argument are extended in the same way; in these
7393         // cases it's safe to pass the argument register value unchanged as the
7394         // return register value (although it's at the target's option whether
7395         // to do so)
7396         // TODO: allow code generation to take advantage of partially preserved
7397         // registers rather than clobbering the entire register when the
7398         // parameter extension method is not compatible with the return
7399         // extension method
7400         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7401             (ExtendKind != ISD::ANY_EXTEND &&
7402              CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7403         Flags.setReturned();
7404       }
7405
7406       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7407                      CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
7408
7409       for (unsigned j = 0; j != NumParts; ++j) {
7410         // if it isn't first piece, alignment must be 1
7411         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7412                                i < CLI.NumFixedArgs,
7413                                i, j*Parts[j].getValueType().getStoreSize());
7414         if (NumParts > 1 && j == 0)
7415           MyFlags.Flags.setSplit();
7416         else if (j != 0)
7417           MyFlags.Flags.setOrigAlign(1);
7418
7419         CLI.Outs.push_back(MyFlags);
7420         CLI.OutVals.push_back(Parts[j]);
7421       }
7422     }
7423   }
7424
7425   SmallVector<SDValue, 4> InVals;
7426   CLI.Chain = LowerCall(CLI, InVals);
7427
7428   // Verify that the target's LowerCall behaved as expected.
7429   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7430          "LowerCall didn't return a valid chain!");
7431   assert((!CLI.IsTailCall || InVals.empty()) &&
7432          "LowerCall emitted a return value for a tail call!");
7433   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7434          "LowerCall didn't emit the correct number of values!");
7435
7436   // For a tail call, the return value is merely live-out and there aren't
7437   // any nodes in the DAG representing it. Return a special value to
7438   // indicate that a tail call has been emitted and no more Instructions
7439   // should be processed in the current block.
7440   if (CLI.IsTailCall) {
7441     CLI.DAG.setRoot(CLI.Chain);
7442     return std::make_pair(SDValue(), SDValue());
7443   }
7444
7445   DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7446           assert(InVals[i].getNode() &&
7447                  "LowerCall emitted a null value!");
7448           assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7449                  "LowerCall emitted a value with the wrong type!");
7450         });
7451
7452   SmallVector<SDValue, 4> ReturnValues;
7453   if (!CanLowerReturn) {
7454     // The instruction result is the result of loading from the
7455     // hidden sret parameter.
7456     SmallVector<EVT, 1> PVTs;
7457     Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
7458
7459     ComputeValueVTs(*this, PtrRetTy, PVTs);
7460     assert(PVTs.size() == 1 && "Pointers should fit in one register");
7461     EVT PtrVT = PVTs[0];
7462
7463     unsigned NumValues = RetTys.size();
7464     ReturnValues.resize(NumValues);
7465     SmallVector<SDValue, 4> Chains(NumValues);
7466
7467     for (unsigned i = 0; i < NumValues; ++i) {
7468       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7469                                     CLI.DAG.getConstant(Offsets[i], PtrVT));
7470       SDValue L = CLI.DAG.getLoad(
7471           RetTys[i], CLI.DL, CLI.Chain, Add,
7472           MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
7473           false, false, 1);
7474       ReturnValues[i] = L;
7475       Chains[i] = L.getValue(1);
7476     }
7477
7478     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7479   } else {
7480     // Collect the legal value parts into potentially illegal values
7481     // that correspond to the original function's return values.
7482     ISD::NodeType AssertOp = ISD::DELETED_NODE;
7483     if (CLI.RetSExt)
7484       AssertOp = ISD::AssertSext;
7485     else if (CLI.RetZExt)
7486       AssertOp = ISD::AssertZext;
7487     unsigned CurReg = 0;
7488     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7489       EVT VT = RetTys[I];
7490       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7491       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7492
7493       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7494                                               NumRegs, RegisterVT, VT, nullptr,
7495                                               AssertOp));
7496       CurReg += NumRegs;
7497     }
7498
7499     // For a function returning void, there is no return value. We can't create
7500     // such a node, so we just return a null return value in that case. In
7501     // that case, nothing will actually look at the value.
7502     if (ReturnValues.empty())
7503       return std::make_pair(SDValue(), CLI.Chain);
7504   }
7505
7506   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7507                                 CLI.DAG.getVTList(RetTys), ReturnValues);
7508   return std::make_pair(Res, CLI.Chain);
7509 }
7510
7511 void TargetLowering::LowerOperationWrapper(SDNode *N,
7512                                            SmallVectorImpl<SDValue> &Results,
7513                                            SelectionDAG &DAG) const {
7514   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
7515   if (Res.getNode())
7516     Results.push_back(Res);
7517 }
7518
7519 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7520   llvm_unreachable("LowerOperation not implemented for this target!");
7521 }
7522
7523 void
7524 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7525   SDValue Op = getNonRegisterValue(V);
7526   assert((Op.getOpcode() != ISD::CopyFromReg ||
7527           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7528          "Copy from a reg to the same reg!");
7529   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7530
7531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7532   RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
7533   SDValue Chain = DAG.getEntryNode();
7534
7535   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7536                               FuncInfo.PreferredExtendType.end())
7537                                  ? ISD::ANY_EXTEND
7538                                  : FuncInfo.PreferredExtendType[V];
7539   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
7540   PendingExports.push_back(Chain);
7541 }
7542
7543 #include "llvm/CodeGen/SelectionDAGISel.h"
7544
7545 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7546 /// entry block, return true.  This includes arguments used by switches, since
7547 /// the switch may expand into multiple basic blocks.
7548 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7549   // With FastISel active, we may be splitting blocks, so force creation
7550   // of virtual registers for all non-dead arguments.
7551   if (FastISel)
7552     return A->use_empty();
7553
7554   const BasicBlock *Entry = A->getParent()->begin();
7555   for (const User *U : A->users())
7556     if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7557       return false;  // Use not in entry block.
7558
7559   return true;
7560 }
7561
7562 void SelectionDAGISel::LowerArguments(const Function &F) {
7563   SelectionDAG &DAG = SDB->DAG;
7564   SDLoc dl = SDB->getCurSDLoc();
7565   const DataLayout *DL = TLI->getDataLayout();
7566   SmallVector<ISD::InputArg, 16> Ins;
7567
7568   if (!FuncInfo->CanLowerReturn) {
7569     // Put in an sret pointer parameter before all the other parameters.
7570     SmallVector<EVT, 1> ValueVTs;
7571     ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7572
7573     // NOTE: Assuming that a pointer will never break down to more than one VT
7574     // or one register.
7575     ISD::ArgFlagsTy Flags;
7576     Flags.setSRet();
7577     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7578     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
7579     Ins.push_back(RetArg);
7580   }
7581
7582   // Set up the incoming argument description vector.
7583   unsigned Idx = 1;
7584   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7585        I != E; ++I, ++Idx) {
7586     SmallVector<EVT, 4> ValueVTs;
7587     ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7588     bool isArgValueUsed = !I->use_empty();
7589     unsigned PartBase = 0;
7590     Type *FinalType = I->getType();
7591     if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7592       FinalType = cast<PointerType>(FinalType)->getElementType();
7593     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7594         FinalType, F.getCallingConv(), F.isVarArg());
7595     for (unsigned Value = 0, NumValues = ValueVTs.size();
7596          Value != NumValues; ++Value) {
7597       EVT VT = ValueVTs[Value];
7598       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7599       ISD::ArgFlagsTy Flags;
7600       unsigned OriginalAlignment = DL->getABITypeAlignment(ArgTy);
7601
7602       if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7603         Flags.setZExt();
7604       if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7605         Flags.setSExt();
7606       if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7607         Flags.setInReg();
7608       if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7609         Flags.setSRet();
7610       if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7611         Flags.setByVal();
7612       if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7613         Flags.setInAlloca();
7614         // Set the byval flag for CCAssignFn callbacks that don't know about
7615         // inalloca.  This way we can know how many bytes we should've allocated
7616         // and how many bytes a callee cleanup function will pop.  If we port
7617         // inalloca to more targets, we'll have to add custom inalloca handling
7618         // in the various CC lowering callbacks.
7619         Flags.setByVal();
7620       }
7621       if (Flags.isByVal() || Flags.isInAlloca()) {
7622         PointerType *Ty = cast<PointerType>(I->getType());
7623         Type *ElementTy = Ty->getElementType();
7624         Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
7625         // For ByVal, alignment should be passed from FE.  BE will guess if
7626         // this info is not there but there are cases it cannot get right.
7627         unsigned FrameAlign;
7628         if (F.getParamAlignment(Idx))
7629           FrameAlign = F.getParamAlignment(Idx);
7630         else
7631           FrameAlign = TLI->getByValTypeAlignment(ElementTy);
7632         Flags.setByValAlign(FrameAlign);
7633       }
7634       if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7635         Flags.setNest();
7636       if (NeedsRegBlock) {
7637         Flags.setInConsecutiveRegs();
7638         if (Value == NumValues - 1)
7639           Flags.setInConsecutiveRegsLast();
7640       }
7641       Flags.setOrigAlign(OriginalAlignment);
7642
7643       MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7644       unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7645       for (unsigned i = 0; i != NumRegs; ++i) {
7646         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7647                               Idx-1, PartBase+i*RegisterVT.getStoreSize());
7648         if (NumRegs > 1 && i == 0)
7649           MyFlags.Flags.setSplit();
7650         // if it isn't first piece, alignment must be 1
7651         else if (i > 0)
7652           MyFlags.Flags.setOrigAlign(1);
7653         Ins.push_back(MyFlags);
7654       }
7655       PartBase += VT.getStoreSize();
7656     }
7657   }
7658
7659   // Call the target to set up the argument values.
7660   SmallVector<SDValue, 8> InVals;
7661   SDValue NewRoot = TLI->LowerFormalArguments(
7662       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
7663
7664   // Verify that the target's LowerFormalArguments behaved as expected.
7665   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7666          "LowerFormalArguments didn't return a valid chain!");
7667   assert(InVals.size() == Ins.size() &&
7668          "LowerFormalArguments didn't emit the correct number of values!");
7669   DEBUG({
7670       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7671         assert(InVals[i].getNode() &&
7672                "LowerFormalArguments emitted a null value!");
7673         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7674                "LowerFormalArguments emitted a value with the wrong type!");
7675       }
7676     });
7677
7678   // Update the DAG with the new chain value resulting from argument lowering.
7679   DAG.setRoot(NewRoot);
7680
7681   // Set up the argument values.
7682   unsigned i = 0;
7683   Idx = 1;
7684   if (!FuncInfo->CanLowerReturn) {
7685     // Create a virtual register for the sret pointer, and put in a copy
7686     // from the sret argument into it.
7687     SmallVector<EVT, 1> ValueVTs;
7688     ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7689     MVT VT = ValueVTs[0].getSimpleVT();
7690     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7691     ISD::NodeType AssertOp = ISD::DELETED_NODE;
7692     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7693                                         RegVT, VT, nullptr, AssertOp);
7694
7695     MachineFunction& MF = SDB->DAG.getMachineFunction();
7696     MachineRegisterInfo& RegInfo = MF.getRegInfo();
7697     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7698     FuncInfo->DemoteRegister = SRetReg;
7699     NewRoot =
7700         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
7701     DAG.setRoot(NewRoot);
7702
7703     // i indexes lowered arguments.  Bump it past the hidden sret argument.
7704     // Idx indexes LLVM arguments.  Don't touch it.
7705     ++i;
7706   }
7707
7708   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7709       ++I, ++Idx) {
7710     SmallVector<SDValue, 4> ArgValues;
7711     SmallVector<EVT, 4> ValueVTs;
7712     ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7713     unsigned NumValues = ValueVTs.size();
7714
7715     // If this argument is unused then remember its value. It is used to generate
7716     // debugging information.
7717     if (I->use_empty() && NumValues) {
7718       SDB->setUnusedArgValue(I, InVals[i]);
7719
7720       // Also remember any frame index for use in FastISel.
7721       if (FrameIndexSDNode *FI =
7722           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7723         FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7724     }
7725
7726     for (unsigned Val = 0; Val != NumValues; ++Val) {
7727       EVT VT = ValueVTs[Val];
7728       MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7729       unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7730
7731       if (!I->use_empty()) {
7732         ISD::NodeType AssertOp = ISD::DELETED_NODE;
7733         if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7734           AssertOp = ISD::AssertSext;
7735         else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7736           AssertOp = ISD::AssertZext;
7737
7738         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7739                                              NumParts, PartVT, VT,
7740                                              nullptr, AssertOp));
7741       }
7742
7743       i += NumParts;
7744     }
7745
7746     // We don't need to do anything else for unused arguments.
7747     if (ArgValues.empty())
7748       continue;
7749
7750     // Note down frame index.
7751     if (FrameIndexSDNode *FI =
7752         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7753       FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7754
7755     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
7756                                      SDB->getCurSDLoc());
7757
7758     SDB->setValue(I, Res);
7759     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7760       if (LoadSDNode *LNode =
7761           dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7762         if (FrameIndexSDNode *FI =
7763             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7764         FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7765     }
7766
7767     // If this argument is live outside of the entry block, insert a copy from
7768     // wherever we got it to the vreg that other BB's will reference it as.
7769     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7770       // If we can, though, try to skip creating an unnecessary vreg.
7771       // FIXME: This isn't very clean... it would be nice to make this more
7772       // general.  It's also subtly incompatible with the hacks FastISel
7773       // uses with vregs.
7774       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7775       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7776         FuncInfo->ValueMap[I] = Reg;
7777         continue;
7778       }
7779     }
7780     if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
7781       FuncInfo->InitializeRegForValue(I);
7782       SDB->CopyToExportRegsIfNeeded(I);
7783     }
7784   }
7785
7786   assert(i == InVals.size() && "Argument register count mismatch!");
7787
7788   // Finally, if the target has anything special to do, allow it to do so.
7789   // FIXME: this should insert code into the DAG!
7790   EmitFunctionEntryCode();
7791 }
7792
7793 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
7794 /// ensure constants are generated when needed.  Remember the virtual registers
7795 /// that need to be added to the Machine PHI nodes as input.  We cannot just
7796 /// directly add them, because expansion might result in multiple MBB's for one
7797 /// BB.  As such, the start of the BB might correspond to a different MBB than
7798 /// the end.
7799 ///
7800 void
7801 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7802   const TerminatorInst *TI = LLVMBB->getTerminator();
7803
7804   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7805
7806   // Check successor nodes' PHI nodes that expect a constant to be available
7807   // from this block.
7808   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7809     const BasicBlock *SuccBB = TI->getSuccessor(succ);
7810     if (!isa<PHINode>(SuccBB->begin())) continue;
7811     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7812
7813     // If this terminator has multiple identical successors (common for
7814     // switches), only handle each succ once.
7815     if (!SuccsHandled.insert(SuccMBB).second)
7816       continue;
7817
7818     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7819
7820     // At this point we know that there is a 1-1 correspondence between LLVM PHI
7821     // nodes and Machine PHI nodes, but the incoming operands have not been
7822     // emitted yet.
7823     for (BasicBlock::const_iterator I = SuccBB->begin();
7824          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7825       // Ignore dead phi's.
7826       if (PN->use_empty()) continue;
7827
7828       // Skip empty types
7829       if (PN->getType()->isEmptyTy())
7830         continue;
7831
7832       unsigned Reg;
7833       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7834
7835       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7836         unsigned &RegOut = ConstantsOut[C];
7837         if (RegOut == 0) {
7838           RegOut = FuncInfo.CreateRegs(C->getType());
7839           CopyValueToVirtualRegister(C, RegOut);
7840         }
7841         Reg = RegOut;
7842       } else {
7843         DenseMap<const Value *, unsigned>::iterator I =
7844           FuncInfo.ValueMap.find(PHIOp);
7845         if (I != FuncInfo.ValueMap.end())
7846           Reg = I->second;
7847         else {
7848           assert(isa<AllocaInst>(PHIOp) &&
7849                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7850                  "Didn't codegen value into a register!??");
7851           Reg = FuncInfo.CreateRegs(PHIOp->getType());
7852           CopyValueToVirtualRegister(PHIOp, Reg);
7853         }
7854       }
7855
7856       // Remember that this register needs to added to the machine PHI node as
7857       // the input for this MBB.
7858       SmallVector<EVT, 4> ValueVTs;
7859       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7860       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
7861       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7862         EVT VT = ValueVTs[vti];
7863         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
7864         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7865           FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7866         Reg += NumRegisters;
7867       }
7868     }
7869   }
7870
7871   ConstantsOut.clear();
7872 }
7873
7874 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7875 /// is 0.
7876 MachineBasicBlock *
7877 SelectionDAGBuilder::StackProtectorDescriptor::
7878 AddSuccessorMBB(const BasicBlock *BB,
7879                 MachineBasicBlock *ParentMBB,
7880                 bool IsLikely,
7881                 MachineBasicBlock *SuccMBB) {
7882   // If SuccBB has not been created yet, create it.
7883   if (!SuccMBB) {
7884     MachineFunction *MF = ParentMBB->getParent();
7885     MachineFunction::iterator BBI = ParentMBB;
7886     SuccMBB = MF->CreateMachineBasicBlock(BB);
7887     MF->insert(++BBI, SuccMBB);
7888   }
7889   // Add it as a successor of ParentMBB.
7890   ParentMBB->addSuccessor(
7891       SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely));
7892   return SuccMBB;
7893 }