xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 3a8f7f9e31dec87ccdc2ca83486e6c8a5c295e9d)
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   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3660   LLVMContext &Ctx = *DAG.getContext();
3661 
3662   SDLoc dl = getCurSDLoc();
3663   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3664   AtomicOrdering FailureOrder = I.getFailureOrdering();
3665   SynchronizationScope Scope = I.getSynchScope();
3666 
3667   SDValue InChain = getRoot();
3668 
3669   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3670   EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), Ctx, MVT::i1);
3671 
3672   // Only use the result of getSetCCResultType if it is legal,
3673   // otherwise just use the promoted result type (NVT).
3674   if (!TLI.isTypeLegal(CCVT))
3675     CCVT = TLI.getTypeToTransformTo(Ctx, MVT::i1);
3676 
3677   SDVTList VTs = DAG.getVTList(MemVT, CCVT, MVT::Other);
3678   SDValue L = DAG.getAtomicCmpSwap(
3679       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3680       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3681       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3682       /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3683 
3684   SDValue OutChain = L.getValue(2);
3685 
3686   setValue(&I, L);
3687   DAG.setRoot(OutChain);
3688 }
3689 
3690 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3691   SDLoc dl = getCurSDLoc();
3692   ISD::NodeType NT;
3693   switch (I.getOperation()) {
3694   default: llvm_unreachable("Unknown atomicrmw operation");
3695   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3696   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
3697   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
3698   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
3699   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3700   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
3701   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
3702   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
3703   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
3704   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3705   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3706   }
3707   AtomicOrdering Order = I.getOrdering();
3708   SynchronizationScope Scope = I.getSynchScope();
3709 
3710   SDValue InChain = getRoot();
3711 
3712   SDValue L =
3713     DAG.getAtomic(NT, dl,
3714                   getValue(I.getValOperand()).getSimpleValueType(),
3715                   InChain,
3716                   getValue(I.getPointerOperand()),
3717                   getValue(I.getValOperand()),
3718                   I.getPointerOperand(),
3719                   /* Alignment=*/ 0, Order, Scope);
3720 
3721   SDValue OutChain = L.getValue(1);
3722 
3723   setValue(&I, L);
3724   DAG.setRoot(OutChain);
3725 }
3726 
3727 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3728   SDLoc dl = getCurSDLoc();
3729   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3730   SDValue Ops[3];
3731   Ops[0] = getRoot();
3732   Ops[1] = DAG.getConstant(I.getOrdering(), dl,
3733                            TLI.getPointerTy(DAG.getDataLayout()));
3734   Ops[2] = DAG.getConstant(I.getSynchScope(), dl,
3735                            TLI.getPointerTy(DAG.getDataLayout()));
3736   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3737 }
3738 
3739 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3740   SDLoc dl = getCurSDLoc();
3741   AtomicOrdering Order = I.getOrdering();
3742   SynchronizationScope Scope = I.getSynchScope();
3743 
3744   SDValue InChain = getRoot();
3745 
3746   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3747   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3748 
3749   if (I.getAlignment() < VT.getSizeInBits() / 8)
3750     report_fatal_error("Cannot generate unaligned atomic load");
3751 
3752   MachineMemOperand *MMO =
3753       DAG.getMachineFunction().
3754       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3755                            MachineMemOperand::MOVolatile |
3756                            MachineMemOperand::MOLoad,
3757                            VT.getStoreSize(),
3758                            I.getAlignment() ? I.getAlignment() :
3759                                               DAG.getEVTAlignment(VT));
3760 
3761   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3762   SDValue L =
3763       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3764                     getValue(I.getPointerOperand()), MMO,
3765                     Order, Scope);
3766 
3767   SDValue OutChain = L.getValue(1);
3768 
3769   setValue(&I, L);
3770   DAG.setRoot(OutChain);
3771 }
3772 
3773 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3774   SDLoc dl = getCurSDLoc();
3775 
3776   AtomicOrdering Order = I.getOrdering();
3777   SynchronizationScope Scope = I.getSynchScope();
3778 
3779   SDValue InChain = getRoot();
3780 
3781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3782   EVT VT =
3783       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
3784 
3785   if (I.getAlignment() < VT.getSizeInBits() / 8)
3786     report_fatal_error("Cannot generate unaligned atomic store");
3787 
3788   SDValue OutChain =
3789     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3790                   InChain,
3791                   getValue(I.getPointerOperand()),
3792                   getValue(I.getValueOperand()),
3793                   I.getPointerOperand(), I.getAlignment(),
3794                   Order, Scope);
3795 
3796   DAG.setRoot(OutChain);
3797 }
3798 
3799 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3800 /// node.
3801 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3802                                                unsigned Intrinsic) {
3803   bool HasChain = !I.doesNotAccessMemory();
3804   bool OnlyLoad = HasChain && I.onlyReadsMemory();
3805 
3806   // Build the operand list.
3807   SmallVector<SDValue, 8> Ops;
3808   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
3809     if (OnlyLoad) {
3810       // We don't need to serialize loads against other loads.
3811       Ops.push_back(DAG.getRoot());
3812     } else {
3813       Ops.push_back(getRoot());
3814     }
3815   }
3816 
3817   // Info is set by getTgtMemInstrinsic
3818   TargetLowering::IntrinsicInfo Info;
3819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3820   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3821 
3822   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3823   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3824       Info.opc == ISD::INTRINSIC_W_CHAIN)
3825     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
3826                                         TLI.getPointerTy(DAG.getDataLayout())));
3827 
3828   // Add all operands of the call to the operand list.
3829   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3830     SDValue Op = getValue(I.getArgOperand(i));
3831     Ops.push_back(Op);
3832   }
3833 
3834   SmallVector<EVT, 4> ValueVTs;
3835   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
3836 
3837   if (HasChain)
3838     ValueVTs.push_back(MVT::Other);
3839 
3840   SDVTList VTs = DAG.getVTList(ValueVTs);
3841 
3842   // Create the node.
3843   SDValue Result;
3844   if (IsTgtIntrinsic) {
3845     // This is target intrinsic that touches memory
3846     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3847                                      VTs, Ops, Info.memVT,
3848                                    MachinePointerInfo(Info.ptrVal, Info.offset),
3849                                      Info.align, Info.vol,
3850                                      Info.readMem, Info.writeMem, Info.size);
3851   } else if (!HasChain) {
3852     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
3853   } else if (!I.getType()->isVoidTy()) {
3854     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
3855   } else {
3856     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
3857   }
3858 
3859   if (HasChain) {
3860     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3861     if (OnlyLoad)
3862       PendingLoads.push_back(Chain);
3863     else
3864       DAG.setRoot(Chain);
3865   }
3866 
3867   if (!I.getType()->isVoidTy()) {
3868     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3869       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
3870       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3871     } else
3872       Result = lowerRangeToAssertZExt(DAG, I, Result);
3873 
3874     setValue(&I, Result);
3875   }
3876 }
3877 
3878 /// GetSignificand - Get the significand and build it into a floating-point
3879 /// number with exponent of 1:
3880 ///
3881 ///   Op = (Op & 0x007fffff) | 0x3f800000;
3882 ///
3883 /// where Op is the hexadecimal representation of floating point value.
3884 static SDValue
3885 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3886   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3887                            DAG.getConstant(0x007fffff, dl, MVT::i32));
3888   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3889                            DAG.getConstant(0x3f800000, dl, MVT::i32));
3890   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3891 }
3892 
3893 /// GetExponent - Get the exponent:
3894 ///
3895 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3896 ///
3897 /// where Op is the hexadecimal representation of floating point value.
3898 static SDValue
3899 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3900             SDLoc dl) {
3901   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3902                            DAG.getConstant(0x7f800000, dl, MVT::i32));
3903   SDValue t1 = DAG.getNode(
3904       ISD::SRL, dl, MVT::i32, t0,
3905       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
3906   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3907                            DAG.getConstant(127, dl, MVT::i32));
3908   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3909 }
3910 
3911 /// getF32Constant - Get 32-bit floating point constant.
3912 static SDValue
3913 getF32Constant(SelectionDAG &DAG, unsigned Flt, SDLoc dl) {
3914   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl,
3915                            MVT::f32);
3916 }
3917 
3918 static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl,
3919                                        SelectionDAG &DAG) {
3920   // TODO: What fast-math-flags should be set on the floating-point nodes?
3921 
3922   //   IntegerPartOfX = ((int32_t)(t0);
3923   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3924 
3925   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
3926   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3927   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3928 
3929   //   IntegerPartOfX <<= 23;
3930   IntegerPartOfX = DAG.getNode(
3931       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3932       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
3933                                   DAG.getDataLayout())));
3934 
3935   SDValue TwoToFractionalPartOfX;
3936   if (LimitFloatPrecision <= 6) {
3937     // For floating-point precision of 6:
3938     //
3939     //   TwoToFractionalPartOfX =
3940     //     0.997535578f +
3941     //       (0.735607626f + 0.252464424f * x) * x;
3942     //
3943     // error 0.0144103317, which is 6 bits
3944     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3945                              getF32Constant(DAG, 0x3e814304, dl));
3946     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3947                              getF32Constant(DAG, 0x3f3c50c8, dl));
3948     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3949     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3950                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
3951   } else if (LimitFloatPrecision <= 12) {
3952     // For floating-point precision of 12:
3953     //
3954     //   TwoToFractionalPartOfX =
3955     //     0.999892986f +
3956     //       (0.696457318f +
3957     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3958     //
3959     // error 0.000107046256, which is 13 to 14 bits
3960     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3961                              getF32Constant(DAG, 0x3da235e3, dl));
3962     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3963                              getF32Constant(DAG, 0x3e65b8f3, dl));
3964     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3965     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3966                              getF32Constant(DAG, 0x3f324b07, dl));
3967     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3968     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3969                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
3970   } else { // LimitFloatPrecision <= 18
3971     // For floating-point precision of 18:
3972     //
3973     //   TwoToFractionalPartOfX =
3974     //     0.999999982f +
3975     //       (0.693148872f +
3976     //         (0.240227044f +
3977     //           (0.554906021e-1f +
3978     //             (0.961591928e-2f +
3979     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3980     // error 2.47208000*10^(-7), which is better than 18 bits
3981     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3982                              getF32Constant(DAG, 0x3924b03e, dl));
3983     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3984                              getF32Constant(DAG, 0x3ab24b87, dl));
3985     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3986     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3987                              getF32Constant(DAG, 0x3c1d8c17, dl));
3988     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3989     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3990                              getF32Constant(DAG, 0x3d634a1d, dl));
3991     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3992     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3993                              getF32Constant(DAG, 0x3e75fe14, dl));
3994     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3995     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3996                               getF32Constant(DAG, 0x3f317234, dl));
3997     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3998     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3999                                          getF32Constant(DAG, 0x3f800000, dl));
4000   }
4001 
4002   // Add the exponent into the result in integer domain.
4003   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4004   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4005                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4006 }
4007 
4008 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4009 /// limited-precision mode.
4010 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4011                          const TargetLowering &TLI) {
4012   if (Op.getValueType() == MVT::f32 &&
4013       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4014 
4015     // Put the exponent in the right bit position for later addition to the
4016     // final result:
4017     //
4018     //   #define LOG2OFe 1.4426950f
4019     //   t0 = Op * LOG2OFe
4020 
4021     // TODO: What fast-math-flags should be set here?
4022     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4023                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4024     return getLimitedPrecisionExp2(t0, dl, DAG);
4025   }
4026 
4027   // No special expansion.
4028   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4029 }
4030 
4031 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4032 /// limited-precision mode.
4033 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4034                          const TargetLowering &TLI) {
4035 
4036   // TODO: What fast-math-flags should be set on the floating-point nodes?
4037 
4038   if (Op.getValueType() == MVT::f32 &&
4039       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4040     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4041 
4042     // Scale the exponent by log(2) [0.69314718f].
4043     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4044     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4045                                         getF32Constant(DAG, 0x3f317218, dl));
4046 
4047     // Get the significand and build it into a floating-point number with
4048     // exponent of 1.
4049     SDValue X = GetSignificand(DAG, Op1, dl);
4050 
4051     SDValue LogOfMantissa;
4052     if (LimitFloatPrecision <= 6) {
4053       // For floating-point precision of 6:
4054       //
4055       //   LogofMantissa =
4056       //     -1.1609546f +
4057       //       (1.4034025f - 0.23903021f * x) * x;
4058       //
4059       // error 0.0034276066, which is better than 8 bits
4060       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4061                                getF32Constant(DAG, 0xbe74c456, dl));
4062       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4063                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4064       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4065       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4066                                   getF32Constant(DAG, 0x3f949a29, dl));
4067     } else if (LimitFloatPrecision <= 12) {
4068       // For floating-point precision of 12:
4069       //
4070       //   LogOfMantissa =
4071       //     -1.7417939f +
4072       //       (2.8212026f +
4073       //         (-1.4699568f +
4074       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4075       //
4076       // error 0.000061011436, which is 14 bits
4077       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4078                                getF32Constant(DAG, 0xbd67b6d6, dl));
4079       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4080                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4081       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4082       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4083                                getF32Constant(DAG, 0x3fbc278b, dl));
4084       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4085       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4086                                getF32Constant(DAG, 0x40348e95, dl));
4087       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4088       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4089                                   getF32Constant(DAG, 0x3fdef31a, dl));
4090     } else { // LimitFloatPrecision <= 18
4091       // For floating-point precision of 18:
4092       //
4093       //   LogOfMantissa =
4094       //     -2.1072184f +
4095       //       (4.2372794f +
4096       //         (-3.7029485f +
4097       //           (2.2781945f +
4098       //             (-0.87823314f +
4099       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4100       //
4101       // error 0.0000023660568, which is better than 18 bits
4102       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4103                                getF32Constant(DAG, 0xbc91e5ac, dl));
4104       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4105                                getF32Constant(DAG, 0x3e4350aa, dl));
4106       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4107       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4108                                getF32Constant(DAG, 0x3f60d3e3, dl));
4109       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4110       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4111                                getF32Constant(DAG, 0x4011cdf0, dl));
4112       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4113       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4114                                getF32Constant(DAG, 0x406cfd1c, dl));
4115       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4116       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4117                                getF32Constant(DAG, 0x408797cb, dl));
4118       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4119       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4120                                   getF32Constant(DAG, 0x4006dcab, dl));
4121     }
4122 
4123     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4124   }
4125 
4126   // No special expansion.
4127   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4128 }
4129 
4130 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4131 /// limited-precision mode.
4132 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4133                           const TargetLowering &TLI) {
4134 
4135   // TODO: What fast-math-flags should be set on the floating-point nodes?
4136 
4137   if (Op.getValueType() == MVT::f32 &&
4138       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4139     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4140 
4141     // Get the exponent.
4142     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4143 
4144     // Get the significand and build it into a floating-point number with
4145     // exponent of 1.
4146     SDValue X = GetSignificand(DAG, Op1, dl);
4147 
4148     // Different possible minimax approximations of significand in
4149     // floating-point for various degrees of accuracy over [1,2].
4150     SDValue Log2ofMantissa;
4151     if (LimitFloatPrecision <= 6) {
4152       // For floating-point precision of 6:
4153       //
4154       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4155       //
4156       // error 0.0049451742, which is more than 7 bits
4157       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4158                                getF32Constant(DAG, 0xbeb08fe0, dl));
4159       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4160                                getF32Constant(DAG, 0x40019463, dl));
4161       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4162       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4163                                    getF32Constant(DAG, 0x3fd6633d, dl));
4164     } else if (LimitFloatPrecision <= 12) {
4165       // For floating-point precision of 12:
4166       //
4167       //   Log2ofMantissa =
4168       //     -2.51285454f +
4169       //       (4.07009056f +
4170       //         (-2.12067489f +
4171       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4172       //
4173       // error 0.0000876136000, which is better than 13 bits
4174       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4175                                getF32Constant(DAG, 0xbda7262e, dl));
4176       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4177                                getF32Constant(DAG, 0x3f25280b, dl));
4178       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4179       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4180                                getF32Constant(DAG, 0x4007b923, dl));
4181       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4182       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4183                                getF32Constant(DAG, 0x40823e2f, dl));
4184       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4185       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4186                                    getF32Constant(DAG, 0x4020d29c, dl));
4187     } else { // LimitFloatPrecision <= 18
4188       // For floating-point precision of 18:
4189       //
4190       //   Log2ofMantissa =
4191       //     -3.0400495f +
4192       //       (6.1129976f +
4193       //         (-5.3420409f +
4194       //           (3.2865683f +
4195       //             (-1.2669343f +
4196       //               (0.27515199f -
4197       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4198       //
4199       // error 0.0000018516, which is better than 18 bits
4200       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4201                                getF32Constant(DAG, 0xbcd2769e, dl));
4202       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4203                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4204       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4205       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4206                                getF32Constant(DAG, 0x3fa22ae7, dl));
4207       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4208       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4209                                getF32Constant(DAG, 0x40525723, dl));
4210       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4211       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4212                                getF32Constant(DAG, 0x40aaf200, dl));
4213       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4214       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4215                                getF32Constant(DAG, 0x40c39dad, dl));
4216       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4217       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4218                                    getF32Constant(DAG, 0x4042902c, dl));
4219     }
4220 
4221     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4222   }
4223 
4224   // No special expansion.
4225   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4226 }
4227 
4228 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4229 /// limited-precision mode.
4230 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4231                            const TargetLowering &TLI) {
4232 
4233   // TODO: What fast-math-flags should be set on the floating-point nodes?
4234 
4235   if (Op.getValueType() == MVT::f32 &&
4236       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4237     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4238 
4239     // Scale the exponent by log10(2) [0.30102999f].
4240     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4241     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4242                                         getF32Constant(DAG, 0x3e9a209a, dl));
4243 
4244     // Get the significand and build it into a floating-point number with
4245     // exponent of 1.
4246     SDValue X = GetSignificand(DAG, Op1, dl);
4247 
4248     SDValue Log10ofMantissa;
4249     if (LimitFloatPrecision <= 6) {
4250       // For floating-point precision of 6:
4251       //
4252       //   Log10ofMantissa =
4253       //     -0.50419619f +
4254       //       (0.60948995f - 0.10380950f * x) * x;
4255       //
4256       // error 0.0014886165, which is 6 bits
4257       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4258                                getF32Constant(DAG, 0xbdd49a13, dl));
4259       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4260                                getF32Constant(DAG, 0x3f1c0789, dl));
4261       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4262       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4263                                     getF32Constant(DAG, 0x3f011300, dl));
4264     } else if (LimitFloatPrecision <= 12) {
4265       // For floating-point precision of 12:
4266       //
4267       //   Log10ofMantissa =
4268       //     -0.64831180f +
4269       //       (0.91751397f +
4270       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4271       //
4272       // error 0.00019228036, which is better than 12 bits
4273       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4274                                getF32Constant(DAG, 0x3d431f31, dl));
4275       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4276                                getF32Constant(DAG, 0x3ea21fb2, dl));
4277       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4278       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4279                                getF32Constant(DAG, 0x3f6ae232, dl));
4280       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4281       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4282                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4283     } else { // LimitFloatPrecision <= 18
4284       // For floating-point precision of 18:
4285       //
4286       //   Log10ofMantissa =
4287       //     -0.84299375f +
4288       //       (1.5327582f +
4289       //         (-1.0688956f +
4290       //           (0.49102474f +
4291       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4292       //
4293       // error 0.0000037995730, which is better than 18 bits
4294       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4295                                getF32Constant(DAG, 0x3c5d51ce, dl));
4296       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4297                                getF32Constant(DAG, 0x3e00685a, dl));
4298       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4299       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4300                                getF32Constant(DAG, 0x3efb6798, dl));
4301       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4302       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4303                                getF32Constant(DAG, 0x3f88d192, dl));
4304       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4305       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4306                                getF32Constant(DAG, 0x3fc4316c, dl));
4307       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4308       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4309                                     getF32Constant(DAG, 0x3f57ce70, dl));
4310     }
4311 
4312     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4313   }
4314 
4315   // No special expansion.
4316   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4317 }
4318 
4319 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4320 /// limited-precision mode.
4321 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4322                           const TargetLowering &TLI) {
4323   if (Op.getValueType() == MVT::f32 &&
4324       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4325     return getLimitedPrecisionExp2(Op, dl, DAG);
4326 
4327   // No special expansion.
4328   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4329 }
4330 
4331 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4332 /// limited-precision mode with x == 10.0f.
4333 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4334                          SelectionDAG &DAG, const TargetLowering &TLI) {
4335   bool IsExp10 = false;
4336   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4337       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4338     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4339       APFloat Ten(10.0f);
4340       IsExp10 = LHSC->isExactlyValue(Ten);
4341     }
4342   }
4343 
4344   // TODO: What fast-math-flags should be set on the FMUL node?
4345   if (IsExp10) {
4346     // Put the exponent in the right bit position for later addition to the
4347     // final result:
4348     //
4349     //   #define LOG2OF10 3.3219281f
4350     //   t0 = Op * LOG2OF10;
4351     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4352                              getF32Constant(DAG, 0x40549a78, dl));
4353     return getLimitedPrecisionExp2(t0, dl, DAG);
4354   }
4355 
4356   // No special expansion.
4357   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4358 }
4359 
4360 
4361 /// ExpandPowI - Expand a llvm.powi intrinsic.
4362 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4363                           SelectionDAG &DAG) {
4364   // If RHS is a constant, we can expand this out to a multiplication tree,
4365   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4366   // optimizing for size, we only want to do this if the expansion would produce
4367   // a small number of multiplies, otherwise we do the full expansion.
4368   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4369     // Get the exponent as a positive value.
4370     unsigned Val = RHSC->getSExtValue();
4371     if ((int)Val < 0) Val = -Val;
4372 
4373     // powi(x, 0) -> 1.0
4374     if (Val == 0)
4375       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4376 
4377     const Function *F = DAG.getMachineFunction().getFunction();
4378     if (!F->optForSize() ||
4379         // If optimizing for size, don't insert too many multiplies.
4380         // This inserts up to 5 multiplies.
4381         countPopulation(Val) + Log2_32(Val) < 7) {
4382       // We use the simple binary decomposition method to generate the multiply
4383       // sequence.  There are more optimal ways to do this (for example,
4384       // powi(x,15) generates one more multiply than it should), but this has
4385       // the benefit of being both really simple and much better than a libcall.
4386       SDValue Res;  // Logically starts equal to 1.0
4387       SDValue CurSquare = LHS;
4388       // TODO: Intrinsics should have fast-math-flags that propagate to these
4389       // nodes.
4390       while (Val) {
4391         if (Val & 1) {
4392           if (Res.getNode())
4393             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4394           else
4395             Res = CurSquare;  // 1.0*CurSquare.
4396         }
4397 
4398         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4399                                 CurSquare, CurSquare);
4400         Val >>= 1;
4401       }
4402 
4403       // If the original was negative, invert the result, producing 1/(x*x*x).
4404       if (RHSC->getSExtValue() < 0)
4405         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4406                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4407       return Res;
4408     }
4409   }
4410 
4411   // Otherwise, expand to a libcall.
4412   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4413 }
4414 
4415 // getUnderlyingArgReg - Find underlying register used for a truncated or
4416 // bitcasted argument.
4417 static unsigned getUnderlyingArgReg(const SDValue &N) {
4418   switch (N.getOpcode()) {
4419   case ISD::CopyFromReg:
4420     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4421   case ISD::BITCAST:
4422   case ISD::AssertZext:
4423   case ISD::AssertSext:
4424   case ISD::TRUNCATE:
4425     return getUnderlyingArgReg(N.getOperand(0));
4426   default:
4427     return 0;
4428   }
4429 }
4430 
4431 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4432 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4433 /// At the end of instruction selection, they will be inserted to the entry BB.
4434 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4435     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4436     DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
4437   const Argument *Arg = dyn_cast<Argument>(V);
4438   if (!Arg)
4439     return false;
4440 
4441   MachineFunction &MF = DAG.getMachineFunction();
4442   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4443 
4444   // Ignore inlined function arguments here.
4445   //
4446   // FIXME: Should we be checking DL->inlinedAt() to determine this?
4447   if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
4448     return false;
4449 
4450   Optional<MachineOperand> Op;
4451   // Some arguments' frame index is recorded during argument lowering.
4452   if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4453     Op = MachineOperand::CreateFI(FI);
4454 
4455   if (!Op && N.getNode()) {
4456     unsigned Reg = getUnderlyingArgReg(N);
4457     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4458       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4459       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4460       if (PR)
4461         Reg = PR;
4462     }
4463     if (Reg)
4464       Op = MachineOperand::CreateReg(Reg, false);
4465   }
4466 
4467   if (!Op) {
4468     // Check if ValueMap has reg number.
4469     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4470     if (VMI != FuncInfo.ValueMap.end())
4471       Op = MachineOperand::CreateReg(VMI->second, false);
4472   }
4473 
4474   if (!Op && N.getNode())
4475     // Check if frame index is available.
4476     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4477       if (FrameIndexSDNode *FINode =
4478           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4479         Op = MachineOperand::CreateFI(FINode->getIndex());
4480 
4481   if (!Op)
4482     return false;
4483 
4484   assert(Variable->isValidLocationForIntrinsic(DL) &&
4485          "Expected inlined-at fields to agree");
4486   if (Op->isReg())
4487     FuncInfo.ArgDbgValues.push_back(
4488         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4489                 Op->getReg(), Offset, Variable, Expr));
4490   else
4491     FuncInfo.ArgDbgValues.push_back(
4492         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4493             .addOperand(*Op)
4494             .addImm(Offset)
4495             .addMetadata(Variable)
4496             .addMetadata(Expr));
4497 
4498   return true;
4499 }
4500 
4501 // VisualStudio defines setjmp as _setjmp
4502 #if defined(_MSC_VER) && defined(setjmp) && \
4503                          !defined(setjmp_undefined_for_msvc)
4504 #  pragma push_macro("setjmp")
4505 #  undef setjmp
4506 #  define setjmp_undefined_for_msvc
4507 #endif
4508 
4509 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
4510 /// we want to emit this as a call to a named external function, return the name
4511 /// otherwise lower it and return null.
4512 const char *
4513 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4514   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4515   SDLoc sdl = getCurSDLoc();
4516   DebugLoc dl = getCurDebugLoc();
4517   SDValue Res;
4518 
4519   switch (Intrinsic) {
4520   default:
4521     // By default, turn this into a target intrinsic node.
4522     visitTargetIntrinsic(I, Intrinsic);
4523     return nullptr;
4524   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
4525   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
4526   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
4527   case Intrinsic::returnaddress:
4528     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
4529                              TLI.getPointerTy(DAG.getDataLayout()),
4530                              getValue(I.getArgOperand(0))));
4531     return nullptr;
4532   case Intrinsic::frameaddress:
4533     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
4534                              TLI.getPointerTy(DAG.getDataLayout()),
4535                              getValue(I.getArgOperand(0))));
4536     return nullptr;
4537   case Intrinsic::read_register: {
4538     Value *Reg = I.getArgOperand(0);
4539     SDValue Chain = getRoot();
4540     SDValue RegName =
4541         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4542     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4543     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
4544       DAG.getVTList(VT, MVT::Other), Chain, RegName);
4545     setValue(&I, Res);
4546     DAG.setRoot(Res.getValue(1));
4547     return nullptr;
4548   }
4549   case Intrinsic::write_register: {
4550     Value *Reg = I.getArgOperand(0);
4551     Value *RegValue = I.getArgOperand(1);
4552     SDValue Chain = getRoot();
4553     SDValue RegName =
4554         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4555     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4556                             RegName, getValue(RegValue)));
4557     return nullptr;
4558   }
4559   case Intrinsic::setjmp:
4560     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
4561   case Intrinsic::longjmp:
4562     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
4563   case Intrinsic::memcpy: {
4564     SDValue Op1 = getValue(I.getArgOperand(0));
4565     SDValue Op2 = getValue(I.getArgOperand(1));
4566     SDValue Op3 = getValue(I.getArgOperand(2));
4567     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4568     if (!Align)
4569       Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4570     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4571     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4572     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4573                                false, isTC,
4574                                MachinePointerInfo(I.getArgOperand(0)),
4575                                MachinePointerInfo(I.getArgOperand(1)));
4576     updateDAGForMaybeTailCall(MC);
4577     return nullptr;
4578   }
4579   case Intrinsic::memset: {
4580     SDValue Op1 = getValue(I.getArgOperand(0));
4581     SDValue Op2 = getValue(I.getArgOperand(1));
4582     SDValue Op3 = getValue(I.getArgOperand(2));
4583     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4584     if (!Align)
4585       Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4586     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4587     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4588     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4589                                isTC, MachinePointerInfo(I.getArgOperand(0)));
4590     updateDAGForMaybeTailCall(MS);
4591     return nullptr;
4592   }
4593   case Intrinsic::memmove: {
4594     SDValue Op1 = getValue(I.getArgOperand(0));
4595     SDValue Op2 = getValue(I.getArgOperand(1));
4596     SDValue Op3 = getValue(I.getArgOperand(2));
4597     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4598     if (!Align)
4599       Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4600     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4601     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4602     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4603                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
4604                                 MachinePointerInfo(I.getArgOperand(1)));
4605     updateDAGForMaybeTailCall(MM);
4606     return nullptr;
4607   }
4608   case Intrinsic::dbg_declare: {
4609     const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4610     DILocalVariable *Variable = DI.getVariable();
4611     DIExpression *Expression = DI.getExpression();
4612     const Value *Address = DI.getAddress();
4613     assert(Variable && "Missing variable");
4614     if (!Address) {
4615       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4616       return nullptr;
4617     }
4618 
4619     // Check if address has undef value.
4620     if (isa<UndefValue>(Address) ||
4621         (Address->use_empty() && !isa<Argument>(Address))) {
4622       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4623       return nullptr;
4624     }
4625 
4626     SDValue &N = NodeMap[Address];
4627     if (!N.getNode() && isa<Argument>(Address))
4628       // Check unused arguments map.
4629       N = UnusedArgNodeMap[Address];
4630     SDDbgValue *SDV;
4631     if (N.getNode()) {
4632       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4633         Address = BCI->getOperand(0);
4634       // Parameters are handled specially.
4635       bool isParameter = Variable->isParameter() || isa<Argument>(Address);
4636       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4637       if (isParameter && FINode) {
4638         // Byval parameter. We have a frame index at this point.
4639         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
4640                                         FINode->getIndex(), 0, dl, SDNodeOrder);
4641       } else if (isa<Argument>(Address)) {
4642         // Address is an argument, so try to emit its dbg value using
4643         // virtual register info from the FuncInfo.ValueMap.
4644         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4645                                  N);
4646         return nullptr;
4647       } else {
4648         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4649                               true, 0, dl, SDNodeOrder);
4650       }
4651       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4652     } else {
4653       // If Address is an argument then try to emit its dbg value using
4654       // virtual register info from the FuncInfo.ValueMap.
4655       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4656                                     N)) {
4657         // If variable is pinned by a alloca in dominating bb then
4658         // use StaticAllocaMap.
4659         if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4660           if (AI->getParent() != DI.getParent()) {
4661             DenseMap<const AllocaInst*, int>::iterator SI =
4662               FuncInfo.StaticAllocaMap.find(AI);
4663             if (SI != FuncInfo.StaticAllocaMap.end()) {
4664               SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
4665                                               0, dl, SDNodeOrder);
4666               DAG.AddDbgValue(SDV, nullptr, false);
4667               return nullptr;
4668             }
4669           }
4670         }
4671         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4672       }
4673     }
4674     return nullptr;
4675   }
4676   case Intrinsic::dbg_value: {
4677     const DbgValueInst &DI = cast<DbgValueInst>(I);
4678     assert(DI.getVariable() && "Missing variable");
4679 
4680     DILocalVariable *Variable = DI.getVariable();
4681     DIExpression *Expression = DI.getExpression();
4682     uint64_t Offset = DI.getOffset();
4683     const Value *V = DI.getValue();
4684     if (!V)
4685       return nullptr;
4686 
4687     SDDbgValue *SDV;
4688     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4689       SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4690                                     SDNodeOrder);
4691       DAG.AddDbgValue(SDV, nullptr, false);
4692     } else {
4693       // Do not use getValue() in here; we don't want to generate code at
4694       // this point if it hasn't been done yet.
4695       SDValue N = NodeMap[V];
4696       if (!N.getNode() && isa<Argument>(V))
4697         // Check unused arguments map.
4698         N = UnusedArgNodeMap[V];
4699       if (N.getNode()) {
4700         if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
4701                                       false, N)) {
4702           SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4703                                 false, Offset, dl, SDNodeOrder);
4704           DAG.AddDbgValue(SDV, N.getNode(), false);
4705         }
4706       } else if (!V->use_empty() ) {
4707         // Do not call getValue(V) yet, as we don't want to generate code.
4708         // Remember it for later.
4709         DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4710         DanglingDebugInfoMap[V] = DDI;
4711       } else {
4712         // We may expand this to cover more cases.  One case where we have no
4713         // data available is an unreferenced parameter.
4714         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4715       }
4716     }
4717 
4718     // Build a debug info table entry.
4719     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4720       V = BCI->getOperand(0);
4721     const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4722     // Don't handle byval struct arguments or VLAs, for example.
4723     if (!AI) {
4724       DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
4725       DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
4726       return nullptr;
4727     }
4728     DenseMap<const AllocaInst*, int>::iterator SI =
4729       FuncInfo.StaticAllocaMap.find(AI);
4730     if (SI == FuncInfo.StaticAllocaMap.end())
4731       return nullptr; // VLAs.
4732     return nullptr;
4733   }
4734 
4735   case Intrinsic::eh_typeid_for: {
4736     // Find the type id for the given typeinfo.
4737     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
4738     unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4739     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
4740     setValue(&I, Res);
4741     return nullptr;
4742   }
4743 
4744   case Intrinsic::eh_return_i32:
4745   case Intrinsic::eh_return_i64:
4746     DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4747     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4748                             MVT::Other,
4749                             getControlRoot(),
4750                             getValue(I.getArgOperand(0)),
4751                             getValue(I.getArgOperand(1))));
4752     return nullptr;
4753   case Intrinsic::eh_unwind_init:
4754     DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4755     return nullptr;
4756   case Intrinsic::eh_dwarf_cfa: {
4757     SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4758                                         TLI.getPointerTy(DAG.getDataLayout()));
4759     SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4760                                  CfaArg.getValueType(),
4761                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4762                                              CfaArg.getValueType()),
4763                                  CfaArg);
4764     SDValue FA = DAG.getNode(
4765         ISD::FRAMEADDR, sdl, TLI.getPointerTy(DAG.getDataLayout()),
4766         DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
4767     setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4768                              FA, Offset));
4769     return nullptr;
4770   }
4771   case Intrinsic::eh_sjlj_callsite: {
4772     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4773     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4774     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4775     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4776 
4777     MMI.setCurrentCallSite(CI->getZExtValue());
4778     return nullptr;
4779   }
4780   case Intrinsic::eh_sjlj_functioncontext: {
4781     // Get and store the index of the function context.
4782     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4783     AllocaInst *FnCtx =
4784       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4785     int FI = FuncInfo.StaticAllocaMap[FnCtx];
4786     MFI->setFunctionContextIndex(FI);
4787     return nullptr;
4788   }
4789   case Intrinsic::eh_sjlj_setjmp: {
4790     SDValue Ops[2];
4791     Ops[0] = getRoot();
4792     Ops[1] = getValue(I.getArgOperand(0));
4793     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4794                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
4795     setValue(&I, Op.getValue(0));
4796     DAG.setRoot(Op.getValue(1));
4797     return nullptr;
4798   }
4799   case Intrinsic::eh_sjlj_longjmp: {
4800     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4801                             getRoot(), getValue(I.getArgOperand(0))));
4802     return nullptr;
4803   }
4804   case Intrinsic::eh_sjlj_setup_dispatch: {
4805     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
4806                             getRoot()));
4807     return nullptr;
4808   }
4809 
4810   case Intrinsic::masked_gather:
4811     visitMaskedGather(I);
4812     return nullptr;
4813   case Intrinsic::masked_load:
4814     visitMaskedLoad(I);
4815     return nullptr;
4816   case Intrinsic::masked_scatter:
4817     visitMaskedScatter(I);
4818     return nullptr;
4819   case Intrinsic::masked_store:
4820     visitMaskedStore(I);
4821     return nullptr;
4822   case Intrinsic::x86_mmx_pslli_w:
4823   case Intrinsic::x86_mmx_pslli_d:
4824   case Intrinsic::x86_mmx_pslli_q:
4825   case Intrinsic::x86_mmx_psrli_w:
4826   case Intrinsic::x86_mmx_psrli_d:
4827   case Intrinsic::x86_mmx_psrli_q:
4828   case Intrinsic::x86_mmx_psrai_w:
4829   case Intrinsic::x86_mmx_psrai_d: {
4830     SDValue ShAmt = getValue(I.getArgOperand(1));
4831     if (isa<ConstantSDNode>(ShAmt)) {
4832       visitTargetIntrinsic(I, Intrinsic);
4833       return nullptr;
4834     }
4835     unsigned NewIntrinsic = 0;
4836     EVT ShAmtVT = MVT::v2i32;
4837     switch (Intrinsic) {
4838     case Intrinsic::x86_mmx_pslli_w:
4839       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4840       break;
4841     case Intrinsic::x86_mmx_pslli_d:
4842       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4843       break;
4844     case Intrinsic::x86_mmx_pslli_q:
4845       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4846       break;
4847     case Intrinsic::x86_mmx_psrli_w:
4848       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4849       break;
4850     case Intrinsic::x86_mmx_psrli_d:
4851       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4852       break;
4853     case Intrinsic::x86_mmx_psrli_q:
4854       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4855       break;
4856     case Intrinsic::x86_mmx_psrai_w:
4857       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4858       break;
4859     case Intrinsic::x86_mmx_psrai_d:
4860       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4861       break;
4862     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
4863     }
4864 
4865     // The vector shift intrinsics with scalars uses 32b shift amounts but
4866     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4867     // to be zero.
4868     // We must do this early because v2i32 is not a legal type.
4869     SDValue ShOps[2];
4870     ShOps[0] = ShAmt;
4871     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
4872     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
4873     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4874     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4875     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4876                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
4877                        getValue(I.getArgOperand(0)), ShAmt);
4878     setValue(&I, Res);
4879     return nullptr;
4880   }
4881   case Intrinsic::convertff:
4882   case Intrinsic::convertfsi:
4883   case Intrinsic::convertfui:
4884   case Intrinsic::convertsif:
4885   case Intrinsic::convertuif:
4886   case Intrinsic::convertss:
4887   case Intrinsic::convertsu:
4888   case Intrinsic::convertus:
4889   case Intrinsic::convertuu: {
4890     ISD::CvtCode Code = ISD::CVT_INVALID;
4891     switch (Intrinsic) {
4892     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
4893     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
4894     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4895     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4896     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4897     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4898     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
4899     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
4900     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
4901     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
4902     }
4903     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4904     const Value *Op1 = I.getArgOperand(0);
4905     Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
4906                                DAG.getValueType(DestVT),
4907                                DAG.getValueType(getValue(Op1).getValueType()),
4908                                getValue(I.getArgOperand(1)),
4909                                getValue(I.getArgOperand(2)),
4910                                Code);
4911     setValue(&I, Res);
4912     return nullptr;
4913   }
4914   case Intrinsic::powi:
4915     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
4916                             getValue(I.getArgOperand(1)), DAG));
4917     return nullptr;
4918   case Intrinsic::log:
4919     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4920     return nullptr;
4921   case Intrinsic::log2:
4922     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4923     return nullptr;
4924   case Intrinsic::log10:
4925     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4926     return nullptr;
4927   case Intrinsic::exp:
4928     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4929     return nullptr;
4930   case Intrinsic::exp2:
4931     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4932     return nullptr;
4933   case Intrinsic::pow:
4934     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
4935                            getValue(I.getArgOperand(1)), DAG, TLI));
4936     return nullptr;
4937   case Intrinsic::sqrt:
4938   case Intrinsic::fabs:
4939   case Intrinsic::sin:
4940   case Intrinsic::cos:
4941   case Intrinsic::floor:
4942   case Intrinsic::ceil:
4943   case Intrinsic::trunc:
4944   case Intrinsic::rint:
4945   case Intrinsic::nearbyint:
4946   case Intrinsic::round: {
4947     unsigned Opcode;
4948     switch (Intrinsic) {
4949     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
4950     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
4951     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
4952     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
4953     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
4954     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
4955     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
4956     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
4957     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
4958     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
4959     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
4960     }
4961 
4962     setValue(&I, DAG.getNode(Opcode, sdl,
4963                              getValue(I.getArgOperand(0)).getValueType(),
4964                              getValue(I.getArgOperand(0))));
4965     return nullptr;
4966   }
4967   case Intrinsic::minnum:
4968     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
4969                              getValue(I.getArgOperand(0)).getValueType(),
4970                              getValue(I.getArgOperand(0)),
4971                              getValue(I.getArgOperand(1))));
4972     return nullptr;
4973   case Intrinsic::maxnum:
4974     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
4975                              getValue(I.getArgOperand(0)).getValueType(),
4976                              getValue(I.getArgOperand(0)),
4977                              getValue(I.getArgOperand(1))));
4978     return nullptr;
4979   case Intrinsic::copysign:
4980     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
4981                              getValue(I.getArgOperand(0)).getValueType(),
4982                              getValue(I.getArgOperand(0)),
4983                              getValue(I.getArgOperand(1))));
4984     return nullptr;
4985   case Intrinsic::fma:
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     return nullptr;
4992   case Intrinsic::fmuladd: {
4993     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4994     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
4995         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
4996       setValue(&I, DAG.getNode(ISD::FMA, sdl,
4997                                getValue(I.getArgOperand(0)).getValueType(),
4998                                getValue(I.getArgOperand(0)),
4999                                getValue(I.getArgOperand(1)),
5000                                getValue(I.getArgOperand(2))));
5001     } else {
5002       // TODO: Intrinsic calls should have fast-math-flags.
5003       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5004                                 getValue(I.getArgOperand(0)).getValueType(),
5005                                 getValue(I.getArgOperand(0)),
5006                                 getValue(I.getArgOperand(1)));
5007       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5008                                 getValue(I.getArgOperand(0)).getValueType(),
5009                                 Mul,
5010                                 getValue(I.getArgOperand(2)));
5011       setValue(&I, Add);
5012     }
5013     return nullptr;
5014   }
5015   case Intrinsic::convert_to_fp16:
5016     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5017                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5018                                          getValue(I.getArgOperand(0)),
5019                                          DAG.getTargetConstant(0, sdl,
5020                                                                MVT::i32))));
5021     return nullptr;
5022   case Intrinsic::convert_from_fp16:
5023     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5024                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5025                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5026                                          getValue(I.getArgOperand(0)))));
5027     return nullptr;
5028   case Intrinsic::pcmarker: {
5029     SDValue Tmp = getValue(I.getArgOperand(0));
5030     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5031     return nullptr;
5032   }
5033   case Intrinsic::readcyclecounter: {
5034     SDValue Op = getRoot();
5035     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5036                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5037     setValue(&I, Res);
5038     DAG.setRoot(Res.getValue(1));
5039     return nullptr;
5040   }
5041   case Intrinsic::bitreverse:
5042     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5043                              getValue(I.getArgOperand(0)).getValueType(),
5044                              getValue(I.getArgOperand(0))));
5045     return nullptr;
5046   case Intrinsic::bswap:
5047     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5048                              getValue(I.getArgOperand(0)).getValueType(),
5049                              getValue(I.getArgOperand(0))));
5050     return nullptr;
5051   case Intrinsic::cttz: {
5052     SDValue Arg = getValue(I.getArgOperand(0));
5053     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5054     EVT Ty = Arg.getValueType();
5055     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5056                              sdl, Ty, Arg));
5057     return nullptr;
5058   }
5059   case Intrinsic::ctlz: {
5060     SDValue Arg = getValue(I.getArgOperand(0));
5061     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5062     EVT Ty = Arg.getValueType();
5063     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5064                              sdl, Ty, Arg));
5065     return nullptr;
5066   }
5067   case Intrinsic::ctpop: {
5068     SDValue Arg = getValue(I.getArgOperand(0));
5069     EVT Ty = Arg.getValueType();
5070     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5071     return nullptr;
5072   }
5073   case Intrinsic::stacksave: {
5074     SDValue Op = getRoot();
5075     Res = DAG.getNode(
5076         ISD::STACKSAVE, sdl,
5077         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5078     setValue(&I, Res);
5079     DAG.setRoot(Res.getValue(1));
5080     return nullptr;
5081   }
5082   case Intrinsic::stackrestore: {
5083     Res = getValue(I.getArgOperand(0));
5084     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5085     return nullptr;
5086   }
5087   case Intrinsic::get_dynamic_area_offset: {
5088     SDValue Op = getRoot();
5089     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5090     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5091     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5092     // target.
5093     if (PtrTy != ResTy)
5094       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5095                          " intrinsic!");
5096     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5097                       Op);
5098     DAG.setRoot(Op);
5099     setValue(&I, Res);
5100     return nullptr;
5101   }
5102   case Intrinsic::stackprotector: {
5103     // Emit code into the DAG to store the stack guard onto the stack.
5104     MachineFunction &MF = DAG.getMachineFunction();
5105     MachineFrameInfo *MFI = MF.getFrameInfo();
5106     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5107     SDValue Src, Chain = getRoot();
5108     const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
5109     const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
5110 
5111     // See if Ptr is a bitcast. If it is, look through it and see if we can get
5112     // global variable __stack_chk_guard.
5113     if (!GV)
5114       if (const Operator *BC = dyn_cast<Operator>(Ptr))
5115         if (BC->getOpcode() == Instruction::BitCast)
5116           GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
5117 
5118     if (GV && TLI.useLoadStackGuardNode()) {
5119       // Emit a LOAD_STACK_GUARD node.
5120       MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
5121                                                sdl, PtrTy, Chain);
5122       MachinePointerInfo MPInfo(GV);
5123       MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
5124       unsigned Flags = MachineMemOperand::MOLoad |
5125                        MachineMemOperand::MOInvariant;
5126       *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
5127                                          PtrTy.getSizeInBits() / 8,
5128                                          DAG.getEVTAlignment(PtrTy));
5129       Node->setMemRefs(MemRefs, MemRefs + 1);
5130 
5131       // Copy the guard value to a virtual register so that it can be
5132       // retrieved in the epilogue.
5133       Src = SDValue(Node, 0);
5134       const TargetRegisterClass *RC =
5135           TLI.getRegClassFor(Src.getSimpleValueType());
5136       unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
5137 
5138       SPDescriptor.setGuardReg(Reg);
5139       Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
5140     } else {
5141       Src = getValue(I.getArgOperand(0));   // The guard's value.
5142     }
5143 
5144     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5145 
5146     int FI = FuncInfo.StaticAllocaMap[Slot];
5147     MFI->setStackProtectorIndex(FI);
5148 
5149     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5150 
5151     // Store the stack protector onto the stack.
5152     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5153                                                  DAG.getMachineFunction(), FI),
5154                        true, false, 0);
5155     setValue(&I, Res);
5156     DAG.setRoot(Res);
5157     return nullptr;
5158   }
5159   case Intrinsic::objectsize: {
5160     // If we don't know by now, we're never going to know.
5161     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5162 
5163     assert(CI && "Non-constant type in __builtin_object_size?");
5164 
5165     SDValue Arg = getValue(I.getCalledValue());
5166     EVT Ty = Arg.getValueType();
5167 
5168     if (CI->isZero())
5169       Res = DAG.getConstant(-1ULL, sdl, Ty);
5170     else
5171       Res = DAG.getConstant(0, sdl, Ty);
5172 
5173     setValue(&I, Res);
5174     return nullptr;
5175   }
5176   case Intrinsic::annotation:
5177   case Intrinsic::ptr_annotation:
5178     // Drop the intrinsic, but forward the value
5179     setValue(&I, getValue(I.getOperand(0)));
5180     return nullptr;
5181   case Intrinsic::assume:
5182   case Intrinsic::var_annotation:
5183     // Discard annotate attributes and assumptions
5184     return nullptr;
5185 
5186   case Intrinsic::init_trampoline: {
5187     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5188 
5189     SDValue Ops[6];
5190     Ops[0] = getRoot();
5191     Ops[1] = getValue(I.getArgOperand(0));
5192     Ops[2] = getValue(I.getArgOperand(1));
5193     Ops[3] = getValue(I.getArgOperand(2));
5194     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5195     Ops[5] = DAG.getSrcValue(F);
5196 
5197     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5198 
5199     DAG.setRoot(Res);
5200     return nullptr;
5201   }
5202   case Intrinsic::adjust_trampoline: {
5203     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5204                              TLI.getPointerTy(DAG.getDataLayout()),
5205                              getValue(I.getArgOperand(0))));
5206     return nullptr;
5207   }
5208   case Intrinsic::gcroot: {
5209     MachineFunction &MF = DAG.getMachineFunction();
5210     const Function *F = MF.getFunction();
5211     (void)F;
5212     assert(F->hasGC() &&
5213            "only valid in functions with gc specified, enforced by Verifier");
5214     assert(GFI && "implied by previous");
5215     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5216     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5217 
5218     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5219     GFI->addStackRoot(FI->getIndex(), TypeMap);
5220     return nullptr;
5221   }
5222   case Intrinsic::gcread:
5223   case Intrinsic::gcwrite:
5224     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5225   case Intrinsic::flt_rounds:
5226     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5227     return nullptr;
5228 
5229   case Intrinsic::expect: {
5230     // Just replace __builtin_expect(exp, c) with EXP.
5231     setValue(&I, getValue(I.getArgOperand(0)));
5232     return nullptr;
5233   }
5234 
5235   case Intrinsic::debugtrap:
5236   case Intrinsic::trap: {
5237     StringRef TrapFuncName =
5238         I.getAttributes()
5239             .getAttribute(AttributeSet::FunctionIndex, "trap-func-name")
5240             .getValueAsString();
5241     if (TrapFuncName.empty()) {
5242       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5243         ISD::TRAP : ISD::DEBUGTRAP;
5244       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5245       return nullptr;
5246     }
5247     TargetLowering::ArgListTy Args;
5248 
5249     TargetLowering::CallLoweringInfo CLI(DAG);
5250     CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee(
5251         CallingConv::C, I.getType(),
5252         DAG.getExternalSymbol(TrapFuncName.data(),
5253                               TLI.getPointerTy(DAG.getDataLayout())),
5254         std::move(Args), 0);
5255 
5256     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5257     DAG.setRoot(Result.second);
5258     return nullptr;
5259   }
5260 
5261   case Intrinsic::uadd_with_overflow:
5262   case Intrinsic::sadd_with_overflow:
5263   case Intrinsic::usub_with_overflow:
5264   case Intrinsic::ssub_with_overflow:
5265   case Intrinsic::umul_with_overflow:
5266   case Intrinsic::smul_with_overflow: {
5267     ISD::NodeType Op;
5268     switch (Intrinsic) {
5269     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5270     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5271     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5272     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5273     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5274     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5275     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5276     }
5277     SDValue Op1 = getValue(I.getArgOperand(0));
5278     SDValue Op2 = getValue(I.getArgOperand(1));
5279 
5280     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5281     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5282     return nullptr;
5283   }
5284   case Intrinsic::prefetch: {
5285     SDValue Ops[5];
5286     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5287     Ops[0] = getRoot();
5288     Ops[1] = getValue(I.getArgOperand(0));
5289     Ops[2] = getValue(I.getArgOperand(1));
5290     Ops[3] = getValue(I.getArgOperand(2));
5291     Ops[4] = getValue(I.getArgOperand(3));
5292     DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5293                                         DAG.getVTList(MVT::Other), Ops,
5294                                         EVT::getIntegerVT(*Context, 8),
5295                                         MachinePointerInfo(I.getArgOperand(0)),
5296                                         0, /* align */
5297                                         false, /* volatile */
5298                                         rw==0, /* read */
5299                                         rw==1)); /* write */
5300     return nullptr;
5301   }
5302   case Intrinsic::lifetime_start:
5303   case Intrinsic::lifetime_end: {
5304     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5305     // Stack coloring is not enabled in O0, discard region information.
5306     if (TM.getOptLevel() == CodeGenOpt::None)
5307       return nullptr;
5308 
5309     SmallVector<Value *, 4> Allocas;
5310     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5311 
5312     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5313            E = Allocas.end(); Object != E; ++Object) {
5314       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5315 
5316       // Could not find an Alloca.
5317       if (!LifetimeObject)
5318         continue;
5319 
5320       // First check that the Alloca is static, otherwise it won't have a
5321       // valid frame index.
5322       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5323       if (SI == FuncInfo.StaticAllocaMap.end())
5324         return nullptr;
5325 
5326       int FI = SI->second;
5327 
5328       SDValue Ops[2];
5329       Ops[0] = getRoot();
5330       Ops[1] =
5331           DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true);
5332       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5333 
5334       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5335       DAG.setRoot(Res);
5336     }
5337     return nullptr;
5338   }
5339   case Intrinsic::invariant_start:
5340     // Discard region information.
5341     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5342     return nullptr;
5343   case Intrinsic::invariant_end:
5344     // Discard region information.
5345     return nullptr;
5346   case Intrinsic::stackprotectorcheck: {
5347     // Do not actually emit anything for this basic block. Instead we initialize
5348     // the stack protector descriptor and export the guard variable so we can
5349     // access it in FinishBasicBlock.
5350     const BasicBlock *BB = I.getParent();
5351     SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5352     ExportFromCurrentBlock(SPDescriptor.getGuard());
5353 
5354     // Flush our exports since we are going to process a terminator.
5355     (void)getControlRoot();
5356     return nullptr;
5357   }
5358   case Intrinsic::clear_cache:
5359     return TLI.getClearCacheBuiltinName();
5360   case Intrinsic::donothing:
5361     // ignore
5362     return nullptr;
5363   case Intrinsic::experimental_stackmap: {
5364     visitStackmap(I);
5365     return nullptr;
5366   }
5367   case Intrinsic::experimental_patchpoint_void:
5368   case Intrinsic::experimental_patchpoint_i64: {
5369     visitPatchpoint(&I);
5370     return nullptr;
5371   }
5372   case Intrinsic::experimental_gc_statepoint: {
5373     visitStatepoint(I);
5374     return nullptr;
5375   }
5376   case Intrinsic::experimental_gc_result: {
5377     visitGCResult(I);
5378     return nullptr;
5379   }
5380   case Intrinsic::experimental_gc_relocate: {
5381     visitGCRelocate(cast<GCRelocateInst>(I));
5382     return nullptr;
5383   }
5384   case Intrinsic::instrprof_increment:
5385     llvm_unreachable("instrprof failed to lower an increment");
5386   case Intrinsic::instrprof_value_profile:
5387     llvm_unreachable("instrprof failed to lower a value profiling call");
5388   case Intrinsic::localescape: {
5389     MachineFunction &MF = DAG.getMachineFunction();
5390     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5391 
5392     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5393     // is the same on all targets.
5394     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5395       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5396       if (isa<ConstantPointerNull>(Arg))
5397         continue; // Skip null pointers. They represent a hole in index space.
5398       AllocaInst *Slot = cast<AllocaInst>(Arg);
5399       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5400              "can only escape static allocas");
5401       int FI = FuncInfo.StaticAllocaMap[Slot];
5402       MCSymbol *FrameAllocSym =
5403           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5404               GlobalValue::getRealLinkageName(MF.getName()), Idx);
5405       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5406               TII->get(TargetOpcode::LOCAL_ESCAPE))
5407           .addSym(FrameAllocSym)
5408           .addFrameIndex(FI);
5409     }
5410 
5411     return nullptr;
5412   }
5413 
5414   case Intrinsic::localrecover: {
5415     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
5416     MachineFunction &MF = DAG.getMachineFunction();
5417     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
5418 
5419     // Get the symbol that defines the frame offset.
5420     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
5421     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
5422     unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
5423     MCSymbol *FrameAllocSym =
5424         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5425             GlobalValue::getRealLinkageName(Fn->getName()), IdxVal);
5426 
5427     // Create a MCSymbol for the label to avoid any target lowering
5428     // that would make this PC relative.
5429     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
5430     SDValue OffsetVal =
5431         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
5432 
5433     // Add the offset to the FP.
5434     Value *FP = I.getArgOperand(1);
5435     SDValue FPVal = getValue(FP);
5436     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
5437     setValue(&I, Add);
5438 
5439     return nullptr;
5440   }
5441 
5442   case Intrinsic::eh_exceptionpointer:
5443   case Intrinsic::eh_exceptioncode: {
5444     // Get the exception pointer vreg, copy from it, and resize it to fit.
5445     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
5446     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
5447     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
5448     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
5449     SDValue N =
5450         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
5451     if (Intrinsic == Intrinsic::eh_exceptioncode)
5452       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
5453     setValue(&I, N);
5454     return nullptr;
5455   }
5456   }
5457 }
5458 
5459 std::pair<SDValue, SDValue>
5460 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5461                                     const BasicBlock *EHPadBB) {
5462   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5463   MCSymbol *BeginLabel = nullptr;
5464 
5465   if (EHPadBB) {
5466     // Insert a label before the invoke call to mark the try range.  This can be
5467     // used to detect deletion of the invoke via the MachineModuleInfo.
5468     BeginLabel = MMI.getContext().createTempSymbol();
5469 
5470     // For SjLj, keep track of which landing pads go with which invokes
5471     // so as to maintain the ordering of pads in the LSDA.
5472     unsigned CallSiteIndex = MMI.getCurrentCallSite();
5473     if (CallSiteIndex) {
5474       MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5475       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
5476 
5477       // Now that the call site is handled, stop tracking it.
5478       MMI.setCurrentCallSite(0);
5479     }
5480 
5481     // Both PendingLoads and PendingExports must be flushed here;
5482     // this call might not return.
5483     (void)getRoot();
5484     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5485 
5486     CLI.setChain(getRoot());
5487   }
5488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5489   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5490 
5491   assert((CLI.IsTailCall || Result.second.getNode()) &&
5492          "Non-null chain expected with non-tail call!");
5493   assert((Result.second.getNode() || !Result.first.getNode()) &&
5494          "Null value expected with tail call!");
5495 
5496   if (!Result.second.getNode()) {
5497     // As a special case, a null chain means that a tail call has been emitted
5498     // and the DAG root is already updated.
5499     HasTailCall = true;
5500 
5501     // Since there's no actual continuation from this block, nothing can be
5502     // relying on us setting vregs for them.
5503     PendingExports.clear();
5504   } else {
5505     DAG.setRoot(Result.second);
5506   }
5507 
5508   if (EHPadBB) {
5509     // Insert a label at the end of the invoke call to mark the try range.  This
5510     // can be used to detect deletion of the invoke via the MachineModuleInfo.
5511     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
5512     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5513 
5514     // Inform MachineModuleInfo of range.
5515     if (MMI.hasEHFunclets()) {
5516       assert(CLI.CS);
5517       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
5518       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS->getInstruction()),
5519                                 BeginLabel, EndLabel);
5520     } else {
5521       MMI.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
5522     }
5523   }
5524 
5525   return Result;
5526 }
5527 
5528 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5529                                       bool isTailCall,
5530                                       const BasicBlock *EHPadBB) {
5531   FunctionType *FTy = CS.getFunctionType();
5532   Type *RetTy = CS.getType();
5533 
5534   TargetLowering::ArgListTy Args;
5535   TargetLowering::ArgListEntry Entry;
5536   Args.reserve(CS.arg_size());
5537 
5538   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5539        i != e; ++i) {
5540     const Value *V = *i;
5541 
5542     // Skip empty types
5543     if (V->getType()->isEmptyTy())
5544       continue;
5545 
5546     SDValue ArgNode = getValue(V);
5547     Entry.Node = ArgNode; Entry.Ty = V->getType();
5548 
5549     // Skip the first return-type Attribute to get to params.
5550     Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5551     Args.push_back(Entry);
5552 
5553     // If we have an explicit sret argument that is an Instruction, (i.e., it
5554     // might point to function-local memory), we can't meaningfully tail-call.
5555     if (Entry.isSRet && isa<Instruction>(V))
5556       isTailCall = false;
5557   }
5558 
5559   // Check if target-independent constraints permit a tail call here.
5560   // Target-dependent constraints are checked within TLI->LowerCallTo.
5561   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5562     isTailCall = false;
5563 
5564   TargetLowering::CallLoweringInfo CLI(DAG);
5565   CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
5566     .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5567     .setTailCall(isTailCall);
5568   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
5569 
5570   if (Result.first.getNode()) {
5571     const Instruction *Inst = CS.getInstruction();
5572     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
5573     setValue(Inst, Result.first);
5574   }
5575 }
5576 
5577 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5578 /// value is equal or not-equal to zero.
5579 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5580   for (const User *U : V->users()) {
5581     if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5582       if (IC->isEquality())
5583         if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5584           if (C->isNullValue())
5585             continue;
5586     // Unknown instruction.
5587     return false;
5588   }
5589   return true;
5590 }
5591 
5592 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5593                              Type *LoadTy,
5594                              SelectionDAGBuilder &Builder) {
5595 
5596   // Check to see if this load can be trivially constant folded, e.g. if the
5597   // input is from a string literal.
5598   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5599     // Cast pointer to the type we really want to load.
5600     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5601                                          PointerType::getUnqual(LoadTy));
5602 
5603     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
5604             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
5605       return Builder.getValue(LoadCst);
5606   }
5607 
5608   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
5609   // still constant memory, the input chain can be the entry node.
5610   SDValue Root;
5611   bool ConstantMemory = false;
5612 
5613   // Do not serialize (non-volatile) loads of constant memory with anything.
5614   if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5615     Root = Builder.DAG.getEntryNode();
5616     ConstantMemory = true;
5617   } else {
5618     // Do not serialize non-volatile loads against each other.
5619     Root = Builder.DAG.getRoot();
5620   }
5621 
5622   SDValue Ptr = Builder.getValue(PtrVal);
5623   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5624                                         Ptr, MachinePointerInfo(PtrVal),
5625                                         false /*volatile*/,
5626                                         false /*nontemporal*/,
5627                                         false /*isinvariant*/, 1 /* align=1 */);
5628 
5629   if (!ConstantMemory)
5630     Builder.PendingLoads.push_back(LoadVal.getValue(1));
5631   return LoadVal;
5632 }
5633 
5634 /// processIntegerCallValue - Record the value for an instruction that
5635 /// produces an integer result, converting the type where necessary.
5636 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5637                                                   SDValue Value,
5638                                                   bool IsSigned) {
5639   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5640                                                     I.getType(), true);
5641   if (IsSigned)
5642     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5643   else
5644     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5645   setValue(&I, Value);
5646 }
5647 
5648 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5649 /// If so, return true and lower it, otherwise return false and it will be
5650 /// lowered like a normal call.
5651 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5652   // Verify that the prototype makes sense.  int memcmp(void*,void*,size_t)
5653   if (I.getNumArgOperands() != 3)
5654     return false;
5655 
5656   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5657   if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5658       !I.getArgOperand(2)->getType()->isIntegerTy() ||
5659       !I.getType()->isIntegerTy())
5660     return false;
5661 
5662   const Value *Size = I.getArgOperand(2);
5663   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5664   if (CSize && CSize->getZExtValue() == 0) {
5665     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5666                                                           I.getType(), true);
5667     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
5668     return true;
5669   }
5670 
5671   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5672   std::pair<SDValue, SDValue> Res =
5673     TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5674                                 getValue(LHS), getValue(RHS), getValue(Size),
5675                                 MachinePointerInfo(LHS),
5676                                 MachinePointerInfo(RHS));
5677   if (Res.first.getNode()) {
5678     processIntegerCallValue(I, Res.first, true);
5679     PendingLoads.push_back(Res.second);
5680     return true;
5681   }
5682 
5683   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
5684   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
5685   if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5686     bool ActuallyDoIt = true;
5687     MVT LoadVT;
5688     Type *LoadTy;
5689     switch (CSize->getZExtValue()) {
5690     default:
5691       LoadVT = MVT::Other;
5692       LoadTy = nullptr;
5693       ActuallyDoIt = false;
5694       break;
5695     case 2:
5696       LoadVT = MVT::i16;
5697       LoadTy = Type::getInt16Ty(CSize->getContext());
5698       break;
5699     case 4:
5700       LoadVT = MVT::i32;
5701       LoadTy = Type::getInt32Ty(CSize->getContext());
5702       break;
5703     case 8:
5704       LoadVT = MVT::i64;
5705       LoadTy = Type::getInt64Ty(CSize->getContext());
5706       break;
5707         /*
5708     case 16:
5709       LoadVT = MVT::v4i32;
5710       LoadTy = Type::getInt32Ty(CSize->getContext());
5711       LoadTy = VectorType::get(LoadTy, 4);
5712       break;
5713          */
5714     }
5715 
5716     // This turns into unaligned loads.  We only do this if the target natively
5717     // supports the MVT we'll be loading or if it is small enough (<= 4) that
5718     // we'll only produce a small number of byte loads.
5719 
5720     // Require that we can find a legal MVT, and only do this if the target
5721     // supports unaligned loads of that type.  Expanding into byte loads would
5722     // bloat the code.
5723     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5724     if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5725       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5726       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5727       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5728       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5729       // TODO: Check alignment of src and dest ptrs.
5730       if (!TLI.isTypeLegal(LoadVT) ||
5731           !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5732           !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
5733         ActuallyDoIt = false;
5734     }
5735 
5736     if (ActuallyDoIt) {
5737       SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5738       SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5739 
5740       SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5741                                  ISD::SETNE);
5742       processIntegerCallValue(I, Res, false);
5743       return true;
5744     }
5745   }
5746 
5747 
5748   return false;
5749 }
5750 
5751 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5752 /// form.  If so, return true and lower it, otherwise return false and it
5753 /// will be lowered like a normal call.
5754 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5755   // Verify that the prototype makes sense.  void *memchr(void *, int, size_t)
5756   if (I.getNumArgOperands() != 3)
5757     return false;
5758 
5759   const Value *Src = I.getArgOperand(0);
5760   const Value *Char = I.getArgOperand(1);
5761   const Value *Length = I.getArgOperand(2);
5762   if (!Src->getType()->isPointerTy() ||
5763       !Char->getType()->isIntegerTy() ||
5764       !Length->getType()->isIntegerTy() ||
5765       !I.getType()->isPointerTy())
5766     return false;
5767 
5768   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5769   std::pair<SDValue, SDValue> Res =
5770     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5771                                 getValue(Src), getValue(Char), getValue(Length),
5772                                 MachinePointerInfo(Src));
5773   if (Res.first.getNode()) {
5774     setValue(&I, Res.first);
5775     PendingLoads.push_back(Res.second);
5776     return true;
5777   }
5778 
5779   return false;
5780 }
5781 
5782 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5783 /// optimized form.  If so, return true and lower it, otherwise return false
5784 /// and it will be lowered like a normal call.
5785 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5786   // Verify that the prototype makes sense.  char *strcpy(char *, char *)
5787   if (I.getNumArgOperands() != 2)
5788     return false;
5789 
5790   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5791   if (!Arg0->getType()->isPointerTy() ||
5792       !Arg1->getType()->isPointerTy() ||
5793       !I.getType()->isPointerTy())
5794     return false;
5795 
5796   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5797   std::pair<SDValue, SDValue> Res =
5798     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5799                                 getValue(Arg0), getValue(Arg1),
5800                                 MachinePointerInfo(Arg0),
5801                                 MachinePointerInfo(Arg1), isStpcpy);
5802   if (Res.first.getNode()) {
5803     setValue(&I, Res.first);
5804     DAG.setRoot(Res.second);
5805     return true;
5806   }
5807 
5808   return false;
5809 }
5810 
5811 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5812 /// If so, return true and lower it, otherwise return false and it will be
5813 /// lowered like a normal call.
5814 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5815   // Verify that the prototype makes sense.  int strcmp(void*,void*)
5816   if (I.getNumArgOperands() != 2)
5817     return false;
5818 
5819   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5820   if (!Arg0->getType()->isPointerTy() ||
5821       !Arg1->getType()->isPointerTy() ||
5822       !I.getType()->isIntegerTy())
5823     return false;
5824 
5825   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5826   std::pair<SDValue, SDValue> Res =
5827     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5828                                 getValue(Arg0), getValue(Arg1),
5829                                 MachinePointerInfo(Arg0),
5830                                 MachinePointerInfo(Arg1));
5831   if (Res.first.getNode()) {
5832     processIntegerCallValue(I, Res.first, true);
5833     PendingLoads.push_back(Res.second);
5834     return true;
5835   }
5836 
5837   return false;
5838 }
5839 
5840 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5841 /// form.  If so, return true and lower it, otherwise return false and it
5842 /// will be lowered like a normal call.
5843 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5844   // Verify that the prototype makes sense.  size_t strlen(char *)
5845   if (I.getNumArgOperands() != 1)
5846     return false;
5847 
5848   const Value *Arg0 = I.getArgOperand(0);
5849   if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5850     return false;
5851 
5852   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5853   std::pair<SDValue, SDValue> Res =
5854     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5855                                 getValue(Arg0), MachinePointerInfo(Arg0));
5856   if (Res.first.getNode()) {
5857     processIntegerCallValue(I, Res.first, false);
5858     PendingLoads.push_back(Res.second);
5859     return true;
5860   }
5861 
5862   return false;
5863 }
5864 
5865 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5866 /// form.  If so, return true and lower it, otherwise return false and it
5867 /// will be lowered like a normal call.
5868 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5869   // Verify that the prototype makes sense.  size_t strnlen(char *, size_t)
5870   if (I.getNumArgOperands() != 2)
5871     return false;
5872 
5873   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5874   if (!Arg0->getType()->isPointerTy() ||
5875       !Arg1->getType()->isIntegerTy() ||
5876       !I.getType()->isIntegerTy())
5877     return false;
5878 
5879   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5880   std::pair<SDValue, SDValue> Res =
5881     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5882                                  getValue(Arg0), getValue(Arg1),
5883                                  MachinePointerInfo(Arg0));
5884   if (Res.first.getNode()) {
5885     processIntegerCallValue(I, Res.first, false);
5886     PendingLoads.push_back(Res.second);
5887     return true;
5888   }
5889 
5890   return false;
5891 }
5892 
5893 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5894 /// operation (as expected), translate it to an SDNode with the specified opcode
5895 /// and return true.
5896 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5897                                               unsigned Opcode) {
5898   // Sanity check that it really is a unary floating-point call.
5899   if (I.getNumArgOperands() != 1 ||
5900       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5901       I.getType() != I.getArgOperand(0)->getType() ||
5902       !I.onlyReadsMemory())
5903     return false;
5904 
5905   SDValue Tmp = getValue(I.getArgOperand(0));
5906   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5907   return true;
5908 }
5909 
5910 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
5911 /// operation (as expected), translate it to an SDNode with the specified opcode
5912 /// and return true.
5913 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
5914                                                unsigned Opcode) {
5915   // Sanity check that it really is a binary floating-point call.
5916   if (I.getNumArgOperands() != 2 ||
5917       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5918       I.getType() != I.getArgOperand(0)->getType() ||
5919       I.getType() != I.getArgOperand(1)->getType() ||
5920       !I.onlyReadsMemory())
5921     return false;
5922 
5923   SDValue Tmp0 = getValue(I.getArgOperand(0));
5924   SDValue Tmp1 = getValue(I.getArgOperand(1));
5925   EVT VT = Tmp0.getValueType();
5926   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
5927   return true;
5928 }
5929 
5930 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5931   // Handle inline assembly differently.
5932   if (isa<InlineAsm>(I.getCalledValue())) {
5933     visitInlineAsm(&I);
5934     return;
5935   }
5936 
5937   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5938   ComputeUsesVAFloatArgument(I, &MMI);
5939 
5940   const char *RenameFn = nullptr;
5941   if (Function *F = I.getCalledFunction()) {
5942     if (F->isDeclaration()) {
5943       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5944         if (unsigned IID = II->getIntrinsicID(F)) {
5945           RenameFn = visitIntrinsicCall(I, IID);
5946           if (!RenameFn)
5947             return;
5948         }
5949       }
5950       if (Intrinsic::ID IID = F->getIntrinsicID()) {
5951         RenameFn = visitIntrinsicCall(I, IID);
5952         if (!RenameFn)
5953           return;
5954       }
5955     }
5956 
5957     // Check for well-known libc/libm calls.  If the function is internal, it
5958     // can't be a library call.
5959     LibFunc::Func Func;
5960     if (!F->hasLocalLinkage() && F->hasName() &&
5961         LibInfo->getLibFunc(F->getName(), Func) &&
5962         LibInfo->hasOptimizedCodeGen(Func)) {
5963       switch (Func) {
5964       default: break;
5965       case LibFunc::copysign:
5966       case LibFunc::copysignf:
5967       case LibFunc::copysignl:
5968         if (I.getNumArgOperands() == 2 &&   // Basic sanity checks.
5969             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5970             I.getType() == I.getArgOperand(0)->getType() &&
5971             I.getType() == I.getArgOperand(1)->getType() &&
5972             I.onlyReadsMemory()) {
5973           SDValue LHS = getValue(I.getArgOperand(0));
5974           SDValue RHS = getValue(I.getArgOperand(1));
5975           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5976                                    LHS.getValueType(), LHS, RHS));
5977           return;
5978         }
5979         break;
5980       case LibFunc::fabs:
5981       case LibFunc::fabsf:
5982       case LibFunc::fabsl:
5983         if (visitUnaryFloatCall(I, ISD::FABS))
5984           return;
5985         break;
5986       case LibFunc::fmin:
5987       case LibFunc::fminf:
5988       case LibFunc::fminl:
5989         if (visitBinaryFloatCall(I, ISD::FMINNUM))
5990           return;
5991         break;
5992       case LibFunc::fmax:
5993       case LibFunc::fmaxf:
5994       case LibFunc::fmaxl:
5995         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
5996           return;
5997         break;
5998       case LibFunc::sin:
5999       case LibFunc::sinf:
6000       case LibFunc::sinl:
6001         if (visitUnaryFloatCall(I, ISD::FSIN))
6002           return;
6003         break;
6004       case LibFunc::cos:
6005       case LibFunc::cosf:
6006       case LibFunc::cosl:
6007         if (visitUnaryFloatCall(I, ISD::FCOS))
6008           return;
6009         break;
6010       case LibFunc::sqrt:
6011       case LibFunc::sqrtf:
6012       case LibFunc::sqrtl:
6013       case LibFunc::sqrt_finite:
6014       case LibFunc::sqrtf_finite:
6015       case LibFunc::sqrtl_finite:
6016         if (visitUnaryFloatCall(I, ISD::FSQRT))
6017           return;
6018         break;
6019       case LibFunc::floor:
6020       case LibFunc::floorf:
6021       case LibFunc::floorl:
6022         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6023           return;
6024         break;
6025       case LibFunc::nearbyint:
6026       case LibFunc::nearbyintf:
6027       case LibFunc::nearbyintl:
6028         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6029           return;
6030         break;
6031       case LibFunc::ceil:
6032       case LibFunc::ceilf:
6033       case LibFunc::ceill:
6034         if (visitUnaryFloatCall(I, ISD::FCEIL))
6035           return;
6036         break;
6037       case LibFunc::rint:
6038       case LibFunc::rintf:
6039       case LibFunc::rintl:
6040         if (visitUnaryFloatCall(I, ISD::FRINT))
6041           return;
6042         break;
6043       case LibFunc::round:
6044       case LibFunc::roundf:
6045       case LibFunc::roundl:
6046         if (visitUnaryFloatCall(I, ISD::FROUND))
6047           return;
6048         break;
6049       case LibFunc::trunc:
6050       case LibFunc::truncf:
6051       case LibFunc::truncl:
6052         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6053           return;
6054         break;
6055       case LibFunc::log2:
6056       case LibFunc::log2f:
6057       case LibFunc::log2l:
6058         if (visitUnaryFloatCall(I, ISD::FLOG2))
6059           return;
6060         break;
6061       case LibFunc::exp2:
6062       case LibFunc::exp2f:
6063       case LibFunc::exp2l:
6064         if (visitUnaryFloatCall(I, ISD::FEXP2))
6065           return;
6066         break;
6067       case LibFunc::memcmp:
6068         if (visitMemCmpCall(I))
6069           return;
6070         break;
6071       case LibFunc::memchr:
6072         if (visitMemChrCall(I))
6073           return;
6074         break;
6075       case LibFunc::strcpy:
6076         if (visitStrCpyCall(I, false))
6077           return;
6078         break;
6079       case LibFunc::stpcpy:
6080         if (visitStrCpyCall(I, true))
6081           return;
6082         break;
6083       case LibFunc::strcmp:
6084         if (visitStrCmpCall(I))
6085           return;
6086         break;
6087       case LibFunc::strlen:
6088         if (visitStrLenCall(I))
6089           return;
6090         break;
6091       case LibFunc::strnlen:
6092         if (visitStrNLenCall(I))
6093           return;
6094         break;
6095       }
6096     }
6097   }
6098 
6099   SDValue Callee;
6100   if (!RenameFn)
6101     Callee = getValue(I.getCalledValue());
6102   else
6103     Callee = DAG.getExternalSymbol(
6104         RenameFn,
6105         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6106 
6107   // Check if we can potentially perform a tail call. More detailed checking is
6108   // be done within LowerCallTo, after more information about the call is known.
6109   LowerCallTo(&I, Callee, I.isTailCall());
6110 }
6111 
6112 namespace {
6113 
6114 /// AsmOperandInfo - This contains information for each constraint that we are
6115 /// lowering.
6116 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6117 public:
6118   /// CallOperand - If this is the result output operand or a clobber
6119   /// this is null, otherwise it is the incoming operand to the CallInst.
6120   /// This gets modified as the asm is processed.
6121   SDValue CallOperand;
6122 
6123   /// AssignedRegs - If this is a register or register class operand, this
6124   /// contains the set of register corresponding to the operand.
6125   RegsForValue AssignedRegs;
6126 
6127   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6128     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
6129   }
6130 
6131   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6132   /// corresponds to.  If there is no Value* for this operand, it returns
6133   /// MVT::Other.
6134   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
6135                            const DataLayout &DL) const {
6136     if (!CallOperandVal) return MVT::Other;
6137 
6138     if (isa<BasicBlock>(CallOperandVal))
6139       return TLI.getPointerTy(DL);
6140 
6141     llvm::Type *OpTy = CallOperandVal->getType();
6142 
6143     // FIXME: code duplicated from TargetLowering::ParseConstraints().
6144     // If this is an indirect operand, the operand is a pointer to the
6145     // accessed type.
6146     if (isIndirect) {
6147       llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6148       if (!PtrTy)
6149         report_fatal_error("Indirect operand for inline asm not a pointer!");
6150       OpTy = PtrTy->getElementType();
6151     }
6152 
6153     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6154     if (StructType *STy = dyn_cast<StructType>(OpTy))
6155       if (STy->getNumElements() == 1)
6156         OpTy = STy->getElementType(0);
6157 
6158     // If OpTy is not a single value, it may be a struct/union that we
6159     // can tile with integers.
6160     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6161       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6162       switch (BitSize) {
6163       default: break;
6164       case 1:
6165       case 8:
6166       case 16:
6167       case 32:
6168       case 64:
6169       case 128:
6170         OpTy = IntegerType::get(Context, BitSize);
6171         break;
6172       }
6173     }
6174 
6175     return TLI.getValueType(DL, OpTy, true);
6176   }
6177 };
6178 
6179 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6180 
6181 } // end anonymous namespace
6182 
6183 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6184 /// specified operand.  We prefer to assign virtual registers, to allow the
6185 /// register allocator to handle the assignment process.  However, if the asm
6186 /// uses features that we can't model on machineinstrs, we have SDISel do the
6187 /// allocation.  This produces generally horrible, but correct, code.
6188 ///
6189 ///   OpInfo describes the operand.
6190 ///
6191 static void GetRegistersForValue(SelectionDAG &DAG,
6192                                  const TargetLowering &TLI,
6193                                  SDLoc DL,
6194                                  SDISelAsmOperandInfo &OpInfo) {
6195   LLVMContext &Context = *DAG.getContext();
6196 
6197   MachineFunction &MF = DAG.getMachineFunction();
6198   SmallVector<unsigned, 4> Regs;
6199 
6200   // If this is a constraint for a single physreg, or a constraint for a
6201   // register class, find it.
6202   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
6203       TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
6204                                        OpInfo.ConstraintCode,
6205                                        OpInfo.ConstraintVT);
6206 
6207   unsigned NumRegs = 1;
6208   if (OpInfo.ConstraintVT != MVT::Other) {
6209     // If this is a FP input in an integer register (or visa versa) insert a bit
6210     // cast of the input value.  More generally, handle any case where the input
6211     // value disagrees with the register class we plan to stick this in.
6212     if (OpInfo.Type == InlineAsm::isInput &&
6213         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6214       // Try to convert to the first EVT that the reg class contains.  If the
6215       // types are identical size, use a bitcast to convert (e.g. two differing
6216       // vector types).
6217       MVT RegVT = *PhysReg.second->vt_begin();
6218       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6219         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6220                                          RegVT, OpInfo.CallOperand);
6221         OpInfo.ConstraintVT = RegVT;
6222       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6223         // If the input is a FP value and we want it in FP registers, do a
6224         // bitcast to the corresponding integer type.  This turns an f64 value
6225         // into i64, which can be passed with two i32 values on a 32-bit
6226         // machine.
6227         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6228         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6229                                          RegVT, OpInfo.CallOperand);
6230         OpInfo.ConstraintVT = RegVT;
6231       }
6232     }
6233 
6234     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6235   }
6236 
6237   MVT RegVT;
6238   EVT ValueVT = OpInfo.ConstraintVT;
6239 
6240   // If this is a constraint for a specific physical register, like {r17},
6241   // assign it now.
6242   if (unsigned AssignedReg = PhysReg.first) {
6243     const TargetRegisterClass *RC = PhysReg.second;
6244     if (OpInfo.ConstraintVT == MVT::Other)
6245       ValueVT = *RC->vt_begin();
6246 
6247     // Get the actual register value type.  This is important, because the user
6248     // may have asked for (e.g.) the AX register in i32 type.  We need to
6249     // remember that AX is actually i16 to get the right extension.
6250     RegVT = *RC->vt_begin();
6251 
6252     // This is a explicit reference to a physical register.
6253     Regs.push_back(AssignedReg);
6254 
6255     // If this is an expanded reference, add the rest of the regs to Regs.
6256     if (NumRegs != 1) {
6257       TargetRegisterClass::iterator I = RC->begin();
6258       for (; *I != AssignedReg; ++I)
6259         assert(I != RC->end() && "Didn't find reg!");
6260 
6261       // Already added the first reg.
6262       --NumRegs; ++I;
6263       for (; NumRegs; --NumRegs, ++I) {
6264         assert(I != RC->end() && "Ran out of registers to allocate!");
6265         Regs.push_back(*I);
6266       }
6267     }
6268 
6269     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6270     return;
6271   }
6272 
6273   // Otherwise, if this was a reference to an LLVM register class, create vregs
6274   // for this reference.
6275   if (const TargetRegisterClass *RC = PhysReg.second) {
6276     RegVT = *RC->vt_begin();
6277     if (OpInfo.ConstraintVT == MVT::Other)
6278       ValueVT = RegVT;
6279 
6280     // Create the appropriate number of virtual registers.
6281     MachineRegisterInfo &RegInfo = MF.getRegInfo();
6282     for (; NumRegs; --NumRegs)
6283       Regs.push_back(RegInfo.createVirtualRegister(RC));
6284 
6285     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6286     return;
6287   }
6288 
6289   // Otherwise, we couldn't allocate enough registers for this.
6290 }
6291 
6292 /// visitInlineAsm - Handle a call to an InlineAsm object.
6293 ///
6294 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6295   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6296 
6297   /// ConstraintOperands - Information about all of the constraints.
6298   SDISelAsmOperandInfoVector ConstraintOperands;
6299 
6300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6301   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
6302       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
6303 
6304   bool hasMemory = false;
6305 
6306   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
6307   unsigned ResNo = 0;   // ResNo - The result number of the next output.
6308   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6309     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6310     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6311 
6312     MVT OpVT = MVT::Other;
6313 
6314     // Compute the value type for each operand.
6315     switch (OpInfo.Type) {
6316     case InlineAsm::isOutput:
6317       // Indirect outputs just consume an argument.
6318       if (OpInfo.isIndirect) {
6319         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6320         break;
6321       }
6322 
6323       // The return value of the call is this value.  As such, there is no
6324       // corresponding argument.
6325       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6326       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6327         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
6328                                       STy->getElementType(ResNo));
6329       } else {
6330         assert(ResNo == 0 && "Asm only has one result!");
6331         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
6332       }
6333       ++ResNo;
6334       break;
6335     case InlineAsm::isInput:
6336       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6337       break;
6338     case InlineAsm::isClobber:
6339       // Nothing to do.
6340       break;
6341     }
6342 
6343     // If this is an input or an indirect output, process the call argument.
6344     // BasicBlocks are labels, currently appearing only in asm's.
6345     if (OpInfo.CallOperandVal) {
6346       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6347         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6348       } else {
6349         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6350       }
6351 
6352       OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
6353                                          DAG.getDataLayout()).getSimpleVT();
6354     }
6355 
6356     OpInfo.ConstraintVT = OpVT;
6357 
6358     // Indirect operand accesses access memory.
6359     if (OpInfo.isIndirect)
6360       hasMemory = true;
6361     else {
6362       for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6363         TargetLowering::ConstraintType
6364           CType = TLI.getConstraintType(OpInfo.Codes[j]);
6365         if (CType == TargetLowering::C_Memory) {
6366           hasMemory = true;
6367           break;
6368         }
6369       }
6370     }
6371   }
6372 
6373   SDValue Chain, Flag;
6374 
6375   // We won't need to flush pending loads if this asm doesn't touch
6376   // memory and is nonvolatile.
6377   if (hasMemory || IA->hasSideEffects())
6378     Chain = getRoot();
6379   else
6380     Chain = DAG.getRoot();
6381 
6382   // Second pass over the constraints: compute which constraint option to use
6383   // and assign registers to constraints that want a specific physreg.
6384   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6385     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6386 
6387     // If this is an output operand with a matching input operand, look up the
6388     // matching input. If their types mismatch, e.g. one is an integer, the
6389     // other is floating point, or their sizes are different, flag it as an
6390     // error.
6391     if (OpInfo.hasMatchingInput()) {
6392       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6393 
6394       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6395         const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
6396         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6397             TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6398                                              OpInfo.ConstraintVT);
6399         std::pair<unsigned, const TargetRegisterClass *> InputRC =
6400             TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6401                                              Input.ConstraintVT);
6402         if ((OpInfo.ConstraintVT.isInteger() !=
6403              Input.ConstraintVT.isInteger()) ||
6404             (MatchRC.second != InputRC.second)) {
6405           report_fatal_error("Unsupported asm: input constraint"
6406                              " with a matching output constraint of"
6407                              " incompatible type!");
6408         }
6409         Input.ConstraintVT = OpInfo.ConstraintVT;
6410       }
6411     }
6412 
6413     // Compute the constraint code and ConstraintType to use.
6414     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6415 
6416     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6417         OpInfo.Type == InlineAsm::isClobber)
6418       continue;
6419 
6420     // If this is a memory input, and if the operand is not indirect, do what we
6421     // need to to provide an address for the memory input.
6422     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6423         !OpInfo.isIndirect) {
6424       assert((OpInfo.isMultipleAlternative ||
6425               (OpInfo.Type == InlineAsm::isInput)) &&
6426              "Can only indirectify direct input operands!");
6427 
6428       // Memory operands really want the address of the value.  If we don't have
6429       // an indirect input, put it in the constpool if we can, otherwise spill
6430       // it to a stack slot.
6431       // TODO: This isn't quite right. We need to handle these according to
6432       // the addressing mode that the constraint wants. Also, this may take
6433       // an additional register for the computation and we don't want that
6434       // either.
6435 
6436       // If the operand is a float, integer, or vector constant, spill to a
6437       // constant pool entry to get its address.
6438       const Value *OpVal = OpInfo.CallOperandVal;
6439       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6440           isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6441         OpInfo.CallOperand = DAG.getConstantPool(
6442             cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
6443       } else {
6444         // Otherwise, create a stack slot and emit a store to it before the
6445         // asm.
6446         Type *Ty = OpVal->getType();
6447         auto &DL = DAG.getDataLayout();
6448         uint64_t TySize = DL.getTypeAllocSize(Ty);
6449         unsigned Align = DL.getPrefTypeAlignment(Ty);
6450         MachineFunction &MF = DAG.getMachineFunction();
6451         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6452         SDValue StackSlot =
6453             DAG.getFrameIndex(SSFI, TLI.getPointerTy(DAG.getDataLayout()));
6454         Chain = DAG.getStore(
6455             Chain, getCurSDLoc(), OpInfo.CallOperand, StackSlot,
6456             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
6457             false, false, 0);
6458         OpInfo.CallOperand = StackSlot;
6459       }
6460 
6461       // There is no longer a Value* corresponding to this operand.
6462       OpInfo.CallOperandVal = nullptr;
6463 
6464       // It is now an indirect operand.
6465       OpInfo.isIndirect = true;
6466     }
6467 
6468     // If this constraint is for a specific register, allocate it before
6469     // anything else.
6470     if (OpInfo.ConstraintType == TargetLowering::C_Register)
6471       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6472   }
6473 
6474   // Second pass - Loop over all of the operands, assigning virtual or physregs
6475   // to register class operands.
6476   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6477     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6478 
6479     // C_Register operands have already been allocated, Other/Memory don't need
6480     // to be.
6481     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6482       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6483   }
6484 
6485   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6486   std::vector<SDValue> AsmNodeOperands;
6487   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
6488   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
6489       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
6490 
6491   // If we have a !srcloc metadata node associated with it, we want to attach
6492   // this to the ultimately generated inline asm machineinstr.  To do this, we
6493   // pass in the third operand as this (potentially null) inline asm MDNode.
6494   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6495   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6496 
6497   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6498   // bits as operand 3.
6499   unsigned ExtraInfo = 0;
6500   if (IA->hasSideEffects())
6501     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6502   if (IA->isAlignStack())
6503     ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6504   // Set the asm dialect.
6505   ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6506 
6507   // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6508   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6509     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6510 
6511     // Compute the constraint code and ConstraintType to use.
6512     TLI.ComputeConstraintToUse(OpInfo, SDValue());
6513 
6514     // Ideally, we would only check against memory constraints.  However, the
6515     // meaning of an other constraint can be target-specific and we can't easily
6516     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
6517     // for other constriants as well.
6518     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6519         OpInfo.ConstraintType == TargetLowering::C_Other) {
6520       if (OpInfo.Type == InlineAsm::isInput)
6521         ExtraInfo |= InlineAsm::Extra_MayLoad;
6522       else if (OpInfo.Type == InlineAsm::isOutput)
6523         ExtraInfo |= InlineAsm::Extra_MayStore;
6524       else if (OpInfo.Type == InlineAsm::isClobber)
6525         ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6526     }
6527   }
6528 
6529   AsmNodeOperands.push_back(DAG.getTargetConstant(
6530       ExtraInfo, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6531 
6532   // Loop over all of the inputs, copying the operand values into the
6533   // appropriate registers and processing the output regs.
6534   RegsForValue RetValRegs;
6535 
6536   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6537   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6538 
6539   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6540     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6541 
6542     switch (OpInfo.Type) {
6543     case InlineAsm::isOutput: {
6544       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6545           OpInfo.ConstraintType != TargetLowering::C_Register) {
6546         // Memory output, or 'other' output (e.g. 'X' constraint).
6547         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6548 
6549         unsigned ConstraintID =
6550             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6551         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6552                "Failed to convert memory constraint code to constraint id.");
6553 
6554         // Add information to the INLINEASM node to know about this output.
6555         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6556         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
6557         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
6558                                                         MVT::i32));
6559         AsmNodeOperands.push_back(OpInfo.CallOperand);
6560         break;
6561       }
6562 
6563       // Otherwise, this is a register or register class output.
6564 
6565       // Copy the output from the appropriate register.  Find a register that
6566       // we can use.
6567       if (OpInfo.AssignedRegs.Regs.empty()) {
6568         LLVMContext &Ctx = *DAG.getContext();
6569         Ctx.emitError(CS.getInstruction(),
6570                       "couldn't allocate output register for constraint '" +
6571                           Twine(OpInfo.ConstraintCode) + "'");
6572         return;
6573       }
6574 
6575       // If this is an indirect operand, store through the pointer after the
6576       // asm.
6577       if (OpInfo.isIndirect) {
6578         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6579                                                       OpInfo.CallOperandVal));
6580       } else {
6581         // This is the result value of the call.
6582         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6583         // Concatenate this output onto the outputs list.
6584         RetValRegs.append(OpInfo.AssignedRegs);
6585       }
6586 
6587       // Add information to the INLINEASM node to know that this register is
6588       // set.
6589       OpInfo.AssignedRegs
6590           .AddInlineAsmOperands(OpInfo.isEarlyClobber
6591                                     ? InlineAsm::Kind_RegDefEarlyClobber
6592                                     : InlineAsm::Kind_RegDef,
6593                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
6594       break;
6595     }
6596     case InlineAsm::isInput: {
6597       SDValue InOperandVal = OpInfo.CallOperand;
6598 
6599       if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
6600         // If this is required to match an output register we have already set,
6601         // just use its register.
6602         unsigned OperandNo = OpInfo.getMatchedOperand();
6603 
6604         // Scan until we find the definition we already emitted of this operand.
6605         // When we find it, create a RegsForValue operand.
6606         unsigned CurOp = InlineAsm::Op_FirstOperand;
6607         for (; OperandNo; --OperandNo) {
6608           // Advance to the next operand.
6609           unsigned OpFlag =
6610             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6611           assert((InlineAsm::isRegDefKind(OpFlag) ||
6612                   InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6613                   InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6614           CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6615         }
6616 
6617         unsigned OpFlag =
6618           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6619         if (InlineAsm::isRegDefKind(OpFlag) ||
6620             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6621           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6622           if (OpInfo.isIndirect) {
6623             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6624             LLVMContext &Ctx = *DAG.getContext();
6625             Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6626                                                " don't know how to handle tied "
6627                                                "indirect register inputs");
6628             return;
6629           }
6630 
6631           RegsForValue MatchedRegs;
6632           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6633           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6634           MatchedRegs.RegVTs.push_back(RegVT);
6635           MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6636           for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6637                i != e; ++i) {
6638             if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6639               MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6640             else {
6641               LLVMContext &Ctx = *DAG.getContext();
6642               Ctx.emitError(CS.getInstruction(),
6643                             "inline asm error: This value"
6644                             " type register class is not natively supported!");
6645               return;
6646             }
6647           }
6648           SDLoc dl = getCurSDLoc();
6649           // Use the produced MatchedRegs object to
6650           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6651                                     Chain, &Flag, CS.getInstruction());
6652           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6653                                            true, OpInfo.getMatchedOperand(), dl,
6654                                            DAG, AsmNodeOperands);
6655           break;
6656         }
6657 
6658         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6659         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6660                "Unexpected number of operands");
6661         // Add information to the INLINEASM node to know about this input.
6662         // See InlineAsm.h isUseOperandTiedToDef.
6663         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
6664         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6665                                                     OpInfo.getMatchedOperand());
6666         AsmNodeOperands.push_back(DAG.getTargetConstant(
6667             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6668         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6669         break;
6670       }
6671 
6672       // Treat indirect 'X' constraint as memory.
6673       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6674           OpInfo.isIndirect)
6675         OpInfo.ConstraintType = TargetLowering::C_Memory;
6676 
6677       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6678         std::vector<SDValue> Ops;
6679         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6680                                           Ops, DAG);
6681         if (Ops.empty()) {
6682           LLVMContext &Ctx = *DAG.getContext();
6683           Ctx.emitError(CS.getInstruction(),
6684                         "invalid operand for inline asm constraint '" +
6685                             Twine(OpInfo.ConstraintCode) + "'");
6686           return;
6687         }
6688 
6689         // Add information to the INLINEASM node to know about this input.
6690         unsigned ResOpType =
6691           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6692         AsmNodeOperands.push_back(DAG.getTargetConstant(
6693             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6694         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6695         break;
6696       }
6697 
6698       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6699         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6700         assert(InOperandVal.getValueType() ==
6701                    TLI.getPointerTy(DAG.getDataLayout()) &&
6702                "Memory operands expect pointer values");
6703 
6704         unsigned ConstraintID =
6705             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6706         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6707                "Failed to convert memory constraint code to constraint id.");
6708 
6709         // Add information to the INLINEASM node to know about this input.
6710         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6711         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
6712         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6713                                                         getCurSDLoc(),
6714                                                         MVT::i32));
6715         AsmNodeOperands.push_back(InOperandVal);
6716         break;
6717       }
6718 
6719       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6720               OpInfo.ConstraintType == TargetLowering::C_Register) &&
6721              "Unknown constraint type!");
6722 
6723       // TODO: Support this.
6724       if (OpInfo.isIndirect) {
6725         LLVMContext &Ctx = *DAG.getContext();
6726         Ctx.emitError(CS.getInstruction(),
6727                       "Don't know how to handle indirect register inputs yet "
6728                       "for constraint '" +
6729                           Twine(OpInfo.ConstraintCode) + "'");
6730         return;
6731       }
6732 
6733       // Copy the input into the appropriate registers.
6734       if (OpInfo.AssignedRegs.Regs.empty()) {
6735         LLVMContext &Ctx = *DAG.getContext();
6736         Ctx.emitError(CS.getInstruction(),
6737                       "couldn't allocate input reg for constraint '" +
6738                           Twine(OpInfo.ConstraintCode) + "'");
6739         return;
6740       }
6741 
6742       SDLoc dl = getCurSDLoc();
6743 
6744       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6745                                         Chain, &Flag, CS.getInstruction());
6746 
6747       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6748                                                dl, DAG, AsmNodeOperands);
6749       break;
6750     }
6751     case InlineAsm::isClobber: {
6752       // Add the clobbered value to the operand list, so that the register
6753       // allocator is aware that the physreg got clobbered.
6754       if (!OpInfo.AssignedRegs.Regs.empty())
6755         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6756                                                  false, 0, getCurSDLoc(), DAG,
6757                                                  AsmNodeOperands);
6758       break;
6759     }
6760     }
6761   }
6762 
6763   // Finish up input operands.  Set the input chain and add the flag last.
6764   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6765   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6766 
6767   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6768                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
6769   Flag = Chain.getValue(1);
6770 
6771   // If this asm returns a register value, copy the result from that register
6772   // and set it as the value of the call.
6773   if (!RetValRegs.Regs.empty()) {
6774     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6775                                              Chain, &Flag, CS.getInstruction());
6776 
6777     // FIXME: Why don't we do this for inline asms with MRVs?
6778     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6779       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
6780 
6781       // If any of the results of the inline asm is a vector, it may have the
6782       // wrong width/num elts.  This can happen for register classes that can
6783       // contain multiple different value types.  The preg or vreg allocated may
6784       // not have the same VT as was expected.  Convert it to the right type
6785       // with bit_convert.
6786       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6787         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6788                           ResultType, Val);
6789 
6790       } else if (ResultType != Val.getValueType() &&
6791                  ResultType.isInteger() && Val.getValueType().isInteger()) {
6792         // If a result value was tied to an input value, the computed result may
6793         // have a wider width than the expected result.  Extract the relevant
6794         // portion.
6795         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6796       }
6797 
6798       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6799     }
6800 
6801     setValue(CS.getInstruction(), Val);
6802     // Don't need to use this as a chain in this case.
6803     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6804       return;
6805   }
6806 
6807   std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6808 
6809   // Process indirect outputs, first output all of the flagged copies out of
6810   // physregs.
6811   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6812     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6813     const Value *Ptr = IndirectStoresToEmit[i].second;
6814     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6815                                              Chain, &Flag, IA);
6816     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6817   }
6818 
6819   // Emit the non-flagged stores from the physregs.
6820   SmallVector<SDValue, 8> OutChains;
6821   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6822     SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6823                                StoresToEmit[i].first,
6824                                getValue(StoresToEmit[i].second),
6825                                MachinePointerInfo(StoresToEmit[i].second),
6826                                false, false, 0);
6827     OutChains.push_back(Val);
6828   }
6829 
6830   if (!OutChains.empty())
6831     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
6832 
6833   DAG.setRoot(Chain);
6834 }
6835 
6836 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6837   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6838                           MVT::Other, getRoot(),
6839                           getValue(I.getArgOperand(0)),
6840                           DAG.getSrcValue(I.getArgOperand(0))));
6841 }
6842 
6843 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6845   const DataLayout &DL = DAG.getDataLayout();
6846   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6847                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
6848                            DAG.getSrcValue(I.getOperand(0)),
6849                            DL.getABITypeAlignment(I.getType()));
6850   setValue(&I, V);
6851   DAG.setRoot(V.getValue(1));
6852 }
6853 
6854 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6855   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6856                           MVT::Other, getRoot(),
6857                           getValue(I.getArgOperand(0)),
6858                           DAG.getSrcValue(I.getArgOperand(0))));
6859 }
6860 
6861 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6862   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6863                           MVT::Other, getRoot(),
6864                           getValue(I.getArgOperand(0)),
6865                           getValue(I.getArgOperand(1)),
6866                           DAG.getSrcValue(I.getArgOperand(0)),
6867                           DAG.getSrcValue(I.getArgOperand(1))));
6868 }
6869 
6870 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
6871                                                     const Instruction &I,
6872                                                     SDValue Op) {
6873   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
6874   if (!Range)
6875     return Op;
6876 
6877   Constant *Lo = cast<ConstantAsMetadata>(Range->getOperand(0))->getValue();
6878   if (!Lo->isNullValue())
6879     return Op;
6880 
6881   Constant *Hi = cast<ConstantAsMetadata>(Range->getOperand(1))->getValue();
6882   unsigned Bits = cast<ConstantInt>(Hi)->getValue().logBase2();
6883 
6884   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
6885 
6886   SDLoc SL = getCurSDLoc();
6887 
6888   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(),
6889                              Op, DAG.getValueType(SmallVT));
6890   unsigned NumVals = Op.getNode()->getNumValues();
6891   if (NumVals == 1)
6892     return ZExt;
6893 
6894   SmallVector<SDValue, 4> Ops;
6895 
6896   Ops.push_back(ZExt);
6897   for (unsigned I = 1; I != NumVals; ++I)
6898     Ops.push_back(Op.getValue(I));
6899 
6900   return DAG.getMergeValues(Ops, SL);
6901 }
6902 
6903 /// \brief Lower an argument list according to the target calling convention.
6904 ///
6905 /// \return A tuple of <return-value, token-chain>
6906 ///
6907 /// This is a helper for lowering intrinsics that follow a target calling
6908 /// convention or require stack pointer adjustment. Only a subset of the
6909 /// intrinsic's operands need to participate in the calling convention.
6910 std::pair<SDValue, SDValue> SelectionDAGBuilder::lowerCallOperands(
6911     ImmutableCallSite CS, unsigned ArgIdx, unsigned NumArgs, SDValue Callee,
6912     Type *ReturnTy, const BasicBlock *EHPadBB, bool IsPatchPoint) {
6913   TargetLowering::ArgListTy Args;
6914   Args.reserve(NumArgs);
6915 
6916   // Populate the argument list.
6917   // Attributes for args start at offset 1, after the return attribute.
6918   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6919        ArgI != ArgE; ++ArgI) {
6920     const Value *V = CS->getOperand(ArgI);
6921 
6922     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6923 
6924     TargetLowering::ArgListEntry Entry;
6925     Entry.Node = getValue(V);
6926     Entry.Ty = V->getType();
6927     Entry.setAttributes(&CS, AttrI);
6928     Args.push_back(Entry);
6929   }
6930 
6931   TargetLowering::CallLoweringInfo CLI(DAG);
6932   CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
6933     .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args), NumArgs)
6934     .setDiscardResult(CS->use_empty()).setIsPatchPoint(IsPatchPoint);
6935 
6936   return lowerInvokable(CLI, EHPadBB);
6937 }
6938 
6939 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6940 /// or patchpoint target node's operand list.
6941 ///
6942 /// Constants are converted to TargetConstants purely as an optimization to
6943 /// avoid constant materialization and register allocation.
6944 ///
6945 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6946 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6947 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6948 /// address materialization and register allocation, but may also be required
6949 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6950 /// alloca in the entry block, then the runtime may assume that the alloca's
6951 /// StackMap location can be read immediately after compilation and that the
6952 /// location is valid at any point during execution (this is similar to the
6953 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6954 /// only available in a register, then the runtime would need to trap when
6955 /// execution reaches the StackMap in order to read the alloca's location.
6956 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
6957                                 SDLoc DL, SmallVectorImpl<SDValue> &Ops,
6958                                 SelectionDAGBuilder &Builder) {
6959   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
6960     SDValue OpVal = Builder.getValue(CS.getArgument(i));
6961     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6962       Ops.push_back(
6963         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
6964       Ops.push_back(
6965         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
6966     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6967       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6968       Ops.push_back(Builder.DAG.getTargetFrameIndex(
6969           FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout())));
6970     } else
6971       Ops.push_back(OpVal);
6972   }
6973 }
6974 
6975 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6976 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6977   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6978   //                                  [live variables...])
6979 
6980   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6981 
6982   SDValue Chain, InFlag, Callee, NullPtr;
6983   SmallVector<SDValue, 32> Ops;
6984 
6985   SDLoc DL = getCurSDLoc();
6986   Callee = getValue(CI.getCalledValue());
6987   NullPtr = DAG.getIntPtrConstant(0, DL, true);
6988 
6989   // The stackmap intrinsic only records the live variables (the arguemnts
6990   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
6991   // intrinsic, this won't be lowered to a function call. This means we don't
6992   // have to worry about calling conventions and target specific lowering code.
6993   // Instead we perform the call lowering right here.
6994   //
6995   // chain, flag = CALLSEQ_START(chain, 0)
6996   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
6997   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
6998   //
6999   Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
7000   InFlag = Chain.getValue(1);
7001 
7002   // Add the <id> and <numBytes> constants.
7003   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7004   Ops.push_back(DAG.getTargetConstant(
7005                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7006   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7007   Ops.push_back(DAG.getTargetConstant(
7008                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7009                   MVT::i32));
7010 
7011   // Push live variables for the stack map.
7012   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7013 
7014   // We are not pushing any register mask info here on the operands list,
7015   // because the stackmap doesn't clobber anything.
7016 
7017   // Push the chain and the glue flag.
7018   Ops.push_back(Chain);
7019   Ops.push_back(InFlag);
7020 
7021   // Create the STACKMAP node.
7022   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7023   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7024   Chain = SDValue(SM, 0);
7025   InFlag = Chain.getValue(1);
7026 
7027   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7028 
7029   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7030 
7031   // Set the root to the target-lowered call chain.
7032   DAG.setRoot(Chain);
7033 
7034   // Inform the Frame Information that we have a stackmap in this function.
7035   FuncInfo.MF->getFrameInfo()->setHasStackMap();
7036 }
7037 
7038 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7039 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7040                                           const BasicBlock *EHPadBB) {
7041   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7042   //                                                 i32 <numBytes>,
7043   //                                                 i8* <target>,
7044   //                                                 i32 <numArgs>,
7045   //                                                 [Args...],
7046   //                                                 [live variables...])
7047 
7048   CallingConv::ID CC = CS.getCallingConv();
7049   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7050   bool HasDef = !CS->getType()->isVoidTy();
7051   SDLoc dl = getCurSDLoc();
7052   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7053 
7054   // Handle immediate and symbolic callees.
7055   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7056     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7057                                    /*isTarget=*/true);
7058   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7059     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7060                                          SDLoc(SymbolicCallee),
7061                                          SymbolicCallee->getValueType(0));
7062 
7063   // Get the real number of arguments participating in the call <numArgs>
7064   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7065   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7066 
7067   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7068   // Intrinsics include all meta-operands up to but not including CC.
7069   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7070   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7071          "Not enough arguments provided to the patchpoint intrinsic");
7072 
7073   // For AnyRegCC the arguments are lowered later on manually.
7074   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7075   Type *ReturnTy =
7076     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7077   std::pair<SDValue, SDValue> Result = lowerCallOperands(
7078       CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, EHPadBB, true);
7079 
7080   SDNode *CallEnd = Result.second.getNode();
7081   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7082     CallEnd = CallEnd->getOperand(0).getNode();
7083 
7084   /// Get a call instruction from the call sequence chain.
7085   /// Tail calls are not allowed.
7086   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7087          "Expected a callseq node.");
7088   SDNode *Call = CallEnd->getOperand(0).getNode();
7089   bool HasGlue = Call->getGluedNode();
7090 
7091   // Replace the target specific call node with the patchable intrinsic.
7092   SmallVector<SDValue, 8> Ops;
7093 
7094   // Add the <id> and <numBytes> constants.
7095   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7096   Ops.push_back(DAG.getTargetConstant(
7097                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
7098   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7099   Ops.push_back(DAG.getTargetConstant(
7100                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
7101                   MVT::i32));
7102 
7103   // Add the callee.
7104   Ops.push_back(Callee);
7105 
7106   // Adjust <numArgs> to account for any arguments that have been passed on the
7107   // stack instead.
7108   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7109   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7110   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7111   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
7112 
7113   // Add the calling convention
7114   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
7115 
7116   // Add the arguments we omitted previously. The register allocator should
7117   // place these in any free register.
7118   if (IsAnyRegCC)
7119     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7120       Ops.push_back(getValue(CS.getArgument(i)));
7121 
7122   // Push the arguments from the call instruction up to the register mask.
7123   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7124   Ops.append(Call->op_begin() + 2, e);
7125 
7126   // Push live variables for the stack map.
7127   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
7128 
7129   // Push the register mask info.
7130   if (HasGlue)
7131     Ops.push_back(*(Call->op_end()-2));
7132   else
7133     Ops.push_back(*(Call->op_end()-1));
7134 
7135   // Push the chain (this is originally the first operand of the call, but
7136   // becomes now the last or second to last operand).
7137   Ops.push_back(*(Call->op_begin()));
7138 
7139   // Push the glue flag (last operand).
7140   if (HasGlue)
7141     Ops.push_back(*(Call->op_end()-1));
7142 
7143   SDVTList NodeTys;
7144   if (IsAnyRegCC && HasDef) {
7145     // Create the return types based on the intrinsic definition
7146     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7147     SmallVector<EVT, 3> ValueVTs;
7148     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7149     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7150 
7151     // There is always a chain and a glue type at the end
7152     ValueVTs.push_back(MVT::Other);
7153     ValueVTs.push_back(MVT::Glue);
7154     NodeTys = DAG.getVTList(ValueVTs);
7155   } else
7156     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7157 
7158   // Replace the target specific call node with a PATCHPOINT node.
7159   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7160                                          dl, NodeTys, Ops);
7161 
7162   // Update the NodeMap.
7163   if (HasDef) {
7164     if (IsAnyRegCC)
7165       setValue(CS.getInstruction(), SDValue(MN, 0));
7166     else
7167       setValue(CS.getInstruction(), Result.first);
7168   }
7169 
7170   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7171   // call sequence. Furthermore the location of the chain and glue can change
7172   // when the AnyReg calling convention is used and the intrinsic returns a
7173   // value.
7174   if (IsAnyRegCC && HasDef) {
7175     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7176     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7177     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7178   } else
7179     DAG.ReplaceAllUsesWith(Call, MN);
7180   DAG.DeleteNode(Call);
7181 
7182   // Inform the Frame Information that we have a patchpoint in this function.
7183   FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
7184 }
7185 
7186 /// Returns an AttributeSet representing the attributes applied to the return
7187 /// value of the given call.
7188 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7189   SmallVector<Attribute::AttrKind, 2> Attrs;
7190   if (CLI.RetSExt)
7191     Attrs.push_back(Attribute::SExt);
7192   if (CLI.RetZExt)
7193     Attrs.push_back(Attribute::ZExt);
7194   if (CLI.IsInReg)
7195     Attrs.push_back(Attribute::InReg);
7196 
7197   return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7198                            Attrs);
7199 }
7200 
7201 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7202 /// implementation, which just calls LowerCall.
7203 /// FIXME: When all targets are
7204 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7205 std::pair<SDValue, SDValue>
7206 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7207   // Handle the incoming return values from the call.
7208   CLI.Ins.clear();
7209   Type *OrigRetTy = CLI.RetTy;
7210   SmallVector<EVT, 4> RetTys;
7211   SmallVector<uint64_t, 4> Offsets;
7212   auto &DL = CLI.DAG.getDataLayout();
7213   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
7214 
7215   SmallVector<ISD::OutputArg, 4> Outs;
7216   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
7217 
7218   bool CanLowerReturn =
7219       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7220                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7221 
7222   SDValue DemoteStackSlot;
7223   int DemoteStackIdx = -100;
7224   if (!CanLowerReturn) {
7225     // FIXME: equivalent assert?
7226     // assert(!CS.hasInAllocaArgument() &&
7227     //        "sret demotion is incompatible with inalloca");
7228     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
7229     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
7230     MachineFunction &MF = CLI.DAG.getMachineFunction();
7231     DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
7232     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7233 
7234     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL));
7235     ArgListEntry Entry;
7236     Entry.Node = DemoteStackSlot;
7237     Entry.Ty = StackSlotPtrType;
7238     Entry.isSExt = false;
7239     Entry.isZExt = false;
7240     Entry.isInReg = false;
7241     Entry.isSRet = true;
7242     Entry.isNest = false;
7243     Entry.isByVal = false;
7244     Entry.isReturned = false;
7245     Entry.Alignment = Align;
7246     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7247     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7248 
7249     // sret demotion isn't compatible with tail-calls, since the sret argument
7250     // points into the callers stack frame.
7251     CLI.IsTailCall = false;
7252   } else {
7253     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7254       EVT VT = RetTys[I];
7255       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7256       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7257       for (unsigned i = 0; i != NumRegs; ++i) {
7258         ISD::InputArg MyFlags;
7259         MyFlags.VT = RegisterVT;
7260         MyFlags.ArgVT = VT;
7261         MyFlags.Used = CLI.IsReturnValueUsed;
7262         if (CLI.RetSExt)
7263           MyFlags.Flags.setSExt();
7264         if (CLI.RetZExt)
7265           MyFlags.Flags.setZExt();
7266         if (CLI.IsInReg)
7267           MyFlags.Flags.setInReg();
7268         CLI.Ins.push_back(MyFlags);
7269       }
7270     }
7271   }
7272 
7273   // Handle all of the outgoing arguments.
7274   CLI.Outs.clear();
7275   CLI.OutVals.clear();
7276   ArgListTy &Args = CLI.getArgs();
7277   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7278     SmallVector<EVT, 4> ValueVTs;
7279     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
7280     Type *FinalType = Args[i].Ty;
7281     if (Args[i].isByVal)
7282       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7283     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7284         FinalType, CLI.CallConv, CLI.IsVarArg);
7285     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7286          ++Value) {
7287       EVT VT = ValueVTs[Value];
7288       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7289       SDValue Op = SDValue(Args[i].Node.getNode(),
7290                            Args[i].Node.getResNo() + Value);
7291       ISD::ArgFlagsTy Flags;
7292       unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7293 
7294       if (Args[i].isZExt)
7295         Flags.setZExt();
7296       if (Args[i].isSExt)
7297         Flags.setSExt();
7298       if (Args[i].isInReg)
7299         Flags.setInReg();
7300       if (Args[i].isSRet)
7301         Flags.setSRet();
7302       if (Args[i].isByVal)
7303         Flags.setByVal();
7304       if (Args[i].isInAlloca) {
7305         Flags.setInAlloca();
7306         // Set the byval flag for CCAssignFn callbacks that don't know about
7307         // inalloca.  This way we can know how many bytes we should've allocated
7308         // and how many bytes a callee cleanup function will pop.  If we port
7309         // inalloca to more targets, we'll have to add custom inalloca handling
7310         // in the various CC lowering callbacks.
7311         Flags.setByVal();
7312       }
7313       if (Args[i].isByVal || Args[i].isInAlloca) {
7314         PointerType *Ty = cast<PointerType>(Args[i].Ty);
7315         Type *ElementTy = Ty->getElementType();
7316         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7317         // For ByVal, alignment should come from FE.  BE will guess if this
7318         // info is not there but there are cases it cannot get right.
7319         unsigned FrameAlign;
7320         if (Args[i].Alignment)
7321           FrameAlign = Args[i].Alignment;
7322         else
7323           FrameAlign = getByValTypeAlignment(ElementTy, DL);
7324         Flags.setByValAlign(FrameAlign);
7325       }
7326       if (Args[i].isNest)
7327         Flags.setNest();
7328       if (NeedsRegBlock)
7329         Flags.setInConsecutiveRegs();
7330       Flags.setOrigAlign(OriginalAlignment);
7331 
7332       MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7333       unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7334       SmallVector<SDValue, 4> Parts(NumParts);
7335       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7336 
7337       if (Args[i].isSExt)
7338         ExtendKind = ISD::SIGN_EXTEND;
7339       else if (Args[i].isZExt)
7340         ExtendKind = ISD::ZERO_EXTEND;
7341 
7342       // Conservatively only handle 'returned' on non-vectors for now
7343       if (Args[i].isReturned && !Op.getValueType().isVector()) {
7344         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7345                "unexpected use of 'returned'");
7346         // Before passing 'returned' to the target lowering code, ensure that
7347         // either the register MVT and the actual EVT are the same size or that
7348         // the return value and argument are extended in the same way; in these
7349         // cases it's safe to pass the argument register value unchanged as the
7350         // return register value (although it's at the target's option whether
7351         // to do so)
7352         // TODO: allow code generation to take advantage of partially preserved
7353         // registers rather than clobbering the entire register when the
7354         // parameter extension method is not compatible with the return
7355         // extension method
7356         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7357             (ExtendKind != ISD::ANY_EXTEND &&
7358              CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7359         Flags.setReturned();
7360       }
7361 
7362       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7363                      CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
7364 
7365       for (unsigned j = 0; j != NumParts; ++j) {
7366         // if it isn't first piece, alignment must be 1
7367         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7368                                i < CLI.NumFixedArgs,
7369                                i, j*Parts[j].getValueType().getStoreSize());
7370         if (NumParts > 1 && j == 0)
7371           MyFlags.Flags.setSplit();
7372         else if (j != 0) {
7373           MyFlags.Flags.setOrigAlign(1);
7374           if (j == NumParts - 1)
7375             MyFlags.Flags.setSplitEnd();
7376         }
7377 
7378         CLI.Outs.push_back(MyFlags);
7379         CLI.OutVals.push_back(Parts[j]);
7380       }
7381 
7382       if (NeedsRegBlock && Value == NumValues - 1)
7383         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
7384     }
7385   }
7386 
7387   SmallVector<SDValue, 4> InVals;
7388   CLI.Chain = LowerCall(CLI, InVals);
7389 
7390   // Verify that the target's LowerCall behaved as expected.
7391   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7392          "LowerCall didn't return a valid chain!");
7393   assert((!CLI.IsTailCall || InVals.empty()) &&
7394          "LowerCall emitted a return value for a tail call!");
7395   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7396          "LowerCall didn't emit the correct number of values!");
7397 
7398   // For a tail call, the return value is merely live-out and there aren't
7399   // any nodes in the DAG representing it. Return a special value to
7400   // indicate that a tail call has been emitted and no more Instructions
7401   // should be processed in the current block.
7402   if (CLI.IsTailCall) {
7403     CLI.DAG.setRoot(CLI.Chain);
7404     return std::make_pair(SDValue(), SDValue());
7405   }
7406 
7407   DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7408           assert(InVals[i].getNode() &&
7409                  "LowerCall emitted a null value!");
7410           assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7411                  "LowerCall emitted a value with the wrong type!");
7412         });
7413 
7414   SmallVector<SDValue, 4> ReturnValues;
7415   if (!CanLowerReturn) {
7416     // The instruction result is the result of loading from the
7417     // hidden sret parameter.
7418     SmallVector<EVT, 1> PVTs;
7419     Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
7420 
7421     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
7422     assert(PVTs.size() == 1 && "Pointers should fit in one register");
7423     EVT PtrVT = PVTs[0];
7424 
7425     unsigned NumValues = RetTys.size();
7426     ReturnValues.resize(NumValues);
7427     SmallVector<SDValue, 4> Chains(NumValues);
7428 
7429     // An aggregate return value cannot wrap around the address space, so
7430     // offsets to its parts don't wrap either.
7431     SDNodeFlags Flags;
7432     Flags.setNoUnsignedWrap(true);
7433 
7434     for (unsigned i = 0; i < NumValues; ++i) {
7435       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7436                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
7437                                                         PtrVT), &Flags);
7438       SDValue L = CLI.DAG.getLoad(
7439           RetTys[i], CLI.DL, CLI.Chain, Add,
7440           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
7441                                             DemoteStackIdx, Offsets[i]),
7442           false, false, false, 1);
7443       ReturnValues[i] = L;
7444       Chains[i] = L.getValue(1);
7445     }
7446 
7447     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7448   } else {
7449     // Collect the legal value parts into potentially illegal values
7450     // that correspond to the original function's return values.
7451     ISD::NodeType AssertOp = ISD::DELETED_NODE;
7452     if (CLI.RetSExt)
7453       AssertOp = ISD::AssertSext;
7454     else if (CLI.RetZExt)
7455       AssertOp = ISD::AssertZext;
7456     unsigned CurReg = 0;
7457     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7458       EVT VT = RetTys[I];
7459       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7460       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7461 
7462       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7463                                               NumRegs, RegisterVT, VT, nullptr,
7464                                               AssertOp));
7465       CurReg += NumRegs;
7466     }
7467 
7468     // For a function returning void, there is no return value. We can't create
7469     // such a node, so we just return a null return value in that case. In
7470     // that case, nothing will actually look at the value.
7471     if (ReturnValues.empty())
7472       return std::make_pair(SDValue(), CLI.Chain);
7473   }
7474 
7475   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7476                                 CLI.DAG.getVTList(RetTys), ReturnValues);
7477   return std::make_pair(Res, CLI.Chain);
7478 }
7479 
7480 void TargetLowering::LowerOperationWrapper(SDNode *N,
7481                                            SmallVectorImpl<SDValue> &Results,
7482                                            SelectionDAG &DAG) const {
7483   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
7484     Results.push_back(Res);
7485 }
7486 
7487 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7488   llvm_unreachable("LowerOperation not implemented for this target!");
7489 }
7490 
7491 void
7492 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7493   SDValue Op = getNonRegisterValue(V);
7494   assert((Op.getOpcode() != ISD::CopyFromReg ||
7495           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7496          "Copy from a reg to the same reg!");
7497   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7498 
7499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7500   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
7501                    V->getType());
7502   SDValue Chain = DAG.getEntryNode();
7503 
7504   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7505                               FuncInfo.PreferredExtendType.end())
7506                                  ? ISD::ANY_EXTEND
7507                                  : FuncInfo.PreferredExtendType[V];
7508   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
7509   PendingExports.push_back(Chain);
7510 }
7511 
7512 #include "llvm/CodeGen/SelectionDAGISel.h"
7513 
7514 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7515 /// entry block, return true.  This includes arguments used by switches, since
7516 /// the switch may expand into multiple basic blocks.
7517 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7518   // With FastISel active, we may be splitting blocks, so force creation
7519   // of virtual registers for all non-dead arguments.
7520   if (FastISel)
7521     return A->use_empty();
7522 
7523   const BasicBlock &Entry = A->getParent()->front();
7524   for (const User *U : A->users())
7525     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
7526       return false;  // Use not in entry block.
7527 
7528   return true;
7529 }
7530 
7531 void SelectionDAGISel::LowerArguments(const Function &F) {
7532   SelectionDAG &DAG = SDB->DAG;
7533   SDLoc dl = SDB->getCurSDLoc();
7534   const DataLayout &DL = DAG.getDataLayout();
7535   SmallVector<ISD::InputArg, 16> Ins;
7536 
7537   if (!FuncInfo->CanLowerReturn) {
7538     // Put in an sret pointer parameter before all the other parameters.
7539     SmallVector<EVT, 1> ValueVTs;
7540     ComputeValueVTs(*TLI, DAG.getDataLayout(),
7541                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
7542 
7543     // NOTE: Assuming that a pointer will never break down to more than one VT
7544     // or one register.
7545     ISD::ArgFlagsTy Flags;
7546     Flags.setSRet();
7547     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7548     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
7549                          ISD::InputArg::NoArgIndex, 0);
7550     Ins.push_back(RetArg);
7551   }
7552 
7553   // Set up the incoming argument description vector.
7554   unsigned Idx = 1;
7555   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7556        I != E; ++I, ++Idx) {
7557     SmallVector<EVT, 4> ValueVTs;
7558     ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7559     bool isArgValueUsed = !I->use_empty();
7560     unsigned PartBase = 0;
7561     Type *FinalType = I->getType();
7562     if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7563       FinalType = cast<PointerType>(FinalType)->getElementType();
7564     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7565         FinalType, F.getCallingConv(), F.isVarArg());
7566     for (unsigned Value = 0, NumValues = ValueVTs.size();
7567          Value != NumValues; ++Value) {
7568       EVT VT = ValueVTs[Value];
7569       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7570       ISD::ArgFlagsTy Flags;
7571       unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7572 
7573       if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7574         Flags.setZExt();
7575       if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7576         Flags.setSExt();
7577       if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7578         Flags.setInReg();
7579       if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7580         Flags.setSRet();
7581       if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7582         Flags.setByVal();
7583       if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7584         Flags.setInAlloca();
7585         // Set the byval flag for CCAssignFn callbacks that don't know about
7586         // inalloca.  This way we can know how many bytes we should've allocated
7587         // and how many bytes a callee cleanup function will pop.  If we port
7588         // inalloca to more targets, we'll have to add custom inalloca handling
7589         // in the various CC lowering callbacks.
7590         Flags.setByVal();
7591       }
7592       if (F.getCallingConv() == CallingConv::X86_INTR) {
7593         // IA Interrupt passes frame (1st parameter) by value in the stack.
7594         if (Idx == 1)
7595           Flags.setByVal();
7596       }
7597       if (Flags.isByVal() || Flags.isInAlloca()) {
7598         PointerType *Ty = cast<PointerType>(I->getType());
7599         Type *ElementTy = Ty->getElementType();
7600         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7601         // For ByVal, alignment should be passed from FE.  BE will guess if
7602         // this info is not there but there are cases it cannot get right.
7603         unsigned FrameAlign;
7604         if (F.getParamAlignment(Idx))
7605           FrameAlign = F.getParamAlignment(Idx);
7606         else
7607           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
7608         Flags.setByValAlign(FrameAlign);
7609       }
7610       if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7611         Flags.setNest();
7612       if (NeedsRegBlock)
7613         Flags.setInConsecutiveRegs();
7614       Flags.setOrigAlign(OriginalAlignment);
7615 
7616       MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7617       unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7618       for (unsigned i = 0; i != NumRegs; ++i) {
7619         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7620                               Idx-1, PartBase+i*RegisterVT.getStoreSize());
7621         if (NumRegs > 1 && i == 0)
7622           MyFlags.Flags.setSplit();
7623         // if it isn't first piece, alignment must be 1
7624         else if (i > 0) {
7625           MyFlags.Flags.setOrigAlign(1);
7626           if (i == NumRegs - 1)
7627             MyFlags.Flags.setSplitEnd();
7628         }
7629         Ins.push_back(MyFlags);
7630       }
7631       if (NeedsRegBlock && Value == NumValues - 1)
7632         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
7633       PartBase += VT.getStoreSize();
7634     }
7635   }
7636 
7637   // Call the target to set up the argument values.
7638   SmallVector<SDValue, 8> InVals;
7639   SDValue NewRoot = TLI->LowerFormalArguments(
7640       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
7641 
7642   // Verify that the target's LowerFormalArguments behaved as expected.
7643   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7644          "LowerFormalArguments didn't return a valid chain!");
7645   assert(InVals.size() == Ins.size() &&
7646          "LowerFormalArguments didn't emit the correct number of values!");
7647   DEBUG({
7648       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7649         assert(InVals[i].getNode() &&
7650                "LowerFormalArguments emitted a null value!");
7651         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7652                "LowerFormalArguments emitted a value with the wrong type!");
7653       }
7654     });
7655 
7656   // Update the DAG with the new chain value resulting from argument lowering.
7657   DAG.setRoot(NewRoot);
7658 
7659   // Set up the argument values.
7660   unsigned i = 0;
7661   Idx = 1;
7662   if (!FuncInfo->CanLowerReturn) {
7663     // Create a virtual register for the sret pointer, and put in a copy
7664     // from the sret argument into it.
7665     SmallVector<EVT, 1> ValueVTs;
7666     ComputeValueVTs(*TLI, DAG.getDataLayout(),
7667                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
7668     MVT VT = ValueVTs[0].getSimpleVT();
7669     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7670     ISD::NodeType AssertOp = ISD::DELETED_NODE;
7671     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7672                                         RegVT, VT, nullptr, AssertOp);
7673 
7674     MachineFunction& MF = SDB->DAG.getMachineFunction();
7675     MachineRegisterInfo& RegInfo = MF.getRegInfo();
7676     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7677     FuncInfo->DemoteRegister = SRetReg;
7678     NewRoot =
7679         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
7680     DAG.setRoot(NewRoot);
7681 
7682     // i indexes lowered arguments.  Bump it past the hidden sret argument.
7683     // Idx indexes LLVM arguments.  Don't touch it.
7684     ++i;
7685   }
7686 
7687   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7688       ++I, ++Idx) {
7689     SmallVector<SDValue, 4> ArgValues;
7690     SmallVector<EVT, 4> ValueVTs;
7691     ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7692     unsigned NumValues = ValueVTs.size();
7693 
7694     // If this argument is unused then remember its value. It is used to generate
7695     // debugging information.
7696     if (I->use_empty() && NumValues) {
7697       SDB->setUnusedArgValue(&*I, InVals[i]);
7698 
7699       // Also remember any frame index for use in FastISel.
7700       if (FrameIndexSDNode *FI =
7701           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7702         FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7703     }
7704 
7705     for (unsigned Val = 0; Val != NumValues; ++Val) {
7706       EVT VT = ValueVTs[Val];
7707       MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7708       unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7709 
7710       if (!I->use_empty()) {
7711         ISD::NodeType AssertOp = ISD::DELETED_NODE;
7712         if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7713           AssertOp = ISD::AssertSext;
7714         else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7715           AssertOp = ISD::AssertZext;
7716 
7717         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7718                                              NumParts, PartVT, VT,
7719                                              nullptr, AssertOp));
7720       }
7721 
7722       i += NumParts;
7723     }
7724 
7725     // We don't need to do anything else for unused arguments.
7726     if (ArgValues.empty())
7727       continue;
7728 
7729     // Note down frame index.
7730     if (FrameIndexSDNode *FI =
7731         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7732       FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7733 
7734     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
7735                                      SDB->getCurSDLoc());
7736 
7737     SDB->setValue(&*I, Res);
7738     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7739       if (LoadSDNode *LNode =
7740           dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7741         if (FrameIndexSDNode *FI =
7742             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7743         FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7744     }
7745 
7746     // If this argument is live outside of the entry block, insert a copy from
7747     // wherever we got it to the vreg that other BB's will reference it as.
7748     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7749       // If we can, though, try to skip creating an unnecessary vreg.
7750       // FIXME: This isn't very clean... it would be nice to make this more
7751       // general.  It's also subtly incompatible with the hacks FastISel
7752       // uses with vregs.
7753       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7754       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7755         FuncInfo->ValueMap[&*I] = Reg;
7756         continue;
7757       }
7758     }
7759     if (!isOnlyUsedInEntryBlock(&*I, TM.Options.EnableFastISel)) {
7760       FuncInfo->InitializeRegForValue(&*I);
7761       SDB->CopyToExportRegsIfNeeded(&*I);
7762     }
7763   }
7764 
7765   assert(i == InVals.size() && "Argument register count mismatch!");
7766 
7767   // Finally, if the target has anything special to do, allow it to do so.
7768   EmitFunctionEntryCode();
7769 }
7770 
7771 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
7772 /// ensure constants are generated when needed.  Remember the virtual registers
7773 /// that need to be added to the Machine PHI nodes as input.  We cannot just
7774 /// directly add them, because expansion might result in multiple MBB's for one
7775 /// BB.  As such, the start of the BB might correspond to a different MBB than
7776 /// the end.
7777 ///
7778 void
7779 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7780   const TerminatorInst *TI = LLVMBB->getTerminator();
7781 
7782   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7783 
7784   // Check PHI nodes in successors that expect a value to be available from this
7785   // block.
7786   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7787     const BasicBlock *SuccBB = TI->getSuccessor(succ);
7788     if (!isa<PHINode>(SuccBB->begin())) continue;
7789     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7790 
7791     // If this terminator has multiple identical successors (common for
7792     // switches), only handle each succ once.
7793     if (!SuccsHandled.insert(SuccMBB).second)
7794       continue;
7795 
7796     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7797 
7798     // At this point we know that there is a 1-1 correspondence between LLVM PHI
7799     // nodes and Machine PHI nodes, but the incoming operands have not been
7800     // emitted yet.
7801     for (BasicBlock::const_iterator I = SuccBB->begin();
7802          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7803       // Ignore dead phi's.
7804       if (PN->use_empty()) continue;
7805 
7806       // Skip empty types
7807       if (PN->getType()->isEmptyTy())
7808         continue;
7809 
7810       unsigned Reg;
7811       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7812 
7813       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7814         unsigned &RegOut = ConstantsOut[C];
7815         if (RegOut == 0) {
7816           RegOut = FuncInfo.CreateRegs(C->getType());
7817           CopyValueToVirtualRegister(C, RegOut);
7818         }
7819         Reg = RegOut;
7820       } else {
7821         DenseMap<const Value *, unsigned>::iterator I =
7822           FuncInfo.ValueMap.find(PHIOp);
7823         if (I != FuncInfo.ValueMap.end())
7824           Reg = I->second;
7825         else {
7826           assert(isa<AllocaInst>(PHIOp) &&
7827                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7828                  "Didn't codegen value into a register!??");
7829           Reg = FuncInfo.CreateRegs(PHIOp->getType());
7830           CopyValueToVirtualRegister(PHIOp, Reg);
7831         }
7832       }
7833 
7834       // Remember that this register needs to added to the machine PHI node as
7835       // the input for this MBB.
7836       SmallVector<EVT, 4> ValueVTs;
7837       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7838       ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
7839       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7840         EVT VT = ValueVTs[vti];
7841         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
7842         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7843           FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7844         Reg += NumRegisters;
7845       }
7846     }
7847   }
7848 
7849   ConstantsOut.clear();
7850 }
7851 
7852 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7853 /// is 0.
7854 MachineBasicBlock *
7855 SelectionDAGBuilder::StackProtectorDescriptor::
7856 AddSuccessorMBB(const BasicBlock *BB,
7857                 MachineBasicBlock *ParentMBB,
7858                 bool IsLikely,
7859                 MachineBasicBlock *SuccMBB) {
7860   // If SuccBB has not been created yet, create it.
7861   if (!SuccMBB) {
7862     MachineFunction *MF = ParentMBB->getParent();
7863     MachineFunction::iterator BBI(ParentMBB);
7864     SuccMBB = MF->CreateMachineBasicBlock(BB);
7865     MF->insert(++BBI, SuccMBB);
7866   }
7867   // Add it as a successor of ParentMBB.
7868   ParentMBB->addSuccessor(
7869       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
7870   return SuccMBB;
7871 }
7872 
7873 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
7874   MachineFunction::iterator I(MBB);
7875   if (++I == FuncInfo.MF->end())
7876     return nullptr;
7877   return &*I;
7878 }
7879 
7880 /// During lowering new call nodes can be created (such as memset, etc.).
7881 /// Those will become new roots of the current DAG, but complications arise
7882 /// when they are tail calls. In such cases, the call lowering will update
7883 /// the root, but the builder still needs to know that a tail call has been
7884 /// lowered in order to avoid generating an additional return.
7885 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
7886   // If the node is null, we do have a tail call.
7887   if (MaybeTC.getNode() != nullptr)
7888     DAG.setRoot(MaybeTC);
7889   else
7890     HasTailCall = true;
7891 }
7892 
7893 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters,
7894                                   unsigned *TotalCases, unsigned First,
7895                                   unsigned Last) {
7896   assert(Last >= First);
7897   assert(TotalCases[Last] >= TotalCases[First]);
7898 
7899   APInt LowCase = Clusters[First].Low->getValue();
7900   APInt HighCase = Clusters[Last].High->getValue();
7901   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
7902 
7903   // FIXME: A range of consecutive cases has 100% density, but only requires one
7904   // comparison to lower. We should discriminate against such consecutive ranges
7905   // in jump tables.
7906 
7907   uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100);
7908   uint64_t Range = Diff + 1;
7909 
7910   uint64_t NumCases =
7911       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
7912 
7913   assert(NumCases < UINT64_MAX / 100);
7914   assert(Range >= NumCases);
7915 
7916   return NumCases * 100 >= Range * MinJumpTableDensity;
7917 }
7918 
7919 static inline bool areJTsAllowed(const TargetLowering &TLI) {
7920   return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
7921          TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
7922 }
7923 
7924 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters,
7925                                          unsigned First, unsigned Last,
7926                                          const SwitchInst *SI,
7927                                          MachineBasicBlock *DefaultMBB,
7928                                          CaseCluster &JTCluster) {
7929   assert(First <= Last);
7930 
7931   auto Prob = BranchProbability::getZero();
7932   unsigned NumCmps = 0;
7933   std::vector<MachineBasicBlock*> Table;
7934   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
7935 
7936   // Initialize probabilities in JTProbs.
7937   for (unsigned I = First; I <= Last; ++I)
7938     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
7939 
7940   for (unsigned I = First; I <= Last; ++I) {
7941     assert(Clusters[I].Kind == CC_Range);
7942     Prob += Clusters[I].Prob;
7943     APInt Low = Clusters[I].Low->getValue();
7944     APInt High = Clusters[I].High->getValue();
7945     NumCmps += (Low == High) ? 1 : 2;
7946     if (I != First) {
7947       // Fill the gap between this and the previous cluster.
7948       APInt PreviousHigh = Clusters[I - 1].High->getValue();
7949       assert(PreviousHigh.slt(Low));
7950       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
7951       for (uint64_t J = 0; J < Gap; J++)
7952         Table.push_back(DefaultMBB);
7953     }
7954     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
7955     for (uint64_t J = 0; J < ClusterSize; ++J)
7956       Table.push_back(Clusters[I].MBB);
7957     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
7958   }
7959 
7960   unsigned NumDests = JTProbs.size();
7961   if (isSuitableForBitTests(NumDests, NumCmps,
7962                             Clusters[First].Low->getValue(),
7963                             Clusters[Last].High->getValue())) {
7964     // Clusters[First..Last] should be lowered as bit tests instead.
7965     return false;
7966   }
7967 
7968   // Create the MBB that will load from and jump through the table.
7969   // Note: We create it here, but it's not inserted into the function yet.
7970   MachineFunction *CurMF = FuncInfo.MF;
7971   MachineBasicBlock *JumpTableMBB =
7972       CurMF->CreateMachineBasicBlock(SI->getParent());
7973 
7974   // Add successors. Note: use table order for determinism.
7975   SmallPtrSet<MachineBasicBlock *, 8> Done;
7976   for (MachineBasicBlock *Succ : Table) {
7977     if (Done.count(Succ))
7978       continue;
7979     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
7980     Done.insert(Succ);
7981   }
7982   JumpTableMBB->normalizeSuccProbs();
7983 
7984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7985   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
7986                      ->createJumpTableIndex(Table);
7987 
7988   // Set up the jump table info.
7989   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
7990   JumpTableHeader JTH(Clusters[First].Low->getValue(),
7991                       Clusters[Last].High->getValue(), SI->getCondition(),
7992                       nullptr, false);
7993   JTCases.emplace_back(std::move(JTH), std::move(JT));
7994 
7995   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
7996                                      JTCases.size() - 1, Prob);
7997   return true;
7998 }
7999 
8000 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
8001                                          const SwitchInst *SI,
8002                                          MachineBasicBlock *DefaultMBB) {
8003 #ifndef NDEBUG
8004   // Clusters must be non-empty, sorted, and only contain Range clusters.
8005   assert(!Clusters.empty());
8006   for (CaseCluster &C : Clusters)
8007     assert(C.Kind == CC_Range);
8008   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
8009     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
8010 #endif
8011 
8012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8013   if (!areJTsAllowed(TLI))
8014     return;
8015 
8016   const int64_t N = Clusters.size();
8017   const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries();
8018 
8019   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
8020   SmallVector<unsigned, 8> TotalCases(N);
8021 
8022   for (unsigned i = 0; i < N; ++i) {
8023     APInt Hi = Clusters[i].High->getValue();
8024     APInt Lo = Clusters[i].Low->getValue();
8025     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
8026     if (i != 0)
8027       TotalCases[i] += TotalCases[i - 1];
8028   }
8029 
8030   if (N >= MinJumpTableSize && isDense(Clusters, &TotalCases[0], 0, N - 1)) {
8031     // Cheap case: the whole range might be suitable for jump table.
8032     CaseCluster JTCluster;
8033     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
8034       Clusters[0] = JTCluster;
8035       Clusters.resize(1);
8036       return;
8037     }
8038   }
8039 
8040   // The algorithm below is not suitable for -O0.
8041   if (TM.getOptLevel() == CodeGenOpt::None)
8042     return;
8043 
8044   // Split Clusters into minimum number of dense partitions. The algorithm uses
8045   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
8046   // for the Case Statement'" (1994), but builds the MinPartitions array in
8047   // reverse order to make it easier to reconstruct the partitions in ascending
8048   // order. In the choice between two optimal partitionings, it picks the one
8049   // which yields more jump tables.
8050 
8051   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
8052   SmallVector<unsigned, 8> MinPartitions(N);
8053   // LastElement[i] is the last element of the partition starting at i.
8054   SmallVector<unsigned, 8> LastElement(N);
8055   // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1].
8056   SmallVector<unsigned, 8> NumTables(N);
8057 
8058   // Base case: There is only one way to partition Clusters[N-1].
8059   MinPartitions[N - 1] = 1;
8060   LastElement[N - 1] = N - 1;
8061   assert(MinJumpTableSize > 1);
8062   NumTables[N - 1] = 0;
8063 
8064   // Note: loop indexes are signed to avoid underflow.
8065   for (int64_t i = N - 2; i >= 0; i--) {
8066     // Find optimal partitioning of Clusters[i..N-1].
8067     // Baseline: Put Clusters[i] into a partition on its own.
8068     MinPartitions[i] = MinPartitions[i + 1] + 1;
8069     LastElement[i] = i;
8070     NumTables[i] = NumTables[i + 1];
8071 
8072     // Search for a solution that results in fewer partitions.
8073     for (int64_t j = N - 1; j > i; j--) {
8074       // Try building a partition from Clusters[i..j].
8075       if (isDense(Clusters, &TotalCases[0], i, j)) {
8076         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
8077         bool IsTable = j - i + 1 >= MinJumpTableSize;
8078         unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]);
8079 
8080         // If this j leads to fewer partitions, or same number of partitions
8081         // with more lookup tables, it is a better partitioning.
8082         if (NumPartitions < MinPartitions[i] ||
8083             (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) {
8084           MinPartitions[i] = NumPartitions;
8085           LastElement[i] = j;
8086           NumTables[i] = Tables;
8087         }
8088       }
8089     }
8090   }
8091 
8092   // Iterate over the partitions, replacing some with jump tables in-place.
8093   unsigned DstIndex = 0;
8094   for (unsigned First = 0, Last; First < N; First = Last + 1) {
8095     Last = LastElement[First];
8096     assert(Last >= First);
8097     assert(DstIndex <= First);
8098     unsigned NumClusters = Last - First + 1;
8099 
8100     CaseCluster JTCluster;
8101     if (NumClusters >= MinJumpTableSize &&
8102         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
8103       Clusters[DstIndex++] = JTCluster;
8104     } else {
8105       for (unsigned I = First; I <= Last; ++I)
8106         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
8107     }
8108   }
8109   Clusters.resize(DstIndex);
8110 }
8111 
8112 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) {
8113   // FIXME: Using the pointer type doesn't seem ideal.
8114   uint64_t BW = DAG.getDataLayout().getPointerSizeInBits();
8115   uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
8116   return Range <= BW;
8117 }
8118 
8119 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests,
8120                                                 unsigned NumCmps,
8121                                                 const APInt &Low,
8122                                                 const APInt &High) {
8123   // FIXME: I don't think NumCmps is the correct metric: a single case and a
8124   // range of cases both require only one branch to lower. Just looking at the
8125   // number of clusters and destinations should be enough to decide whether to
8126   // build bit tests.
8127 
8128   // To lower a range with bit tests, the range must fit the bitwidth of a
8129   // machine word.
8130   if (!rangeFitsInWord(Low, High))
8131     return false;
8132 
8133   // Decide whether it's profitable to lower this range with bit tests. Each
8134   // destination requires a bit test and branch, and there is an overall range
8135   // check branch. For a small number of clusters, separate comparisons might be
8136   // cheaper, and for many destinations, splitting the range might be better.
8137   return (NumDests == 1 && NumCmps >= 3) ||
8138          (NumDests == 2 && NumCmps >= 5) ||
8139          (NumDests == 3 && NumCmps >= 6);
8140 }
8141 
8142 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
8143                                         unsigned First, unsigned Last,
8144                                         const SwitchInst *SI,
8145                                         CaseCluster &BTCluster) {
8146   assert(First <= Last);
8147   if (First == Last)
8148     return false;
8149 
8150   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
8151   unsigned NumCmps = 0;
8152   for (int64_t I = First; I <= Last; ++I) {
8153     assert(Clusters[I].Kind == CC_Range);
8154     Dests.set(Clusters[I].MBB->getNumber());
8155     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
8156   }
8157   unsigned NumDests = Dests.count();
8158 
8159   APInt Low = Clusters[First].Low->getValue();
8160   APInt High = Clusters[Last].High->getValue();
8161   assert(Low.slt(High));
8162 
8163   if (!isSuitableForBitTests(NumDests, NumCmps, Low, High))
8164     return false;
8165 
8166   APInt LowBound;
8167   APInt CmpRange;
8168 
8169   const int BitWidth = DAG.getTargetLoweringInfo()
8170                            .getPointerTy(DAG.getDataLayout())
8171                            .getSizeInBits();
8172   assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!");
8173 
8174   // Check if the clusters cover a contiguous range such that no value in the
8175   // range will jump to the default statement.
8176   bool ContiguousRange = true;
8177   for (int64_t I = First + 1; I <= Last; ++I) {
8178     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
8179       ContiguousRange = false;
8180       break;
8181     }
8182   }
8183 
8184   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
8185     // Optimize the case where all the case values fit in a word without having
8186     // to subtract minValue. In this case, we can optimize away the subtraction.
8187     LowBound = APInt::getNullValue(Low.getBitWidth());
8188     CmpRange = High;
8189     ContiguousRange = false;
8190   } else {
8191     LowBound = Low;
8192     CmpRange = High - Low;
8193   }
8194 
8195   CaseBitsVector CBV;
8196   auto TotalProb = BranchProbability::getZero();
8197   for (unsigned i = First; i <= Last; ++i) {
8198     // Find the CaseBits for this destination.
8199     unsigned j;
8200     for (j = 0; j < CBV.size(); ++j)
8201       if (CBV[j].BB == Clusters[i].MBB)
8202         break;
8203     if (j == CBV.size())
8204       CBV.push_back(
8205           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
8206     CaseBits *CB = &CBV[j];
8207 
8208     // Update Mask, Bits and ExtraProb.
8209     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
8210     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
8211     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
8212     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
8213     CB->Bits += Hi - Lo + 1;
8214     CB->ExtraProb += Clusters[i].Prob;
8215     TotalProb += Clusters[i].Prob;
8216   }
8217 
8218   BitTestInfo BTI;
8219   std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
8220     // Sort by probability first, number of bits second.
8221     if (a.ExtraProb != b.ExtraProb)
8222       return a.ExtraProb > b.ExtraProb;
8223     return a.Bits > b.Bits;
8224   });
8225 
8226   for (auto &CB : CBV) {
8227     MachineBasicBlock *BitTestBB =
8228         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
8229     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
8230   }
8231   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
8232                             SI->getCondition(), -1U, MVT::Other, false,
8233                             ContiguousRange, nullptr, nullptr, std::move(BTI),
8234                             TotalProb);
8235 
8236   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
8237                                     BitTestCases.size() - 1, TotalProb);
8238   return true;
8239 }
8240 
8241 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
8242                                               const SwitchInst *SI) {
8243 // Partition Clusters into as few subsets as possible, where each subset has a
8244 // range that fits in a machine word and has <= 3 unique destinations.
8245 
8246 #ifndef NDEBUG
8247   // Clusters must be sorted and contain Range or JumpTable clusters.
8248   assert(!Clusters.empty());
8249   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
8250   for (const CaseCluster &C : Clusters)
8251     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
8252   for (unsigned i = 1; i < Clusters.size(); ++i)
8253     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
8254 #endif
8255 
8256   // The algorithm below is not suitable for -O0.
8257   if (TM.getOptLevel() == CodeGenOpt::None)
8258     return;
8259 
8260   // If target does not have legal shift left, do not emit bit tests at all.
8261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8262   EVT PTy = TLI.getPointerTy(DAG.getDataLayout());
8263   if (!TLI.isOperationLegal(ISD::SHL, PTy))
8264     return;
8265 
8266   int BitWidth = PTy.getSizeInBits();
8267   const int64_t N = Clusters.size();
8268 
8269   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
8270   SmallVector<unsigned, 8> MinPartitions(N);
8271   // LastElement[i] is the last element of the partition starting at i.
8272   SmallVector<unsigned, 8> LastElement(N);
8273 
8274   // FIXME: This might not be the best algorithm for finding bit test clusters.
8275 
8276   // Base case: There is only one way to partition Clusters[N-1].
8277   MinPartitions[N - 1] = 1;
8278   LastElement[N - 1] = N - 1;
8279 
8280   // Note: loop indexes are signed to avoid underflow.
8281   for (int64_t i = N - 2; i >= 0; --i) {
8282     // Find optimal partitioning of Clusters[i..N-1].
8283     // Baseline: Put Clusters[i] into a partition on its own.
8284     MinPartitions[i] = MinPartitions[i + 1] + 1;
8285     LastElement[i] = i;
8286 
8287     // Search for a solution that results in fewer partitions.
8288     // Note: the search is limited by BitWidth, reducing time complexity.
8289     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
8290       // Try building a partition from Clusters[i..j].
8291 
8292       // Check the range.
8293       if (!rangeFitsInWord(Clusters[i].Low->getValue(),
8294                            Clusters[j].High->getValue()))
8295         continue;
8296 
8297       // Check nbr of destinations and cluster types.
8298       // FIXME: This works, but doesn't seem very efficient.
8299       bool RangesOnly = true;
8300       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
8301       for (int64_t k = i; k <= j; k++) {
8302         if (Clusters[k].Kind != CC_Range) {
8303           RangesOnly = false;
8304           break;
8305         }
8306         Dests.set(Clusters[k].MBB->getNumber());
8307       }
8308       if (!RangesOnly || Dests.count() > 3)
8309         break;
8310 
8311       // Check if it's a better partition.
8312       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
8313       if (NumPartitions < MinPartitions[i]) {
8314         // Found a better partition.
8315         MinPartitions[i] = NumPartitions;
8316         LastElement[i] = j;
8317       }
8318     }
8319   }
8320 
8321   // Iterate over the partitions, replacing with bit-test clusters in-place.
8322   unsigned DstIndex = 0;
8323   for (unsigned First = 0, Last; First < N; First = Last + 1) {
8324     Last = LastElement[First];
8325     assert(First <= Last);
8326     assert(DstIndex <= First);
8327 
8328     CaseCluster BitTestCluster;
8329     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
8330       Clusters[DstIndex++] = BitTestCluster;
8331     } else {
8332       size_t NumClusters = Last - First + 1;
8333       std::memmove(&Clusters[DstIndex], &Clusters[First],
8334                    sizeof(Clusters[0]) * NumClusters);
8335       DstIndex += NumClusters;
8336     }
8337   }
8338   Clusters.resize(DstIndex);
8339 }
8340 
8341 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
8342                                         MachineBasicBlock *SwitchMBB,
8343                                         MachineBasicBlock *DefaultMBB) {
8344   MachineFunction *CurMF = FuncInfo.MF;
8345   MachineBasicBlock *NextMBB = nullptr;
8346   MachineFunction::iterator BBI(W.MBB);
8347   if (++BBI != FuncInfo.MF->end())
8348     NextMBB = &*BBI;
8349 
8350   unsigned Size = W.LastCluster - W.FirstCluster + 1;
8351 
8352   BranchProbabilityInfo *BPI = FuncInfo.BPI;
8353 
8354   if (Size == 2 && W.MBB == SwitchMBB) {
8355     // If any two of the cases has the same destination, and if one value
8356     // is the same as the other, but has one bit unset that the other has set,
8357     // use bit manipulation to do two compares at once.  For example:
8358     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
8359     // TODO: This could be extended to merge any 2 cases in switches with 3
8360     // cases.
8361     // TODO: Handle cases where W.CaseBB != SwitchBB.
8362     CaseCluster &Small = *W.FirstCluster;
8363     CaseCluster &Big = *W.LastCluster;
8364 
8365     if (Small.Low == Small.High && Big.Low == Big.High &&
8366         Small.MBB == Big.MBB) {
8367       const APInt &SmallValue = Small.Low->getValue();
8368       const APInt &BigValue = Big.Low->getValue();
8369 
8370       // Check that there is only one bit different.
8371       APInt CommonBit = BigValue ^ SmallValue;
8372       if (CommonBit.isPowerOf2()) {
8373         SDValue CondLHS = getValue(Cond);
8374         EVT VT = CondLHS.getValueType();
8375         SDLoc DL = getCurSDLoc();
8376 
8377         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
8378                                  DAG.getConstant(CommonBit, DL, VT));
8379         SDValue Cond = DAG.getSetCC(
8380             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
8381             ISD::SETEQ);
8382 
8383         // Update successor info.
8384         // Both Small and Big will jump to Small.BB, so we sum up the
8385         // probabilities.
8386         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
8387         if (BPI)
8388           addSuccessorWithProb(
8389               SwitchMBB, DefaultMBB,
8390               // The default destination is the first successor in IR.
8391               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
8392         else
8393           addSuccessorWithProb(SwitchMBB, DefaultMBB);
8394 
8395         // Insert the true branch.
8396         SDValue BrCond =
8397             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
8398                         DAG.getBasicBlock(Small.MBB));
8399         // Insert the false branch.
8400         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
8401                              DAG.getBasicBlock(DefaultMBB));
8402 
8403         DAG.setRoot(BrCond);
8404         return;
8405       }
8406     }
8407   }
8408 
8409   if (TM.getOptLevel() != CodeGenOpt::None) {
8410     // Order cases by probability so the most likely case will be checked first.
8411     std::sort(W.FirstCluster, W.LastCluster + 1,
8412               [](const CaseCluster &a, const CaseCluster &b) {
8413       return a.Prob > b.Prob;
8414     });
8415 
8416     // Rearrange the case blocks so that the last one falls through if possible
8417     // without without changing the order of probabilities.
8418     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
8419       --I;
8420       if (I->Prob > W.LastCluster->Prob)
8421         break;
8422       if (I->Kind == CC_Range && I->MBB == NextMBB) {
8423         std::swap(*I, *W.LastCluster);
8424         break;
8425       }
8426     }
8427   }
8428 
8429   // Compute total probability.
8430   BranchProbability DefaultProb = W.DefaultProb;
8431   BranchProbability UnhandledProbs = DefaultProb;
8432   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
8433     UnhandledProbs += I->Prob;
8434 
8435   MachineBasicBlock *CurMBB = W.MBB;
8436   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
8437     MachineBasicBlock *Fallthrough;
8438     if (I == W.LastCluster) {
8439       // For the last cluster, fall through to the default destination.
8440       Fallthrough = DefaultMBB;
8441     } else {
8442       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
8443       CurMF->insert(BBI, Fallthrough);
8444       // Put Cond in a virtual register to make it available from the new blocks.
8445       ExportFromCurrentBlock(Cond);
8446     }
8447     UnhandledProbs -= I->Prob;
8448 
8449     switch (I->Kind) {
8450       case CC_JumpTable: {
8451         // FIXME: Optimize away range check based on pivot comparisons.
8452         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
8453         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
8454 
8455         // The jump block hasn't been inserted yet; insert it here.
8456         MachineBasicBlock *JumpMBB = JT->MBB;
8457         CurMF->insert(BBI, JumpMBB);
8458 
8459         auto JumpProb = I->Prob;
8460         auto FallthroughProb = UnhandledProbs;
8461 
8462         // If the default statement is a target of the jump table, we evenly
8463         // distribute the default probability to successors of CurMBB. Also
8464         // update the probability on the edge from JumpMBB to Fallthrough.
8465         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
8466                                               SE = JumpMBB->succ_end();
8467              SI != SE; ++SI) {
8468           if (*SI == DefaultMBB) {
8469             JumpProb += DefaultProb / 2;
8470             FallthroughProb -= DefaultProb / 2;
8471             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
8472             JumpMBB->normalizeSuccProbs();
8473             break;
8474           }
8475         }
8476 
8477         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
8478         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
8479         CurMBB->normalizeSuccProbs();
8480 
8481         // The jump table header will be inserted in our current block, do the
8482         // range check, and fall through to our fallthrough block.
8483         JTH->HeaderBB = CurMBB;
8484         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
8485 
8486         // If we're in the right place, emit the jump table header right now.
8487         if (CurMBB == SwitchMBB) {
8488           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
8489           JTH->Emitted = true;
8490         }
8491         break;
8492       }
8493       case CC_BitTests: {
8494         // FIXME: Optimize away range check based on pivot comparisons.
8495         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
8496 
8497         // The bit test blocks haven't been inserted yet; insert them here.
8498         for (BitTestCase &BTC : BTB->Cases)
8499           CurMF->insert(BBI, BTC.ThisBB);
8500 
8501         // Fill in fields of the BitTestBlock.
8502         BTB->Parent = CurMBB;
8503         BTB->Default = Fallthrough;
8504 
8505         BTB->DefaultProb = UnhandledProbs;
8506         // If the cases in bit test don't form a contiguous range, we evenly
8507         // distribute the probability on the edge to Fallthrough to two
8508         // successors of CurMBB.
8509         if (!BTB->ContiguousRange) {
8510           BTB->Prob += DefaultProb / 2;
8511           BTB->DefaultProb -= DefaultProb / 2;
8512         }
8513 
8514         // If we're in the right place, emit the bit test header right now.
8515         if (CurMBB == SwitchMBB) {
8516           visitBitTestHeader(*BTB, SwitchMBB);
8517           BTB->Emitted = true;
8518         }
8519         break;
8520       }
8521       case CC_Range: {
8522         const Value *RHS, *LHS, *MHS;
8523         ISD::CondCode CC;
8524         if (I->Low == I->High) {
8525           // Check Cond == I->Low.
8526           CC = ISD::SETEQ;
8527           LHS = Cond;
8528           RHS=I->Low;
8529           MHS = nullptr;
8530         } else {
8531           // Check I->Low <= Cond <= I->High.
8532           CC = ISD::SETLE;
8533           LHS = I->Low;
8534           MHS = Cond;
8535           RHS = I->High;
8536         }
8537 
8538         // The false probability is the sum of all unhandled cases.
8539         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Prob,
8540                      UnhandledProbs);
8541 
8542         if (CurMBB == SwitchMBB)
8543           visitSwitchCase(CB, SwitchMBB);
8544         else
8545           SwitchCases.push_back(CB);
8546 
8547         break;
8548       }
8549     }
8550     CurMBB = Fallthrough;
8551   }
8552 }
8553 
8554 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
8555                                               CaseClusterIt First,
8556                                               CaseClusterIt Last) {
8557   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
8558     if (X.Prob != CC.Prob)
8559       return X.Prob > CC.Prob;
8560 
8561     // Ties are broken by comparing the case value.
8562     return X.Low->getValue().slt(CC.Low->getValue());
8563   });
8564 }
8565 
8566 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
8567                                         const SwitchWorkListItem &W,
8568                                         Value *Cond,
8569                                         MachineBasicBlock *SwitchMBB) {
8570   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
8571          "Clusters not sorted?");
8572 
8573   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
8574 
8575   // Balance the tree based on branch probabilities to create a near-optimal (in
8576   // terms of search time given key frequency) binary search tree. See e.g. Kurt
8577   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
8578   CaseClusterIt LastLeft = W.FirstCluster;
8579   CaseClusterIt FirstRight = W.LastCluster;
8580   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
8581   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
8582 
8583   // Move LastLeft and FirstRight towards each other from opposite directions to
8584   // find a partitioning of the clusters which balances the probability on both
8585   // sides. If LeftProb and RightProb are equal, alternate which side is
8586   // taken to ensure 0-probability nodes are distributed evenly.
8587   unsigned I = 0;
8588   while (LastLeft + 1 < FirstRight) {
8589     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
8590       LeftProb += (++LastLeft)->Prob;
8591     else
8592       RightProb += (--FirstRight)->Prob;
8593     I++;
8594   }
8595 
8596   for (;;) {
8597     // Our binary search tree differs from a typical BST in that ours can have up
8598     // to three values in each leaf. The pivot selection above doesn't take that
8599     // into account, which means the tree might require more nodes and be less
8600     // efficient. We compensate for this here.
8601 
8602     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
8603     unsigned NumRight = W.LastCluster - FirstRight + 1;
8604 
8605     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
8606       // If one side has less than 3 clusters, and the other has more than 3,
8607       // consider taking a cluster from the other side.
8608 
8609       if (NumLeft < NumRight) {
8610         // Consider moving the first cluster on the right to the left side.
8611         CaseCluster &CC = *FirstRight;
8612         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8613         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8614         if (LeftSideRank <= RightSideRank) {
8615           // Moving the cluster to the left does not demote it.
8616           ++LastLeft;
8617           ++FirstRight;
8618           continue;
8619         }
8620       } else {
8621         assert(NumRight < NumLeft);
8622         // Consider moving the last element on the left to the right side.
8623         CaseCluster &CC = *LastLeft;
8624         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8625         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8626         if (RightSideRank <= LeftSideRank) {
8627           // Moving the cluster to the right does not demot it.
8628           --LastLeft;
8629           --FirstRight;
8630           continue;
8631         }
8632       }
8633     }
8634     break;
8635   }
8636 
8637   assert(LastLeft + 1 == FirstRight);
8638   assert(LastLeft >= W.FirstCluster);
8639   assert(FirstRight <= W.LastCluster);
8640 
8641   // Use the first element on the right as pivot since we will make less-than
8642   // comparisons against it.
8643   CaseClusterIt PivotCluster = FirstRight;
8644   assert(PivotCluster > W.FirstCluster);
8645   assert(PivotCluster <= W.LastCluster);
8646 
8647   CaseClusterIt FirstLeft = W.FirstCluster;
8648   CaseClusterIt LastRight = W.LastCluster;
8649 
8650   const ConstantInt *Pivot = PivotCluster->Low;
8651 
8652   // New blocks will be inserted immediately after the current one.
8653   MachineFunction::iterator BBI(W.MBB);
8654   ++BBI;
8655 
8656   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
8657   // we can branch to its destination directly if it's squeezed exactly in
8658   // between the known lower bound and Pivot - 1.
8659   MachineBasicBlock *LeftMBB;
8660   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
8661       FirstLeft->Low == W.GE &&
8662       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
8663     LeftMBB = FirstLeft->MBB;
8664   } else {
8665     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8666     FuncInfo.MF->insert(BBI, LeftMBB);
8667     WorkList.push_back(
8668         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
8669     // Put Cond in a virtual register to make it available from the new blocks.
8670     ExportFromCurrentBlock(Cond);
8671   }
8672 
8673   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
8674   // single cluster, RHS.Low == Pivot, and we can branch to its destination
8675   // directly if RHS.High equals the current upper bound.
8676   MachineBasicBlock *RightMBB;
8677   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
8678       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
8679     RightMBB = FirstRight->MBB;
8680   } else {
8681     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8682     FuncInfo.MF->insert(BBI, RightMBB);
8683     WorkList.push_back(
8684         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
8685     // Put Cond in a virtual register to make it available from the new blocks.
8686     ExportFromCurrentBlock(Cond);
8687   }
8688 
8689   // Create the CaseBlock record that will be used to lower the branch.
8690   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
8691                LeftProb, RightProb);
8692 
8693   if (W.MBB == SwitchMBB)
8694     visitSwitchCase(CB, SwitchMBB);
8695   else
8696     SwitchCases.push_back(CB);
8697 }
8698 
8699 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
8700   // Extract cases from the switch.
8701   BranchProbabilityInfo *BPI = FuncInfo.BPI;
8702   CaseClusterVector Clusters;
8703   Clusters.reserve(SI.getNumCases());
8704   for (auto I : SI.cases()) {
8705     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
8706     const ConstantInt *CaseVal = I.getCaseValue();
8707     BranchProbability Prob =
8708         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
8709             : BranchProbability(1, SI.getNumCases() + 1);
8710     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
8711   }
8712 
8713   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
8714 
8715   // Cluster adjacent cases with the same destination. We do this at all
8716   // optimization levels because it's cheap to do and will make codegen faster
8717   // if there are many clusters.
8718   sortAndRangeify(Clusters);
8719 
8720   if (TM.getOptLevel() != CodeGenOpt::None) {
8721     // Replace an unreachable default with the most popular destination.
8722     // FIXME: Exploit unreachable default more aggressively.
8723     bool UnreachableDefault =
8724         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
8725     if (UnreachableDefault && !Clusters.empty()) {
8726       DenseMap<const BasicBlock *, unsigned> Popularity;
8727       unsigned MaxPop = 0;
8728       const BasicBlock *MaxBB = nullptr;
8729       for (auto I : SI.cases()) {
8730         const BasicBlock *BB = I.getCaseSuccessor();
8731         if (++Popularity[BB] > MaxPop) {
8732           MaxPop = Popularity[BB];
8733           MaxBB = BB;
8734         }
8735       }
8736       // Set new default.
8737       assert(MaxPop > 0 && MaxBB);
8738       DefaultMBB = FuncInfo.MBBMap[MaxBB];
8739 
8740       // Remove cases that were pointing to the destination that is now the
8741       // default.
8742       CaseClusterVector New;
8743       New.reserve(Clusters.size());
8744       for (CaseCluster &CC : Clusters) {
8745         if (CC.MBB != DefaultMBB)
8746           New.push_back(CC);
8747       }
8748       Clusters = std::move(New);
8749     }
8750   }
8751 
8752   // If there is only the default destination, jump there directly.
8753   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
8754   if (Clusters.empty()) {
8755     SwitchMBB->addSuccessor(DefaultMBB);
8756     if (DefaultMBB != NextBlock(SwitchMBB)) {
8757       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
8758                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
8759     }
8760     return;
8761   }
8762 
8763   findJumpTables(Clusters, &SI, DefaultMBB);
8764   findBitTestClusters(Clusters, &SI);
8765 
8766   DEBUG({
8767     dbgs() << "Case clusters: ";
8768     for (const CaseCluster &C : Clusters) {
8769       if (C.Kind == CC_JumpTable) dbgs() << "JT:";
8770       if (C.Kind == CC_BitTests) dbgs() << "BT:";
8771 
8772       C.Low->getValue().print(dbgs(), true);
8773       if (C.Low != C.High) {
8774         dbgs() << '-';
8775         C.High->getValue().print(dbgs(), true);
8776       }
8777       dbgs() << ' ';
8778     }
8779     dbgs() << '\n';
8780   });
8781 
8782   assert(!Clusters.empty());
8783   SwitchWorkList WorkList;
8784   CaseClusterIt First = Clusters.begin();
8785   CaseClusterIt Last = Clusters.end() - 1;
8786   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
8787   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
8788 
8789   while (!WorkList.empty()) {
8790     SwitchWorkListItem W = WorkList.back();
8791     WorkList.pop_back();
8792     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
8793 
8794     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) {
8795       // For optimized builds, lower large range as a balanced binary tree.
8796       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
8797       continue;
8798     }
8799 
8800     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
8801   }
8802 }
8803