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