3a11277c473f390d71a599273d5051e3ebaf55e6
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuilder.cpp
1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/FastISel.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/GCMetadata.h"
27 #include "llvm/CodeGen/GCStrategy.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/StackMaps.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/DebugInfo.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/InlineAsm.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/LLVMContext.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetFrameLowering.h"
55 #include "llvm/Target/TargetInstrInfo.h"
56 #include "llvm/Target/TargetIntrinsicInfo.h"
57 #include "llvm/Target/TargetLibraryInfo.h"
58 #include "llvm/Target/TargetLowering.h"
59 #include "llvm/Target/TargetOptions.h"
60 #include "llvm/Target/TargetSelectionDAGInfo.h"
61 #include "llvm/Target/TargetSubtargetInfo.h"
62 #include <algorithm>
63 using namespace llvm;
64
65 #define DEBUG_TYPE "isel"
66
67 /// LimitFloatPrecision - Generate low-precision inline sequences for
68 /// some float libcalls (6, 8 or 12 bits).
69 static unsigned LimitFloatPrecision;
70
71 static cl::opt<unsigned, true>
72 LimitFPPrecision("limit-float-precision",
73                  cl::desc("Generate low-precision inline sequences "
74                           "for some float libcalls"),
75                  cl::location(LimitFloatPrecision),
76                  cl::init(0));
77
78 // Limit the width of DAG chains. This is important in general to prevent
79 // prevent DAG-based analysis from blowing up. For example, alias analysis and
80 // load clustering may not complete in reasonable time. It is difficult to
81 // recognize and avoid this situation within each individual analysis, and
82 // future analyses are likely to have the same behavior. Limiting DAG width is
83 // the safe approach, and will be especially important with global DAGs.
84 //
85 // MaxParallelChains default is arbitrarily high to avoid affecting
86 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
87 // sequence over this should have been converted to llvm.memcpy by the
88 // frontend. It easy to induce this behavior with .ll code such as:
89 // %buffer = alloca [4096 x i8]
90 // %data = load [4096 x i8]* %argPtr
91 // store [4096 x i8] %data, [4096 x i8]* %buffer
92 static const unsigned MaxParallelChains = 64;
93
94 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
95                                       const SDValue *Parts, unsigned NumParts,
96                                       MVT PartVT, EVT ValueVT, const Value *V);
97
98 /// getCopyFromParts - Create a value that contains the specified legal parts
99 /// combined into the value they represent.  If the parts combine to a type
100 /// larger then ValueVT then AssertOp can be used to specify whether the extra
101 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
102 /// (ISD::AssertSext).
103 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
104                                 const SDValue *Parts,
105                                 unsigned NumParts, MVT PartVT, EVT ValueVT,
106                                 const Value *V,
107                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
108   if (ValueVT.isVector())
109     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
110                                   PartVT, ValueVT, V);
111
112   assert(NumParts > 0 && "No parts to assemble!");
113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
114   SDValue Val = Parts[0];
115
116   if (NumParts > 1) {
117     // Assemble the value from multiple parts.
118     if (ValueVT.isInteger()) {
119       unsigned PartBits = PartVT.getSizeInBits();
120       unsigned ValueBits = ValueVT.getSizeInBits();
121
122       // Assemble the power of 2 part.
123       unsigned RoundParts = NumParts & (NumParts - 1) ?
124         1 << Log2_32(NumParts) : NumParts;
125       unsigned RoundBits = PartBits * RoundParts;
126       EVT RoundVT = RoundBits == ValueBits ?
127         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
128       SDValue Lo, Hi;
129
130       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
131
132       if (RoundParts > 2) {
133         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
134                               PartVT, HalfVT, V);
135         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
136                               RoundParts / 2, PartVT, HalfVT, V);
137       } else {
138         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
139         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
140       }
141
142       if (TLI.isBigEndian())
143         std::swap(Lo, Hi);
144
145       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
146
147       if (RoundParts < NumParts) {
148         // Assemble the trailing non-power-of-2 part.
149         unsigned OddParts = NumParts - RoundParts;
150         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
151         Hi = getCopyFromParts(DAG, DL,
152                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
153
154         // Combine the round and odd parts.
155         Lo = Val;
156         if (TLI.isBigEndian())
157           std::swap(Lo, Hi);
158         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
159         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
160         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
161                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
162                                          TLI.getPointerTy()));
163         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
164         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
165       }
166     } else if (PartVT.isFloatingPoint()) {
167       // FP split into multiple FP parts (for ppcf128)
168       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
169              "Unexpected split");
170       SDValue Lo, Hi;
171       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
172       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
173       if (TLI.hasBigEndianPartOrdering(ValueVT))
174         std::swap(Lo, Hi);
175       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
176     } else {
177       // FP split into integer parts (soft fp)
178       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
179              !PartVT.isVector() && "Unexpected split");
180       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
181       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
182     }
183   }
184
185   // There is now one part, held in Val.  Correct it to match ValueVT.
186   EVT PartEVT = Val.getValueType();
187
188   if (PartEVT == ValueVT)
189     return Val;
190
191   if (PartEVT.isInteger() && ValueVT.isInteger()) {
192     if (ValueVT.bitsLT(PartEVT)) {
193       // For a truncate, see if we have any information to
194       // indicate whether the truncated bits will always be
195       // zero or sign-extension.
196       if (AssertOp != ISD::DELETED_NODE)
197         Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
198                           DAG.getValueType(ValueVT));
199       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
200     }
201     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
202   }
203
204   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
205     // FP_ROUND's are always exact here.
206     if (ValueVT.bitsLT(Val.getValueType()))
207       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
208                          DAG.getTargetConstant(1, TLI.getPointerTy()));
209
210     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
211   }
212
213   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
214     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
215
216   llvm_unreachable("Unknown mismatch!");
217 }
218
219 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
220                                               const Twine &ErrMsg) {
221   const Instruction *I = dyn_cast_or_null<Instruction>(V);
222   if (!V)
223     return Ctx.emitError(ErrMsg);
224
225   const char *AsmError = ", possible invalid constraint for vector type";
226   if (const CallInst *CI = dyn_cast<CallInst>(I))
227     if (isa<InlineAsm>(CI->getCalledValue()))
228       return Ctx.emitError(I, ErrMsg + AsmError);
229
230   return Ctx.emitError(I, ErrMsg);
231 }
232
233 /// getCopyFromPartsVector - Create a value that contains the specified legal
234 /// parts combined into the value they represent.  If the parts combine to a
235 /// type larger then ValueVT then AssertOp can be used to specify whether the
236 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
237 /// ValueVT (ISD::AssertSext).
238 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
239                                       const SDValue *Parts, unsigned NumParts,
240                                       MVT PartVT, EVT ValueVT, const Value *V) {
241   assert(ValueVT.isVector() && "Not a vector value");
242   assert(NumParts > 0 && "No parts to assemble!");
243   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
244   SDValue Val = Parts[0];
245
246   // Handle a multi-element vector.
247   if (NumParts > 1) {
248     EVT IntermediateVT;
249     MVT RegisterVT;
250     unsigned NumIntermediates;
251     unsigned NumRegs =
252     TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
253                                NumIntermediates, RegisterVT);
254     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
255     NumParts = NumRegs; // Silence a compiler warning.
256     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
257     assert(RegisterVT == Parts[0].getSimpleValueType() &&
258            "Part type doesn't match part!");
259
260     // Assemble the parts into intermediate operands.
261     SmallVector<SDValue, 8> Ops(NumIntermediates);
262     if (NumIntermediates == NumParts) {
263       // If the register was not expanded, truncate or copy the value,
264       // as appropriate.
265       for (unsigned i = 0; i != NumParts; ++i)
266         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
267                                   PartVT, IntermediateVT, V);
268     } else if (NumParts > 0) {
269       // If the intermediate type was expanded, build the intermediate
270       // operands from the parts.
271       assert(NumParts % NumIntermediates == 0 &&
272              "Must expand into a divisible number of parts!");
273       unsigned Factor = NumParts / NumIntermediates;
274       for (unsigned i = 0; i != NumIntermediates; ++i)
275         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
276                                   PartVT, IntermediateVT, V);
277     }
278
279     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
280     // intermediate operands.
281     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
282                                                 : ISD::BUILD_VECTOR,
283                       DL, ValueVT, Ops);
284   }
285
286   // There is now one part, held in Val.  Correct it to match ValueVT.
287   EVT PartEVT = Val.getValueType();
288
289   if (PartEVT == ValueVT)
290     return Val;
291
292   if (PartEVT.isVector()) {
293     // If the element type of the source/dest vectors are the same, but the
294     // parts vector has more elements than the value vector, then we have a
295     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
296     // elements we want.
297     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
298       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
299              "Cannot narrow, it would be a lossy transformation");
300       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
301                          DAG.getConstant(0, TLI.getVectorIdxTy()));
302     }
303
304     // Vector/Vector bitcast.
305     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
306       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
307
308     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
309       "Cannot handle this kind of promotion");
310     // Promoted vector extract
311     bool Smaller = ValueVT.bitsLE(PartEVT);
312     return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
313                        DL, ValueVT, Val);
314
315   }
316
317   // Trivial bitcast if the types are the same size and the destination
318   // vector type is legal.
319   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
320       TLI.isTypeLegal(ValueVT))
321     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
322
323   // Handle cases such as i8 -> <1 x i1>
324   if (ValueVT.getVectorNumElements() != 1) {
325     diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
326                                       "non-trivial scalar-to-vector conversion");
327     return DAG.getUNDEF(ValueVT);
328   }
329
330   if (ValueVT.getVectorNumElements() == 1 &&
331       ValueVT.getVectorElementType() != PartEVT) {
332     bool Smaller = ValueVT.bitsLE(PartEVT);
333     Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
334                        DL, ValueVT.getScalarType(), Val);
335   }
336
337   return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
338 }
339
340 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
341                                  SDValue Val, SDValue *Parts, unsigned NumParts,
342                                  MVT PartVT, const Value *V);
343
344 /// getCopyToParts - Create a series of nodes that contain the specified value
345 /// split into legal parts.  If the parts contain more bits than Val, then, for
346 /// integers, ExtendKind can be used to specify how to generate the extra bits.
347 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
348                            SDValue Val, SDValue *Parts, unsigned NumParts,
349                            MVT PartVT, const Value *V,
350                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
351   EVT ValueVT = Val.getValueType();
352
353   // Handle the vector case separately.
354   if (ValueVT.isVector())
355     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
356
357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
358   unsigned PartBits = PartVT.getSizeInBits();
359   unsigned OrigNumParts = NumParts;
360   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
361
362   if (NumParts == 0)
363     return;
364
365   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
366   EVT PartEVT = PartVT;
367   if (PartEVT == ValueVT) {
368     assert(NumParts == 1 && "No-op copy with multiple parts!");
369     Parts[0] = Val;
370     return;
371   }
372
373   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
374     // If the parts cover more bits than the value has, promote the value.
375     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
376       assert(NumParts == 1 && "Do not know what to promote to!");
377       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
378     } else {
379       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
380              ValueVT.isInteger() &&
381              "Unknown mismatch!");
382       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
383       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
384       if (PartVT == MVT::x86mmx)
385         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
386     }
387   } else if (PartBits == ValueVT.getSizeInBits()) {
388     // Different types of the same size.
389     assert(NumParts == 1 && PartEVT != ValueVT);
390     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
391   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
392     // If the parts cover less bits than value has, truncate the value.
393     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
394            ValueVT.isInteger() &&
395            "Unknown mismatch!");
396     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
397     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
398     if (PartVT == MVT::x86mmx)
399       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
400   }
401
402   // The value may have changed - recompute ValueVT.
403   ValueVT = Val.getValueType();
404   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
405          "Failed to tile the value with PartVT!");
406
407   if (NumParts == 1) {
408     if (PartEVT != ValueVT)
409       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
410                                         "scalar-to-vector conversion failed");
411
412     Parts[0] = Val;
413     return;
414   }
415
416   // Expand the value into multiple parts.
417   if (NumParts & (NumParts - 1)) {
418     // The number of parts is not a power of 2.  Split off and copy the tail.
419     assert(PartVT.isInteger() && ValueVT.isInteger() &&
420            "Do not know what to expand to!");
421     unsigned RoundParts = 1 << Log2_32(NumParts);
422     unsigned RoundBits = RoundParts * PartBits;
423     unsigned OddParts = NumParts - RoundParts;
424     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
425                                  DAG.getIntPtrConstant(RoundBits));
426     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
427
428     if (TLI.isBigEndian())
429       // The odd parts were reversed by getCopyToParts - unreverse them.
430       std::reverse(Parts + RoundParts, Parts + NumParts);
431
432     NumParts = RoundParts;
433     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
434     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
435   }
436
437   // The number of parts is a power of 2.  Repeatedly bisect the value using
438   // EXTRACT_ELEMENT.
439   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
440                          EVT::getIntegerVT(*DAG.getContext(),
441                                            ValueVT.getSizeInBits()),
442                          Val);
443
444   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
445     for (unsigned i = 0; i < NumParts; i += StepSize) {
446       unsigned ThisBits = StepSize * PartBits / 2;
447       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
448       SDValue &Part0 = Parts[i];
449       SDValue &Part1 = Parts[i+StepSize/2];
450
451       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
452                           ThisVT, Part0, DAG.getIntPtrConstant(1));
453       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
454                           ThisVT, Part0, DAG.getIntPtrConstant(0));
455
456       if (ThisBits == PartBits && ThisVT != PartVT) {
457         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
458         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
459       }
460     }
461   }
462
463   if (TLI.isBigEndian())
464     std::reverse(Parts, Parts + OrigNumParts);
465 }
466
467
468 /// getCopyToPartsVector - Create a series of nodes that contain the specified
469 /// value split into legal parts.
470 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
471                                  SDValue Val, SDValue *Parts, unsigned NumParts,
472                                  MVT PartVT, const Value *V) {
473   EVT ValueVT = Val.getValueType();
474   assert(ValueVT.isVector() && "Not a vector");
475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
476
477   if (NumParts == 1) {
478     EVT PartEVT = PartVT;
479     if (PartEVT == ValueVT) {
480       // Nothing to do.
481     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
482       // Bitconvert vector->vector case.
483       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
484     } else if (PartVT.isVector() &&
485                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
486                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
487       EVT ElementVT = PartVT.getVectorElementType();
488       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
489       // undef elements.
490       SmallVector<SDValue, 16> Ops;
491       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
492         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
493                                   ElementVT, Val, DAG.getConstant(i,
494                                                   TLI.getVectorIdxTy())));
495
496       for (unsigned i = ValueVT.getVectorNumElements(),
497            e = PartVT.getVectorNumElements(); i != e; ++i)
498         Ops.push_back(DAG.getUNDEF(ElementVT));
499
500       Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
501
502       // FIXME: Use CONCAT for 2x -> 4x.
503
504       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
505       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
506     } else if (PartVT.isVector() &&
507                PartEVT.getVectorElementType().bitsGE(
508                  ValueVT.getVectorElementType()) &&
509                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
510
511       // Promoted vector extract
512       bool Smaller = PartEVT.bitsLE(ValueVT);
513       Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
514                         DL, PartVT, Val);
515     } else{
516       // Vector -> scalar conversion.
517       assert(ValueVT.getVectorNumElements() == 1 &&
518              "Only trivial vector-to-scalar conversions should get here!");
519       Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
520                         PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
521
522       bool Smaller = ValueVT.bitsLE(PartVT);
523       Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
524                          DL, PartVT, Val);
525     }
526
527     Parts[0] = Val;
528     return;
529   }
530
531   // Handle a multi-element vector.
532   EVT IntermediateVT;
533   MVT RegisterVT;
534   unsigned NumIntermediates;
535   unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
536                                                 IntermediateVT,
537                                                 NumIntermediates, RegisterVT);
538   unsigned NumElements = ValueVT.getVectorNumElements();
539
540   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
541   NumParts = NumRegs; // Silence a compiler warning.
542   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
543
544   // Split the vector into intermediate operands.
545   SmallVector<SDValue, 8> Ops(NumIntermediates);
546   for (unsigned i = 0; i != NumIntermediates; ++i) {
547     if (IntermediateVT.isVector())
548       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
549                            IntermediateVT, Val,
550                    DAG.getConstant(i * (NumElements / NumIntermediates),
551                                    TLI.getVectorIdxTy()));
552     else
553       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
554                            IntermediateVT, Val,
555                            DAG.getConstant(i, TLI.getVectorIdxTy()));
556   }
557
558   // Split the intermediate operands into legal parts.
559   if (NumParts == NumIntermediates) {
560     // If the register was not expanded, promote or copy the value,
561     // as appropriate.
562     for (unsigned i = 0; i != NumParts; ++i)
563       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
564   } else if (NumParts > 0) {
565     // If the intermediate type was expanded, split each the value into
566     // legal parts.
567     assert(NumParts % NumIntermediates == 0 &&
568            "Must expand into a divisible number of parts!");
569     unsigned Factor = NumParts / NumIntermediates;
570     for (unsigned i = 0; i != NumIntermediates; ++i)
571       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
572   }
573 }
574
575 namespace {
576   /// RegsForValue - This struct represents the registers (physical or virtual)
577   /// that a particular set of values is assigned, and the type information
578   /// about the value. The most common situation is to represent one value at a
579   /// time, but struct or array values are handled element-wise as multiple
580   /// values.  The splitting of aggregates is performed recursively, so that we
581   /// never have aggregate-typed registers. The values at this point do not
582   /// necessarily have legal types, so each value may require one or more
583   /// registers of some legal type.
584   ///
585   struct RegsForValue {
586     /// ValueVTs - The value types of the values, which may not be legal, and
587     /// may need be promoted or synthesized from one or more registers.
588     ///
589     SmallVector<EVT, 4> ValueVTs;
590
591     /// RegVTs - The value types of the registers. This is the same size as
592     /// ValueVTs and it records, for each value, what the type of the assigned
593     /// register or registers are. (Individual values are never synthesized
594     /// from more than one type of register.)
595     ///
596     /// With virtual registers, the contents of RegVTs is redundant with TLI's
597     /// getRegisterType member function, however when with physical registers
598     /// it is necessary to have a separate record of the types.
599     ///
600     SmallVector<MVT, 4> RegVTs;
601
602     /// Regs - This list holds the registers assigned to the values.
603     /// Each legal or promoted value requires one register, and each
604     /// expanded value requires multiple registers.
605     ///
606     SmallVector<unsigned, 4> Regs;
607
608     RegsForValue() {}
609
610     RegsForValue(const SmallVector<unsigned, 4> &regs,
611                  MVT regvt, EVT valuevt)
612       : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
613
614     RegsForValue(LLVMContext &Context, const TargetLowering &tli,
615                  unsigned Reg, Type *Ty) {
616       ComputeValueVTs(tli, Ty, ValueVTs);
617
618       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
619         EVT ValueVT = ValueVTs[Value];
620         unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
621         MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
622         for (unsigned i = 0; i != NumRegs; ++i)
623           Regs.push_back(Reg + i);
624         RegVTs.push_back(RegisterVT);
625         Reg += NumRegs;
626       }
627     }
628
629     /// append - Add the specified values to this one.
630     void append(const RegsForValue &RHS) {
631       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
632       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
633       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
634     }
635
636     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
637     /// this value and returns the result as a ValueVTs value.  This uses
638     /// Chain/Flag as the input and updates them for the output Chain/Flag.
639     /// If the Flag pointer is NULL, no flag is used.
640     SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
641                             SDLoc dl,
642                             SDValue &Chain, SDValue *Flag,
643                             const Value *V = nullptr) const;
644
645     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
646     /// specified value into the registers specified by this object.  This uses
647     /// Chain/Flag as the input and updates them for the output Chain/Flag.
648     /// If the Flag pointer is NULL, no flag is used.
649     void
650     getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
651                   SDValue *Flag, const Value *V,
652                   ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
653
654     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
655     /// operand list.  This adds the code marker, matching input operand index
656     /// (if applicable), and includes the number of values added into it.
657     void AddInlineAsmOperands(unsigned Kind,
658                               bool HasMatching, unsigned MatchingIdx,
659                               SelectionDAG &DAG,
660                               std::vector<SDValue> &Ops) const;
661   };
662 }
663
664 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
665 /// this value and returns the result as a ValueVT value.  This uses
666 /// Chain/Flag as the input and updates them for the output Chain/Flag.
667 /// If the Flag pointer is NULL, no flag is used.
668 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
669                                       FunctionLoweringInfo &FuncInfo,
670                                       SDLoc dl,
671                                       SDValue &Chain, SDValue *Flag,
672                                       const Value *V) const {
673   // A Value with type {} or [0 x %t] needs no registers.
674   if (ValueVTs.empty())
675     return SDValue();
676
677   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
678
679   // Assemble the legal parts into the final values.
680   SmallVector<SDValue, 4> Values(ValueVTs.size());
681   SmallVector<SDValue, 8> Parts;
682   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
683     // Copy the legal parts from the registers.
684     EVT ValueVT = ValueVTs[Value];
685     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
686     MVT RegisterVT = RegVTs[Value];
687
688     Parts.resize(NumRegs);
689     for (unsigned i = 0; i != NumRegs; ++i) {
690       SDValue P;
691       if (!Flag) {
692         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
693       } else {
694         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
695         *Flag = P.getValue(2);
696       }
697
698       Chain = P.getValue(1);
699       Parts[i] = P;
700
701       // If the source register was virtual and if we know something about it,
702       // add an assert node.
703       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
704           !RegisterVT.isInteger() || RegisterVT.isVector())
705         continue;
706
707       const FunctionLoweringInfo::LiveOutInfo *LOI =
708         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
709       if (!LOI)
710         continue;
711
712       unsigned RegSize = RegisterVT.getSizeInBits();
713       unsigned NumSignBits = LOI->NumSignBits;
714       unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
715
716       if (NumZeroBits == RegSize) {
717         // The current value is a zero.
718         // Explicitly express that as it would be easier for
719         // optimizations to kick in.
720         Parts[i] = DAG.getConstant(0, RegisterVT);
721         continue;
722       }
723
724       // FIXME: We capture more information than the dag can represent.  For
725       // now, just use the tightest assertzext/assertsext possible.
726       bool isSExt = true;
727       EVT FromVT(MVT::Other);
728       if (NumSignBits == RegSize)
729         isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
730       else if (NumZeroBits >= RegSize-1)
731         isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
732       else if (NumSignBits > RegSize-8)
733         isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
734       else if (NumZeroBits >= RegSize-8)
735         isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
736       else if (NumSignBits > RegSize-16)
737         isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
738       else if (NumZeroBits >= RegSize-16)
739         isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
740       else if (NumSignBits > RegSize-32)
741         isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
742       else if (NumZeroBits >= RegSize-32)
743         isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
744       else
745         continue;
746
747       // Add an assertion node.
748       assert(FromVT != MVT::Other);
749       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
750                              RegisterVT, P, DAG.getValueType(FromVT));
751     }
752
753     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
754                                      NumRegs, RegisterVT, ValueVT, V);
755     Part += NumRegs;
756     Parts.clear();
757   }
758
759   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
760 }
761
762 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
763 /// specified value into the registers specified by this object.  This uses
764 /// Chain/Flag as the input and updates them for the output Chain/Flag.
765 /// If the Flag pointer is NULL, no flag is used.
766 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
767                                  SDValue &Chain, SDValue *Flag, const Value *V,
768                                  ISD::NodeType PreferredExtendType) const {
769   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
770   ISD::NodeType ExtendKind = PreferredExtendType;
771
772   // Get the list of the values's legal parts.
773   unsigned NumRegs = Regs.size();
774   SmallVector<SDValue, 8> Parts(NumRegs);
775   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
776     EVT ValueVT = ValueVTs[Value];
777     unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
778     MVT RegisterVT = RegVTs[Value];
779
780     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
781       ExtendKind = ISD::ZERO_EXTEND;
782
783     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
784                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
785     Part += NumParts;
786   }
787
788   // Copy the parts into the registers.
789   SmallVector<SDValue, 8> Chains(NumRegs);
790   for (unsigned i = 0; i != NumRegs; ++i) {
791     SDValue Part;
792     if (!Flag) {
793       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
794     } else {
795       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
796       *Flag = Part.getValue(1);
797     }
798
799     Chains[i] = Part.getValue(0);
800   }
801
802   if (NumRegs == 1 || Flag)
803     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
804     // flagged to it. That is the CopyToReg nodes and the user are considered
805     // a single scheduling unit. If we create a TokenFactor and return it as
806     // chain, then the TokenFactor is both a predecessor (operand) of the
807     // user as well as a successor (the TF operands are flagged to the user).
808     // c1, f1 = CopyToReg
809     // c2, f2 = CopyToReg
810     // c3     = TokenFactor c1, c2
811     // ...
812     //        = op c3, ..., f2
813     Chain = Chains[NumRegs-1];
814   else
815     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
816 }
817
818 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
819 /// operand list.  This adds the code marker and includes the number of
820 /// values added into it.
821 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
822                                         unsigned MatchingIdx,
823                                         SelectionDAG &DAG,
824                                         std::vector<SDValue> &Ops) const {
825   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
826
827   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
828   if (HasMatching)
829     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
830   else if (!Regs.empty() &&
831            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
832     // Put the register class of the virtual registers in the flag word.  That
833     // way, later passes can recompute register class constraints for inline
834     // assembly as well as normal instructions.
835     // Don't do this for tied operands that can use the regclass information
836     // from the def.
837     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
838     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
839     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
840   }
841
842   SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
843   Ops.push_back(Res);
844
845   unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
846   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
847     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
848     MVT RegisterVT = RegVTs[Value];
849     for (unsigned i = 0; i != NumRegs; ++i) {
850       assert(Reg < Regs.size() && "Mismatch in # registers expected");
851       unsigned TheReg = Regs[Reg++];
852       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
853
854       if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
855         // If we clobbered the stack pointer, MFI should know about it.
856         assert(DAG.getMachineFunction().getFrameInfo()->
857             hasInlineAsmWithSPAdjust());
858       }
859     }
860   }
861 }
862
863 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
864                                const TargetLibraryInfo *li) {
865   AA = &aa;
866   GFI = gfi;
867   LibInfo = li;
868   DL = DAG.getSubtarget().getDataLayout();
869   Context = DAG.getContext();
870   LPadToCallSiteMap.clear();
871 }
872
873 /// clear - Clear out the current SelectionDAG and the associated
874 /// state and prepare this SelectionDAGBuilder object to be used
875 /// for a new block. This doesn't clear out information about
876 /// additional blocks that are needed to complete switch lowering
877 /// or PHI node updating; that information is cleared out as it is
878 /// consumed.
879 void SelectionDAGBuilder::clear() {
880   NodeMap.clear();
881   UnusedArgNodeMap.clear();
882   PendingLoads.clear();
883   PendingExports.clear();
884   CurInst = nullptr;
885   HasTailCall = false;
886   SDNodeOrder = LowestSDNodeOrder;
887 }
888
889 /// clearDanglingDebugInfo - Clear the dangling debug information
890 /// map. This function is separated from the clear so that debug
891 /// information that is dangling in a basic block can be properly
892 /// resolved in a different basic block. This allows the
893 /// SelectionDAG to resolve dangling debug information attached
894 /// to PHI nodes.
895 void SelectionDAGBuilder::clearDanglingDebugInfo() {
896   DanglingDebugInfoMap.clear();
897 }
898
899 /// getRoot - Return the current virtual root of the Selection DAG,
900 /// flushing any PendingLoad items. This must be done before emitting
901 /// a store or any other node that may need to be ordered after any
902 /// prior load instructions.
903 ///
904 SDValue SelectionDAGBuilder::getRoot() {
905   if (PendingLoads.empty())
906     return DAG.getRoot();
907
908   if (PendingLoads.size() == 1) {
909     SDValue Root = PendingLoads[0];
910     DAG.setRoot(Root);
911     PendingLoads.clear();
912     return Root;
913   }
914
915   // Otherwise, we have to make a token factor node.
916   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
917                              PendingLoads);
918   PendingLoads.clear();
919   DAG.setRoot(Root);
920   return Root;
921 }
922
923 /// getControlRoot - Similar to getRoot, but instead of flushing all the
924 /// PendingLoad items, flush all the PendingExports items. It is necessary
925 /// to do this before emitting a terminator instruction.
926 ///
927 SDValue SelectionDAGBuilder::getControlRoot() {
928   SDValue Root = DAG.getRoot();
929
930   if (PendingExports.empty())
931     return Root;
932
933   // Turn all of the CopyToReg chains into one factored node.
934   if (Root.getOpcode() != ISD::EntryToken) {
935     unsigned i = 0, e = PendingExports.size();
936     for (; i != e; ++i) {
937       assert(PendingExports[i].getNode()->getNumOperands() > 1);
938       if (PendingExports[i].getNode()->getOperand(0) == Root)
939         break;  // Don't add the root if we already indirectly depend on it.
940     }
941
942     if (i == e)
943       PendingExports.push_back(Root);
944   }
945
946   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
947                      PendingExports);
948   PendingExports.clear();
949   DAG.setRoot(Root);
950   return Root;
951 }
952
953 void SelectionDAGBuilder::visit(const Instruction &I) {
954   // Set up outgoing PHI node register values before emitting the terminator.
955   if (isa<TerminatorInst>(&I))
956     HandlePHINodesInSuccessorBlocks(I.getParent());
957
958   ++SDNodeOrder;
959
960   CurInst = &I;
961
962   visit(I.getOpcode(), I);
963
964   if (!isa<TerminatorInst>(&I) && !HasTailCall)
965     CopyToExportRegsIfNeeded(&I);
966
967   CurInst = nullptr;
968 }
969
970 void SelectionDAGBuilder::visitPHI(const PHINode &) {
971   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
972 }
973
974 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
975   // Note: this doesn't use InstVisitor, because it has to work with
976   // ConstantExpr's in addition to instructions.
977   switch (Opcode) {
978   default: llvm_unreachable("Unknown instruction type encountered!");
979     // Build the switch statement using the Instruction.def file.
980 #define HANDLE_INST(NUM, OPCODE, CLASS) \
981     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
982 #include "llvm/IR/Instruction.def"
983   }
984 }
985
986 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
987 // generate the debug data structures now that we've seen its definition.
988 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
989                                                    SDValue Val) {
990   DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
991   if (DDI.getDI()) {
992     const DbgValueInst *DI = DDI.getDI();
993     DebugLoc dl = DDI.getdl();
994     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
995     MDNode *Variable = DI->getVariable();
996     MDNode *Expr = DI->getExpression();
997     uint64_t Offset = DI->getOffset();
998     // A dbg.value for an alloca is always indirect.
999     bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
1000     SDDbgValue *SDV;
1001     if (Val.getNode()) {
1002       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, Offset, IsIndirect,
1003                                     Val)) {
1004         SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
1005                               IsIndirect, Offset, dl, DbgSDNodeOrder);
1006         DAG.AddDbgValue(SDV, Val.getNode(), false);
1007       }
1008     } else
1009       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1010     DanglingDebugInfoMap[V] = DanglingDebugInfo();
1011   }
1012 }
1013
1014 /// getValue - Return an SDValue for the given Value.
1015 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1016   // If we already have an SDValue for this value, use it. It's important
1017   // to do this first, so that we don't create a CopyFromReg if we already
1018   // have a regular SDValue.
1019   SDValue &N = NodeMap[V];
1020   if (N.getNode()) return N;
1021
1022   // If there's a virtual register allocated and initialized for this
1023   // value, use it.
1024   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1025   if (It != FuncInfo.ValueMap.end()) {
1026     unsigned InReg = It->second;
1027     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
1028                      V->getType());
1029     SDValue Chain = DAG.getEntryNode();
1030     N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1031     resolveDanglingDebugInfo(V, N);
1032     return N;
1033   }
1034
1035   // Otherwise create a new SDValue and remember it.
1036   SDValue Val = getValueImpl(V);
1037   NodeMap[V] = Val;
1038   resolveDanglingDebugInfo(V, Val);
1039   return Val;
1040 }
1041
1042 /// getNonRegisterValue - Return an SDValue for the given Value, but
1043 /// don't look in FuncInfo.ValueMap for a virtual register.
1044 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1045   // If we already have an SDValue for this value, use it.
1046   SDValue &N = NodeMap[V];
1047   if (N.getNode()) return N;
1048
1049   // Otherwise create a new SDValue and remember it.
1050   SDValue Val = getValueImpl(V);
1051   NodeMap[V] = Val;
1052   resolveDanglingDebugInfo(V, Val);
1053   return Val;
1054 }
1055
1056 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1057 /// Create an SDValue for the given value.
1058 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1059   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1060
1061   if (const Constant *C = dyn_cast<Constant>(V)) {
1062     EVT VT = TLI.getValueType(V->getType(), true);
1063
1064     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1065       return DAG.getConstant(*CI, VT);
1066
1067     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1068       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1069
1070     if (isa<ConstantPointerNull>(C)) {
1071       unsigned AS = V->getType()->getPointerAddressSpace();
1072       return DAG.getConstant(0, TLI.getPointerTy(AS));
1073     }
1074
1075     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1076       return DAG.getConstantFP(*CFP, VT);
1077
1078     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1079       return DAG.getUNDEF(VT);
1080
1081     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1082       visit(CE->getOpcode(), *CE);
1083       SDValue N1 = NodeMap[V];
1084       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1085       return N1;
1086     }
1087
1088     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1089       SmallVector<SDValue, 4> Constants;
1090       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1091            OI != OE; ++OI) {
1092         SDNode *Val = getValue(*OI).getNode();
1093         // If the operand is an empty aggregate, there are no values.
1094         if (!Val) continue;
1095         // Add each leaf value from the operand to the Constants list
1096         // to form a flattened list of all the values.
1097         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1098           Constants.push_back(SDValue(Val, i));
1099       }
1100
1101       return DAG.getMergeValues(Constants, getCurSDLoc());
1102     }
1103
1104     if (const ConstantDataSequential *CDS =
1105           dyn_cast<ConstantDataSequential>(C)) {
1106       SmallVector<SDValue, 4> Ops;
1107       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1108         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1109         // Add each leaf value from the operand to the Constants list
1110         // to form a flattened list of all the values.
1111         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1112           Ops.push_back(SDValue(Val, i));
1113       }
1114
1115       if (isa<ArrayType>(CDS->getType()))
1116         return DAG.getMergeValues(Ops, getCurSDLoc());
1117       return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1118                                       VT, Ops);
1119     }
1120
1121     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1122       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1123              "Unknown struct or array constant!");
1124
1125       SmallVector<EVT, 4> ValueVTs;
1126       ComputeValueVTs(TLI, C->getType(), ValueVTs);
1127       unsigned NumElts = ValueVTs.size();
1128       if (NumElts == 0)
1129         return SDValue(); // empty struct
1130       SmallVector<SDValue, 4> Constants(NumElts);
1131       for (unsigned i = 0; i != NumElts; ++i) {
1132         EVT EltVT = ValueVTs[i];
1133         if (isa<UndefValue>(C))
1134           Constants[i] = DAG.getUNDEF(EltVT);
1135         else if (EltVT.isFloatingPoint())
1136           Constants[i] = DAG.getConstantFP(0, EltVT);
1137         else
1138           Constants[i] = DAG.getConstant(0, EltVT);
1139       }
1140
1141       return DAG.getMergeValues(Constants, getCurSDLoc());
1142     }
1143
1144     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1145       return DAG.getBlockAddress(BA, VT);
1146
1147     VectorType *VecTy = cast<VectorType>(V->getType());
1148     unsigned NumElements = VecTy->getNumElements();
1149
1150     // Now that we know the number and type of the elements, get that number of
1151     // elements into the Ops array based on what kind of constant it is.
1152     SmallVector<SDValue, 16> Ops;
1153     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1154       for (unsigned i = 0; i != NumElements; ++i)
1155         Ops.push_back(getValue(CV->getOperand(i)));
1156     } else {
1157       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1158       EVT EltVT = TLI.getValueType(VecTy->getElementType());
1159
1160       SDValue Op;
1161       if (EltVT.isFloatingPoint())
1162         Op = DAG.getConstantFP(0, EltVT);
1163       else
1164         Op = DAG.getConstant(0, EltVT);
1165       Ops.assign(NumElements, Op);
1166     }
1167
1168     // Create a BUILD_VECTOR node.
1169     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1170   }
1171
1172   // If this is a static alloca, generate it as the frameindex instead of
1173   // computation.
1174   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1175     DenseMap<const AllocaInst*, int>::iterator SI =
1176       FuncInfo.StaticAllocaMap.find(AI);
1177     if (SI != FuncInfo.StaticAllocaMap.end())
1178       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1179   }
1180
1181   // If this is an instruction which fast-isel has deferred, select it now.
1182   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1183     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1184     RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1185     SDValue Chain = DAG.getEntryNode();
1186     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1187   }
1188
1189   llvm_unreachable("Can't get register for value!");
1190 }
1191
1192 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1194   SDValue Chain = getControlRoot();
1195   SmallVector<ISD::OutputArg, 8> Outs;
1196   SmallVector<SDValue, 8> OutVals;
1197
1198   if (!FuncInfo.CanLowerReturn) {
1199     unsigned DemoteReg = FuncInfo.DemoteRegister;
1200     const Function *F = I.getParent()->getParent();
1201
1202     // Emit a store of the return value through the virtual register.
1203     // Leave Outs empty so that LowerReturn won't try to load return
1204     // registers the usual way.
1205     SmallVector<EVT, 1> PtrValueVTs;
1206     ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1207                     PtrValueVTs);
1208
1209     SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1210     SDValue RetOp = getValue(I.getOperand(0));
1211
1212     SmallVector<EVT, 4> ValueVTs;
1213     SmallVector<uint64_t, 4> Offsets;
1214     ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1215     unsigned NumValues = ValueVTs.size();
1216
1217     SmallVector<SDValue, 4> Chains(NumValues);
1218     for (unsigned i = 0; i != NumValues; ++i) {
1219       SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1220                                 RetPtr.getValueType(), RetPtr,
1221                                 DAG.getIntPtrConstant(Offsets[i]));
1222       Chains[i] =
1223         DAG.getStore(Chain, getCurSDLoc(),
1224                      SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1225                      // FIXME: better loc info would be nice.
1226                      Add, MachinePointerInfo(), false, false, 0);
1227     }
1228
1229     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1230                         MVT::Other, Chains);
1231   } else if (I.getNumOperands() != 0) {
1232     SmallVector<EVT, 4> ValueVTs;
1233     ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1234     unsigned NumValues = ValueVTs.size();
1235     if (NumValues) {
1236       SDValue RetOp = getValue(I.getOperand(0));
1237       for (unsigned j = 0, f = NumValues; j != f; ++j) {
1238         EVT VT = ValueVTs[j];
1239
1240         ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1241
1242         const Function *F = I.getParent()->getParent();
1243         if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1244                                             Attribute::SExt))
1245           ExtendKind = ISD::SIGN_EXTEND;
1246         else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1247                                                  Attribute::ZExt))
1248           ExtendKind = ISD::ZERO_EXTEND;
1249
1250         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1251           VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
1252
1253         unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1254         MVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1255         SmallVector<SDValue, 4> Parts(NumParts);
1256         getCopyToParts(DAG, getCurSDLoc(),
1257                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1258                        &Parts[0], NumParts, PartVT, &I, ExtendKind);
1259
1260         // 'inreg' on function refers to return value
1261         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1262         if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1263                                             Attribute::InReg))
1264           Flags.setInReg();
1265
1266         // Propagate extension type if any
1267         if (ExtendKind == ISD::SIGN_EXTEND)
1268           Flags.setSExt();
1269         else if (ExtendKind == ISD::ZERO_EXTEND)
1270           Flags.setZExt();
1271
1272         for (unsigned i = 0; i < NumParts; ++i) {
1273           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1274                                         VT, /*isfixed=*/true, 0, 0));
1275           OutVals.push_back(Parts[i]);
1276         }
1277       }
1278     }
1279   }
1280
1281   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1282   CallingConv::ID CallConv =
1283     DAG.getMachineFunction().getFunction()->getCallingConv();
1284   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1285       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1286
1287   // Verify that the target's LowerReturn behaved as expected.
1288   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1289          "LowerReturn didn't return a valid chain!");
1290
1291   // Update the DAG with the new chain value resulting from return lowering.
1292   DAG.setRoot(Chain);
1293 }
1294
1295 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1296 /// created for it, emit nodes to copy the value into the virtual
1297 /// registers.
1298 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1299   // Skip empty types
1300   if (V->getType()->isEmptyTy())
1301     return;
1302
1303   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1304   if (VMI != FuncInfo.ValueMap.end()) {
1305     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1306     CopyValueToVirtualRegister(V, VMI->second);
1307   }
1308 }
1309
1310 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1311 /// the current basic block, add it to ValueMap now so that we'll get a
1312 /// CopyTo/FromReg.
1313 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1314   // No need to export constants.
1315   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1316
1317   // Already exported?
1318   if (FuncInfo.isExportedInst(V)) return;
1319
1320   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1321   CopyValueToVirtualRegister(V, Reg);
1322 }
1323
1324 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1325                                                      const BasicBlock *FromBB) {
1326   // The operands of the setcc have to be in this block.  We don't know
1327   // how to export them from some other block.
1328   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1329     // Can export from current BB.
1330     if (VI->getParent() == FromBB)
1331       return true;
1332
1333     // Is already exported, noop.
1334     return FuncInfo.isExportedInst(V);
1335   }
1336
1337   // If this is an argument, we can export it if the BB is the entry block or
1338   // if it is already exported.
1339   if (isa<Argument>(V)) {
1340     if (FromBB == &FromBB->getParent()->getEntryBlock())
1341       return true;
1342
1343     // Otherwise, can only export this if it is already exported.
1344     return FuncInfo.isExportedInst(V);
1345   }
1346
1347   // Otherwise, constants can always be exported.
1348   return true;
1349 }
1350
1351 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1352 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1353                                             const MachineBasicBlock *Dst) const {
1354   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1355   if (!BPI)
1356     return 0;
1357   const BasicBlock *SrcBB = Src->getBasicBlock();
1358   const BasicBlock *DstBB = Dst->getBasicBlock();
1359   return BPI->getEdgeWeight(SrcBB, DstBB);
1360 }
1361
1362 void SelectionDAGBuilder::
1363 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1364                        uint32_t Weight /* = 0 */) {
1365   if (!Weight)
1366     Weight = getEdgeWeight(Src, Dst);
1367   Src->addSuccessor(Dst, Weight);
1368 }
1369
1370
1371 static bool InBlock(const Value *V, const BasicBlock *BB) {
1372   if (const Instruction *I = dyn_cast<Instruction>(V))
1373     return I->getParent() == BB;
1374   return true;
1375 }
1376
1377 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1378 /// This function emits a branch and is used at the leaves of an OR or an
1379 /// AND operator tree.
1380 ///
1381 void
1382 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1383                                                   MachineBasicBlock *TBB,
1384                                                   MachineBasicBlock *FBB,
1385                                                   MachineBasicBlock *CurBB,
1386                                                   MachineBasicBlock *SwitchBB,
1387                                                   uint32_t TWeight,
1388                                                   uint32_t FWeight) {
1389   const BasicBlock *BB = CurBB->getBasicBlock();
1390
1391   // If the leaf of the tree is a comparison, merge the condition into
1392   // the caseblock.
1393   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1394     // The operands of the cmp have to be in this block.  We don't know
1395     // how to export them from some other block.  If this is the first block
1396     // of the sequence, no exporting is needed.
1397     if (CurBB == SwitchBB ||
1398         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1399          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1400       ISD::CondCode Condition;
1401       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1402         Condition = getICmpCondCode(IC->getPredicate());
1403       } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1404         Condition = getFCmpCondCode(FC->getPredicate());
1405         if (TM.Options.NoNaNsFPMath)
1406           Condition = getFCmpCodeWithoutNaN(Condition);
1407       } else {
1408         Condition = ISD::SETEQ; // silence warning.
1409         llvm_unreachable("Unknown compare instruction");
1410       }
1411
1412       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1413                    TBB, FBB, CurBB, TWeight, FWeight);
1414       SwitchCases.push_back(CB);
1415       return;
1416     }
1417   }
1418
1419   // Create a CaseBlock record representing this branch.
1420   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1421                nullptr, TBB, FBB, CurBB, TWeight, FWeight);
1422   SwitchCases.push_back(CB);
1423 }
1424
1425 /// Scale down both weights to fit into uint32_t.
1426 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1427   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1428   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1429   NewTrue = NewTrue / Scale;
1430   NewFalse = NewFalse / Scale;
1431 }
1432
1433 /// FindMergedConditions - If Cond is an expression like
1434 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1435                                                MachineBasicBlock *TBB,
1436                                                MachineBasicBlock *FBB,
1437                                                MachineBasicBlock *CurBB,
1438                                                MachineBasicBlock *SwitchBB,
1439                                                unsigned Opc, uint32_t TWeight,
1440                                                uint32_t FWeight) {
1441   // If this node is not part of the or/and tree, emit it as a branch.
1442   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1443   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1444       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1445       BOp->getParent() != CurBB->getBasicBlock() ||
1446       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1447       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1448     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1449                                  TWeight, FWeight);
1450     return;
1451   }
1452
1453   //  Create TmpBB after CurBB.
1454   MachineFunction::iterator BBI = CurBB;
1455   MachineFunction &MF = DAG.getMachineFunction();
1456   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1457   CurBB->getParent()->insert(++BBI, TmpBB);
1458
1459   if (Opc == Instruction::Or) {
1460     // Codegen X | Y as:
1461     // BB1:
1462     //   jmp_if_X TBB
1463     //   jmp TmpBB
1464     // TmpBB:
1465     //   jmp_if_Y TBB
1466     //   jmp FBB
1467     //
1468
1469     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1470     // The requirement is that
1471     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1472     //     = TrueProb for orignal BB.
1473     // Assuming the orignal weights are A and B, one choice is to set BB1's
1474     // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1475     // assumes that
1476     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1477     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1478     // TmpBB, but the math is more complicated.
1479
1480     uint64_t NewTrueWeight = TWeight;
1481     uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1482     ScaleWeights(NewTrueWeight, NewFalseWeight);
1483     // Emit the LHS condition.
1484     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1485                          NewTrueWeight, NewFalseWeight);
1486
1487     NewTrueWeight = TWeight;
1488     NewFalseWeight = 2 * (uint64_t)FWeight;
1489     ScaleWeights(NewTrueWeight, NewFalseWeight);
1490     // Emit the RHS condition into TmpBB.
1491     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1492                          NewTrueWeight, NewFalseWeight);
1493   } else {
1494     assert(Opc == Instruction::And && "Unknown merge op!");
1495     // Codegen X & Y as:
1496     // BB1:
1497     //   jmp_if_X TmpBB
1498     //   jmp FBB
1499     // TmpBB:
1500     //   jmp_if_Y TBB
1501     //   jmp FBB
1502     //
1503     //  This requires creation of TmpBB after CurBB.
1504
1505     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1506     // The requirement is that
1507     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1508     //     = FalseProb for orignal BB.
1509     // Assuming the orignal weights are A and B, one choice is to set BB1's
1510     // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1511     // assumes that
1512     //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1513
1514     uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1515     uint64_t NewFalseWeight = FWeight;
1516     ScaleWeights(NewTrueWeight, NewFalseWeight);
1517     // Emit the LHS condition.
1518     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1519                          NewTrueWeight, NewFalseWeight);
1520
1521     NewTrueWeight = 2 * (uint64_t)TWeight;
1522     NewFalseWeight = FWeight;
1523     ScaleWeights(NewTrueWeight, NewFalseWeight);
1524     // Emit the RHS condition into TmpBB.
1525     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1526                          NewTrueWeight, NewFalseWeight);
1527   }
1528 }
1529
1530 /// If the set of cases should be emitted as a series of branches, return true.
1531 /// If we should emit this as a bunch of and/or'd together conditions, return
1532 /// false.
1533 bool
1534 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1535   if (Cases.size() != 2) return true;
1536
1537   // If this is two comparisons of the same values or'd or and'd together, they
1538   // will get folded into a single comparison, so don't emit two blocks.
1539   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1540        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1541       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1542        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1543     return false;
1544   }
1545
1546   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1547   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1548   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1549       Cases[0].CC == Cases[1].CC &&
1550       isa<Constant>(Cases[0].CmpRHS) &&
1551       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1552     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1553       return false;
1554     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1555       return false;
1556   }
1557
1558   return true;
1559 }
1560
1561 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1562   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1563
1564   // Update machine-CFG edges.
1565   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1566
1567   // Figure out which block is immediately after the current one.
1568   MachineBasicBlock *NextBlock = nullptr;
1569   MachineFunction::iterator BBI = BrMBB;
1570   if (++BBI != FuncInfo.MF->end())
1571     NextBlock = BBI;
1572
1573   if (I.isUnconditional()) {
1574     // Update machine-CFG edges.
1575     BrMBB->addSuccessor(Succ0MBB);
1576
1577     // If this is not a fall-through branch or optimizations are switched off,
1578     // emit the branch.
1579     if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
1580       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1581                               MVT::Other, getControlRoot(),
1582                               DAG.getBasicBlock(Succ0MBB)));
1583
1584     return;
1585   }
1586
1587   // If this condition is one of the special cases we handle, do special stuff
1588   // now.
1589   const Value *CondVal = I.getCondition();
1590   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1591
1592   // If this is a series of conditions that are or'd or and'd together, emit
1593   // this as a sequence of branches instead of setcc's with and/or operations.
1594   // As long as jumps are not expensive, this should improve performance.
1595   // For example, instead of something like:
1596   //     cmp A, B
1597   //     C = seteq
1598   //     cmp D, E
1599   //     F = setle
1600   //     or C, F
1601   //     jnz foo
1602   // Emit:
1603   //     cmp A, B
1604   //     je foo
1605   //     cmp D, E
1606   //     jle foo
1607   //
1608   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1609     if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
1610         BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1611                              BOp->getOpcode() == Instruction::Or)) {
1612       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1613                            BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1614                            getEdgeWeight(BrMBB, Succ1MBB));
1615       // If the compares in later blocks need to use values not currently
1616       // exported from this block, export them now.  This block should always
1617       // be the first entry.
1618       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1619
1620       // Allow some cases to be rejected.
1621       if (ShouldEmitAsBranches(SwitchCases)) {
1622         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1623           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1624           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1625         }
1626
1627         // Emit the branch for this block.
1628         visitSwitchCase(SwitchCases[0], BrMBB);
1629         SwitchCases.erase(SwitchCases.begin());
1630         return;
1631       }
1632
1633       // Okay, we decided not to do this, remove any inserted MBB's and clear
1634       // SwitchCases.
1635       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1636         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1637
1638       SwitchCases.clear();
1639     }
1640   }
1641
1642   // Create a CaseBlock record representing this branch.
1643   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1644                nullptr, Succ0MBB, Succ1MBB, BrMBB);
1645
1646   // Use visitSwitchCase to actually insert the fast branch sequence for this
1647   // cond branch.
1648   visitSwitchCase(CB, BrMBB);
1649 }
1650
1651 /// visitSwitchCase - Emits the necessary code to represent a single node in
1652 /// the binary search tree resulting from lowering a switch instruction.
1653 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1654                                           MachineBasicBlock *SwitchBB) {
1655   SDValue Cond;
1656   SDValue CondLHS = getValue(CB.CmpLHS);
1657   SDLoc dl = getCurSDLoc();
1658
1659   // Build the setcc now.
1660   if (!CB.CmpMHS) {
1661     // Fold "(X == true)" to X and "(X == false)" to !X to
1662     // handle common cases produced by branch lowering.
1663     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1664         CB.CC == ISD::SETEQ)
1665       Cond = CondLHS;
1666     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1667              CB.CC == ISD::SETEQ) {
1668       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1669       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1670     } else
1671       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1672   } else {
1673     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1674
1675     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1676     const APInt& High  = cast<ConstantInt>(CB.CmpRHS)->getValue();
1677
1678     SDValue CmpOp = getValue(CB.CmpMHS);
1679     EVT VT = CmpOp.getValueType();
1680
1681     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1682       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1683                           ISD::SETLE);
1684     } else {
1685       SDValue SUB = DAG.getNode(ISD::SUB, dl,
1686                                 VT, CmpOp, DAG.getConstant(Low, VT));
1687       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1688                           DAG.getConstant(High-Low, VT), ISD::SETULE);
1689     }
1690   }
1691
1692   // Update successor info
1693   addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1694   // TrueBB and FalseBB are always different unless the incoming IR is
1695   // degenerate. This only happens when running llc on weird IR.
1696   if (CB.TrueBB != CB.FalseBB)
1697     addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1698
1699   // Set NextBlock to be the MBB immediately after the current one, if any.
1700   // This is used to avoid emitting unnecessary branches to the next block.
1701   MachineBasicBlock *NextBlock = nullptr;
1702   MachineFunction::iterator BBI = SwitchBB;
1703   if (++BBI != FuncInfo.MF->end())
1704     NextBlock = BBI;
1705
1706   // If the lhs block is the next block, invert the condition so that we can
1707   // fall through to the lhs instead of the rhs block.
1708   if (CB.TrueBB == NextBlock) {
1709     std::swap(CB.TrueBB, CB.FalseBB);
1710     SDValue True = DAG.getConstant(1, Cond.getValueType());
1711     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1712   }
1713
1714   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1715                                MVT::Other, getControlRoot(), Cond,
1716                                DAG.getBasicBlock(CB.TrueBB));
1717
1718   // Insert the false branch. Do this even if it's a fall through branch,
1719   // this makes it easier to do DAG optimizations which require inverting
1720   // the branch condition.
1721   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1722                        DAG.getBasicBlock(CB.FalseBB));
1723
1724   DAG.setRoot(BrCond);
1725 }
1726
1727 /// visitJumpTable - Emit JumpTable node in the current MBB
1728 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1729   // Emit the code for the jump table
1730   assert(JT.Reg != -1U && "Should lower JT Header first!");
1731   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
1732   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1733                                      JT.Reg, PTy);
1734   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1735   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1736                                     MVT::Other, Index.getValue(1),
1737                                     Table, Index);
1738   DAG.setRoot(BrJumpTable);
1739 }
1740
1741 /// visitJumpTableHeader - This function emits necessary code to produce index
1742 /// in the JumpTable from switch case.
1743 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1744                                                JumpTableHeader &JTH,
1745                                                MachineBasicBlock *SwitchBB) {
1746   // Subtract the lowest switch case value from the value being switched on and
1747   // conditional branch to default mbb if the result is greater than the
1748   // difference between smallest and largest cases.
1749   SDValue SwitchOp = getValue(JTH.SValue);
1750   EVT VT = SwitchOp.getValueType();
1751   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1752                             DAG.getConstant(JTH.First, VT));
1753
1754   // The SDNode we just created, which holds the value being switched on minus
1755   // the smallest case value, needs to be copied to a virtual register so it
1756   // can be used as an index into the jump table in a subsequent basic block.
1757   // This value may be smaller or larger than the target's pointer type, and
1758   // therefore require extension or truncating.
1759   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1760   SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
1761
1762   unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1763   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1764                                     JumpTableReg, SwitchOp);
1765   JT.Reg = JumpTableReg;
1766
1767   // Emit the range check for the jump table, and branch to the default block
1768   // for the switch statement if the value being switched on exceeds the largest
1769   // case in the switch.
1770   SDValue CMP =
1771       DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1772                                                          Sub.getValueType()),
1773                    Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
1774
1775   // Set NextBlock to be the MBB immediately after the current one, if any.
1776   // This is used to avoid emitting unnecessary branches to the next block.
1777   MachineBasicBlock *NextBlock = nullptr;
1778   MachineFunction::iterator BBI = SwitchBB;
1779
1780   if (++BBI != FuncInfo.MF->end())
1781     NextBlock = BBI;
1782
1783   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1784                                MVT::Other, CopyTo, CMP,
1785                                DAG.getBasicBlock(JT.Default));
1786
1787   if (JT.MBB != NextBlock)
1788     BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1789                          DAG.getBasicBlock(JT.MBB));
1790
1791   DAG.setRoot(BrCond);
1792 }
1793
1794 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1795 /// tail spliced into a stack protector check success bb.
1796 ///
1797 /// For a high level explanation of how this fits into the stack protector
1798 /// generation see the comment on the declaration of class
1799 /// StackProtectorDescriptor.
1800 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1801                                                   MachineBasicBlock *ParentBB) {
1802
1803   // First create the loads to the guard/stack slot for the comparison.
1804   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1805   EVT PtrTy = TLI.getPointerTy();
1806
1807   MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1808   int FI = MFI->getStackProtectorIndex();
1809
1810   const Value *IRGuard = SPD.getGuard();
1811   SDValue GuardPtr = getValue(IRGuard);
1812   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1813
1814   unsigned Align =
1815     TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1816
1817   SDValue Guard;
1818
1819   // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1820   // guard value from the virtual register holding the value. Otherwise, emit a
1821   // volatile load to retrieve the stack guard value.
1822   unsigned GuardReg = SPD.getGuardReg();
1823
1824   if (GuardReg && TLI.useLoadStackGuardNode())
1825     Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
1826                                PtrTy);
1827   else
1828     Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1829                         GuardPtr, MachinePointerInfo(IRGuard, 0),
1830                         true, false, false, Align);
1831
1832   SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1833                                   StackSlotPtr,
1834                                   MachinePointerInfo::getFixedStack(FI),
1835                                   true, false, false, Align);
1836
1837   // Perform the comparison via a subtract/getsetcc.
1838   EVT VT = Guard.getValueType();
1839   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1840
1841   SDValue Cmp =
1842       DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1843                                                          Sub.getValueType()),
1844                    Sub, DAG.getConstant(0, VT), ISD::SETNE);
1845
1846   // If the sub is not 0, then we know the guard/stackslot do not equal, so
1847   // branch to failure MBB.
1848   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1849                                MVT::Other, StackSlot.getOperand(0),
1850                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1851   // Otherwise branch to success MBB.
1852   SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1853                            MVT::Other, BrCond,
1854                            DAG.getBasicBlock(SPD.getSuccessMBB()));
1855
1856   DAG.setRoot(Br);
1857 }
1858
1859 /// Codegen the failure basic block for a stack protector check.
1860 ///
1861 /// A failure stack protector machine basic block consists simply of a call to
1862 /// __stack_chk_fail().
1863 ///
1864 /// For a high level explanation of how this fits into the stack protector
1865 /// generation see the comment on the declaration of class
1866 /// StackProtectorDescriptor.
1867 void
1868 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1870   SDValue Chain =
1871       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1872                       nullptr, 0, false, getCurSDLoc(), false, false).second;
1873   DAG.setRoot(Chain);
1874 }
1875
1876 /// visitBitTestHeader - This function emits necessary code to produce value
1877 /// suitable for "bit tests"
1878 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1879                                              MachineBasicBlock *SwitchBB) {
1880   // Subtract the minimum value
1881   SDValue SwitchOp = getValue(B.SValue);
1882   EVT VT = SwitchOp.getValueType();
1883   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1884                             DAG.getConstant(B.First, VT));
1885
1886   // Check range
1887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1888   SDValue RangeCmp =
1889       DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1890                                                          Sub.getValueType()),
1891                    Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
1892
1893   // Determine the type of the test operands.
1894   bool UsePtrType = false;
1895   if (!TLI.isTypeLegal(VT))
1896     UsePtrType = true;
1897   else {
1898     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1899       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1900         // Switch table case range are encoded into series of masks.
1901         // Just use pointer type, it's guaranteed to fit.
1902         UsePtrType = true;
1903         break;
1904       }
1905   }
1906   if (UsePtrType) {
1907     VT = TLI.getPointerTy();
1908     Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1909   }
1910
1911   B.RegVT = VT.getSimpleVT();
1912   B.Reg = FuncInfo.CreateReg(B.RegVT);
1913   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1914                                     B.Reg, Sub);
1915
1916   // Set NextBlock to be the MBB immediately after the current one, if any.
1917   // This is used to avoid emitting unnecessary branches to the next block.
1918   MachineBasicBlock *NextBlock = nullptr;
1919   MachineFunction::iterator BBI = SwitchBB;
1920   if (++BBI != FuncInfo.MF->end())
1921     NextBlock = BBI;
1922
1923   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1924
1925   addSuccessorWithWeight(SwitchBB, B.Default);
1926   addSuccessorWithWeight(SwitchBB, MBB);
1927
1928   SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1929                                 MVT::Other, CopyTo, RangeCmp,
1930                                 DAG.getBasicBlock(B.Default));
1931
1932   if (MBB != NextBlock)
1933     BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1934                           DAG.getBasicBlock(MBB));
1935
1936   DAG.setRoot(BrRange);
1937 }
1938
1939 /// visitBitTestCase - this function produces one "bit test"
1940 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1941                                            MachineBasicBlock* NextMBB,
1942                                            uint32_t BranchWeightToNext,
1943                                            unsigned Reg,
1944                                            BitTestCase &B,
1945                                            MachineBasicBlock *SwitchBB) {
1946   MVT VT = BB.RegVT;
1947   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1948                                        Reg, VT);
1949   SDValue Cmp;
1950   unsigned PopCount = CountPopulation_64(B.Mask);
1951   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1952   if (PopCount == 1) {
1953     // Testing for a single bit; just compare the shift count with what it
1954     // would need to be to shift a 1 bit in that position.
1955     Cmp = DAG.getSetCC(
1956         getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1957         DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
1958   } else if (PopCount == BB.Range) {
1959     // There is only one zero bit in the range, test for it directly.
1960     Cmp = DAG.getSetCC(
1961         getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1962         DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), ISD::SETNE);
1963   } else {
1964     // Make desired shift
1965     SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1966                                     DAG.getConstant(1, VT), ShiftOp);
1967
1968     // Emit bit tests and jumps
1969     SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1970                                 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1971     Cmp = DAG.getSetCC(getCurSDLoc(),
1972                        TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1973                        DAG.getConstant(0, VT), ISD::SETNE);
1974   }
1975
1976   // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1977   addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1978   // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1979   addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1980
1981   SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1982                               MVT::Other, getControlRoot(),
1983                               Cmp, DAG.getBasicBlock(B.TargetBB));
1984
1985   // Set NextBlock to be the MBB immediately after the current one, if any.
1986   // This is used to avoid emitting unnecessary branches to the next block.
1987   MachineBasicBlock *NextBlock = nullptr;
1988   MachineFunction::iterator BBI = SwitchBB;
1989   if (++BBI != FuncInfo.MF->end())
1990     NextBlock = BBI;
1991
1992   if (NextMBB != NextBlock)
1993     BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
1994                         DAG.getBasicBlock(NextMBB));
1995
1996   DAG.setRoot(BrAnd);
1997 }
1998
1999 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2000   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2001
2002   // Retrieve successors.
2003   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2004   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2005
2006   const Value *Callee(I.getCalledValue());
2007   const Function *Fn = dyn_cast<Function>(Callee);
2008   if (isa<InlineAsm>(Callee))
2009     visitInlineAsm(&I);
2010   else if (Fn && Fn->isIntrinsic()) {
2011     switch (Fn->getIntrinsicID()) {
2012     default:
2013       llvm_unreachable("Cannot invoke this intrinsic");
2014     case Intrinsic::donothing:
2015       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2016       break;
2017     case Intrinsic::experimental_patchpoint_void:
2018     case Intrinsic::experimental_patchpoint_i64:
2019       visitPatchpoint(&I, LandingPad);
2020       break;
2021     }
2022   } else
2023     LowerCallTo(&I, getValue(Callee), false, LandingPad);
2024
2025   // If the value of the invoke is used outside of its defining block, make it
2026   // available as a virtual register.
2027   CopyToExportRegsIfNeeded(&I);
2028
2029   // Update successor info
2030   addSuccessorWithWeight(InvokeMBB, Return);
2031   addSuccessorWithWeight(InvokeMBB, LandingPad);
2032
2033   // Drop into normal successor.
2034   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2035                           MVT::Other, getControlRoot(),
2036                           DAG.getBasicBlock(Return)));
2037 }
2038
2039 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2040   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2041 }
2042
2043 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2044   assert(FuncInfo.MBB->isLandingPad() &&
2045          "Call to landingpad not in landing pad!");
2046
2047   MachineBasicBlock *MBB = FuncInfo.MBB;
2048   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2049   AddLandingPadInfo(LP, MMI, MBB);
2050
2051   // If there aren't registers to copy the values into (e.g., during SjLj
2052   // exceptions), then don't bother to create these DAG nodes.
2053   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2054   if (TLI.getExceptionPointerRegister() == 0 &&
2055       TLI.getExceptionSelectorRegister() == 0)
2056     return;
2057
2058   SmallVector<EVT, 2> ValueVTs;
2059   ComputeValueVTs(TLI, LP.getType(), ValueVTs);
2060   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2061
2062   // Get the two live-in registers as SDValues. The physregs have already been
2063   // copied into virtual registers.
2064   SDValue Ops[2];
2065   Ops[0] = DAG.getZExtOrTrunc(
2066       DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2067                          FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2068       getCurSDLoc(), ValueVTs[0]);
2069   Ops[1] = DAG.getZExtOrTrunc(
2070       DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2071                          FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
2072       getCurSDLoc(), ValueVTs[1]);
2073
2074   // Merge into one.
2075   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2076                             DAG.getVTList(ValueVTs), Ops);
2077   setValue(&LP, Res);
2078 }
2079
2080 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2081 /// small case ranges).
2082 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2083                                                  CaseRecVector& WorkList,
2084                                                  const Value* SV,
2085                                                  MachineBasicBlock *Default,
2086                                                  MachineBasicBlock *SwitchBB) {
2087   // Size is the number of Cases represented by this range.
2088   size_t Size = CR.Range.second - CR.Range.first;
2089   if (Size > 3)
2090     return false;
2091
2092   // Get the MachineFunction which holds the current MBB.  This is used when
2093   // inserting any additional MBBs necessary to represent the switch.
2094   MachineFunction *CurMF = FuncInfo.MF;
2095
2096   // Figure out which block is immediately after the current one.
2097   MachineBasicBlock *NextBlock = nullptr;
2098   MachineFunction::iterator BBI = CR.CaseBB;
2099
2100   if (++BBI != FuncInfo.MF->end())
2101     NextBlock = BBI;
2102
2103   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2104   // If any two of the cases has the same destination, and if one value
2105   // is the same as the other, but has one bit unset that the other has set,
2106   // use bit manipulation to do two compares at once.  For example:
2107   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2108   // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2109   // TODO: Handle cases where CR.CaseBB != SwitchBB.
2110   if (Size == 2 && CR.CaseBB == SwitchBB) {
2111     Case &Small = *CR.Range.first;
2112     Case &Big = *(CR.Range.second-1);
2113
2114     if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2115       const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2116       const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2117
2118       // Check that there is only one bit different.
2119       if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2120           (SmallValue | BigValue) == BigValue) {
2121         // Isolate the common bit.
2122         APInt CommonBit = BigValue & ~SmallValue;
2123         assert((SmallValue | CommonBit) == BigValue &&
2124                CommonBit.countPopulation() == 1 && "Not a common bit?");
2125
2126         SDValue CondLHS = getValue(SV);
2127         EVT VT = CondLHS.getValueType();
2128         SDLoc DL = getCurSDLoc();
2129
2130         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2131                                  DAG.getConstant(CommonBit, VT));
2132         SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2133                                     Or, DAG.getConstant(BigValue, VT),
2134                                     ISD::SETEQ);
2135
2136         // Update successor info.
2137         // Both Small and Big will jump to Small.BB, so we sum up the weights.
2138         addSuccessorWithWeight(SwitchBB, Small.BB,
2139                                Small.ExtraWeight + Big.ExtraWeight);
2140         addSuccessorWithWeight(SwitchBB, Default,
2141           // The default destination is the first successor in IR.
2142           BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2143
2144         // Insert the true branch.
2145         SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2146                                      getControlRoot(), Cond,
2147                                      DAG.getBasicBlock(Small.BB));
2148
2149         // Insert the false branch.
2150         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2151                              DAG.getBasicBlock(Default));
2152
2153         DAG.setRoot(BrCond);
2154         return true;
2155       }
2156     }
2157   }
2158
2159   // Order cases by weight so the most likely case will be checked first.
2160   uint32_t UnhandledWeights = 0;
2161   if (BPI) {
2162     for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2163       uint32_t IWeight = I->ExtraWeight;
2164       UnhandledWeights += IWeight;
2165       for (CaseItr J = CR.Range.first; J < I; ++J) {
2166         uint32_t JWeight = J->ExtraWeight;
2167         if (IWeight > JWeight)
2168           std::swap(*I, *J);
2169       }
2170     }
2171   }
2172   // Rearrange the case blocks so that the last one falls through if possible.
2173   Case &BackCase = *(CR.Range.second-1);
2174   if (Size > 1 &&
2175       NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2176     // The last case block won't fall through into 'NextBlock' if we emit the
2177     // branches in this order.  See if rearranging a case value would help.
2178     // We start at the bottom as it's the case with the least weight.
2179     for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2180       if (I->BB == NextBlock) {
2181         std::swap(*I, BackCase);
2182         break;
2183       }
2184   }
2185
2186   // Create a CaseBlock record representing a conditional branch to
2187   // the Case's target mbb if the value being switched on SV is equal
2188   // to C.
2189   MachineBasicBlock *CurBlock = CR.CaseBB;
2190   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2191     MachineBasicBlock *FallThrough;
2192     if (I != E-1) {
2193       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2194       CurMF->insert(BBI, FallThrough);
2195
2196       // Put SV in a virtual register to make it available from the new blocks.
2197       ExportFromCurrentBlock(SV);
2198     } else {
2199       // If the last case doesn't match, go to the default block.
2200       FallThrough = Default;
2201     }
2202
2203     const Value *RHS, *LHS, *MHS;
2204     ISD::CondCode CC;
2205     if (I->High == I->Low) {
2206       // This is just small small case range :) containing exactly 1 case
2207       CC = ISD::SETEQ;
2208       LHS = SV; RHS = I->High; MHS = nullptr;
2209     } else {
2210       CC = ISD::SETLE;
2211       LHS = I->Low; MHS = SV; RHS = I->High;
2212     }
2213
2214     // The false weight should be sum of all un-handled cases.
2215     UnhandledWeights -= I->ExtraWeight;
2216     CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2217                  /* me */ CurBlock,
2218                  /* trueweight */ I->ExtraWeight,
2219                  /* falseweight */ UnhandledWeights);
2220
2221     // If emitting the first comparison, just call visitSwitchCase to emit the
2222     // code into the current block.  Otherwise, push the CaseBlock onto the
2223     // vector to be later processed by SDISel, and insert the node's MBB
2224     // before the next MBB.
2225     if (CurBlock == SwitchBB)
2226       visitSwitchCase(CB, SwitchBB);
2227     else
2228       SwitchCases.push_back(CB);
2229
2230     CurBlock = FallThrough;
2231   }
2232
2233   return true;
2234 }
2235
2236 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2237   return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2238          TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
2239 }
2240
2241 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2242   uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2243   APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2244   return (LastExt - FirstExt + 1ULL);
2245 }
2246
2247 /// handleJTSwitchCase - Emit jumptable for current switch case range
2248 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2249                                              CaseRecVector &WorkList,
2250                                              const Value *SV,
2251                                              MachineBasicBlock *Default,
2252                                              MachineBasicBlock *SwitchBB) {
2253   Case& FrontCase = *CR.Range.first;
2254   Case& BackCase  = *(CR.Range.second-1);
2255
2256   const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2257   const APInt &Last  = cast<ConstantInt>(BackCase.High)->getValue();
2258
2259   APInt TSize(First.getBitWidth(), 0);
2260   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2261     TSize += I->size();
2262
2263   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2264   if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
2265     return false;
2266
2267   APInt Range = ComputeRange(First, Last);
2268   // The density is TSize / Range. Require at least 40%.
2269   // It should not be possible for IntTSize to saturate for sane code, but make
2270   // sure we handle Range saturation correctly.
2271   uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2272   uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2273   if (IntTSize * 10 < IntRange * 4)
2274     return false;
2275
2276   DEBUG(dbgs() << "Lowering jump table\n"
2277                << "First entry: " << First << ". Last entry: " << Last << '\n'
2278                << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2279
2280   // Get the MachineFunction which holds the current MBB.  This is used when
2281   // inserting any additional MBBs necessary to represent the switch.
2282   MachineFunction *CurMF = FuncInfo.MF;
2283
2284   // Figure out which block is immediately after the current one.
2285   MachineFunction::iterator BBI = CR.CaseBB;
2286   ++BBI;
2287
2288   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2289
2290   // Create a new basic block to hold the code for loading the address
2291   // of the jump table, and jumping to it.  Update successor information;
2292   // we will either branch to the default case for the switch, or the jump
2293   // table.
2294   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2295   CurMF->insert(BBI, JumpTableBB);
2296
2297   addSuccessorWithWeight(CR.CaseBB, Default);
2298   addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2299
2300   // Build a vector of destination BBs, corresponding to each target
2301   // of the jump table. If the value of the jump table slot corresponds to
2302   // a case statement, push the case's BB onto the vector, otherwise, push
2303   // the default BB.
2304   std::vector<MachineBasicBlock*> DestBBs;
2305   APInt TEI = First;
2306   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2307     const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2308     const APInt &High = cast<ConstantInt>(I->High)->getValue();
2309
2310     if (Low.sle(TEI) && TEI.sle(High)) {
2311       DestBBs.push_back(I->BB);
2312       if (TEI==High)
2313         ++I;
2314     } else {
2315       DestBBs.push_back(Default);
2316     }
2317   }
2318
2319   // Calculate weight for each unique destination in CR.
2320   DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2321   if (FuncInfo.BPI)
2322     for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2323       DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2324           DestWeights.find(I->BB);
2325       if (Itr != DestWeights.end())
2326         Itr->second += I->ExtraWeight;
2327       else
2328         DestWeights[I->BB] = I->ExtraWeight;
2329     }
2330
2331   // Update successor info. Add one edge to each unique successor.
2332   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2333   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2334          E = DestBBs.end(); I != E; ++I) {
2335     if (!SuccsHandled[(*I)->getNumber()]) {
2336       SuccsHandled[(*I)->getNumber()] = true;
2337       DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2338           DestWeights.find(*I);
2339       addSuccessorWithWeight(JumpTableBB, *I,
2340                              Itr != DestWeights.end() ? Itr->second : 0);
2341     }
2342   }
2343
2344   // Create a jump table index for this jump table.
2345   unsigned JTEncoding = TLI.getJumpTableEncoding();
2346   unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2347                        ->createJumpTableIndex(DestBBs);
2348
2349   // Set the jump table information so that we can codegen it as a second
2350   // MachineBasicBlock
2351   JumpTable JT(-1U, JTI, JumpTableBB, Default);
2352   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2353   if (CR.CaseBB == SwitchBB)
2354     visitJumpTableHeader(JT, JTH, SwitchBB);
2355
2356   JTCases.push_back(JumpTableBlock(JTH, JT));
2357   return true;
2358 }
2359
2360 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2361 /// 2 subtrees.
2362 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2363                                                   CaseRecVector& WorkList,
2364                                                   const Value* SV,
2365                                                   MachineBasicBlock* SwitchBB) {
2366   // Get the MachineFunction which holds the current MBB.  This is used when
2367   // inserting any additional MBBs necessary to represent the switch.
2368   MachineFunction *CurMF = FuncInfo.MF;
2369
2370   // Figure out which block is immediately after the current one.
2371   MachineFunction::iterator BBI = CR.CaseBB;
2372   ++BBI;
2373
2374   Case& FrontCase = *CR.Range.first;
2375   Case& BackCase  = *(CR.Range.second-1);
2376   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2377
2378   // Size is the number of Cases represented by this range.
2379   unsigned Size = CR.Range.second - CR.Range.first;
2380
2381   const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2382   const APInt &Last  = cast<ConstantInt>(BackCase.High)->getValue();
2383   double FMetric = 0;
2384   CaseItr Pivot = CR.Range.first + Size/2;
2385
2386   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2387   // (heuristically) allow us to emit JumpTable's later.
2388   APInt TSize(First.getBitWidth(), 0);
2389   for (CaseItr I = CR.Range.first, E = CR.Range.second;
2390        I!=E; ++I)
2391     TSize += I->size();
2392
2393   APInt LSize = FrontCase.size();
2394   APInt RSize = TSize-LSize;
2395   DEBUG(dbgs() << "Selecting best pivot: \n"
2396                << "First: " << First << ", Last: " << Last <<'\n'
2397                << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2398   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2399        J!=E; ++I, ++J) {
2400     const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2401     const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2402     APInt Range = ComputeRange(LEnd, RBegin);
2403     assert((Range - 2ULL).isNonNegative() &&
2404            "Invalid case distance");
2405     // Use volatile double here to avoid excess precision issues on some hosts,
2406     // e.g. that use 80-bit X87 registers.
2407     volatile double LDensity =
2408        (double)LSize.roundToDouble() /
2409                            (LEnd - First + 1ULL).roundToDouble();
2410     volatile double RDensity =
2411       (double)RSize.roundToDouble() /
2412                            (Last - RBegin + 1ULL).roundToDouble();
2413     volatile double Metric = Range.logBase2()*(LDensity+RDensity);
2414     // Should always split in some non-trivial place
2415     DEBUG(dbgs() <<"=>Step\n"
2416                  << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2417                  << "LDensity: " << LDensity
2418                  << ", RDensity: " << RDensity << '\n'
2419                  << "Metric: " << Metric << '\n');
2420     if (FMetric < Metric) {
2421       Pivot = J;
2422       FMetric = Metric;
2423       DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2424     }
2425
2426     LSize += J->size();
2427     RSize -= J->size();
2428   }
2429
2430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2431   if (areJTsAllowed(TLI)) {
2432     // If our case is dense we *really* should handle it earlier!
2433     assert((FMetric > 0) && "Should handle dense range earlier!");
2434   } else {
2435     Pivot = CR.Range.first + Size/2;
2436   }
2437
2438   CaseRange LHSR(CR.Range.first, Pivot);
2439   CaseRange RHSR(Pivot, CR.Range.second);
2440   const Constant *C = Pivot->Low;
2441   MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
2442
2443   // We know that we branch to the LHS if the Value being switched on is
2444   // less than the Pivot value, C.  We use this to optimize our binary
2445   // tree a bit, by recognizing that if SV is greater than or equal to the
2446   // LHS's Case Value, and that Case Value is exactly one less than the
2447   // Pivot's Value, then we can branch directly to the LHS's Target,
2448   // rather than creating a leaf node for it.
2449   if ((LHSR.second - LHSR.first) == 1 &&
2450       LHSR.first->High == CR.GE &&
2451       cast<ConstantInt>(C)->getValue() ==
2452       (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2453     TrueBB = LHSR.first->BB;
2454   } else {
2455     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2456     CurMF->insert(BBI, TrueBB);
2457     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2458
2459     // Put SV in a virtual register to make it available from the new blocks.
2460     ExportFromCurrentBlock(SV);
2461   }
2462
2463   // Similar to the optimization above, if the Value being switched on is
2464   // known to be less than the Constant CR.LT, and the current Case Value
2465   // is CR.LT - 1, then we can branch directly to the target block for
2466   // the current Case Value, rather than emitting a RHS leaf node for it.
2467   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2468       cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2469       (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2470     FalseBB = RHSR.first->BB;
2471   } else {
2472     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2473     CurMF->insert(BBI, FalseBB);
2474     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2475
2476     // Put SV in a virtual register to make it available from the new blocks.
2477     ExportFromCurrentBlock(SV);
2478   }
2479
2480   // Create a CaseBlock record representing a conditional branch to
2481   // the LHS node if the value being switched on SV is less than C.
2482   // Otherwise, branch to LHS.
2483   CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
2484
2485   if (CR.CaseBB == SwitchBB)
2486     visitSwitchCase(CB, SwitchBB);
2487   else
2488     SwitchCases.push_back(CB);
2489
2490   return true;
2491 }
2492
2493 /// handleBitTestsSwitchCase - if current case range has few destination and
2494 /// range span less, than machine word bitwidth, encode case range into series
2495 /// of masks and emit bit tests with these masks.
2496 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2497                                                    CaseRecVector& WorkList,
2498                                                    const Value* SV,
2499                                                    MachineBasicBlock* Default,
2500                                                    MachineBasicBlock* SwitchBB) {
2501   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2502   EVT PTy = TLI.getPointerTy();
2503   unsigned IntPtrBits = PTy.getSizeInBits();
2504
2505   Case& FrontCase = *CR.Range.first;
2506   Case& BackCase  = *(CR.Range.second-1);
2507
2508   // Get the MachineFunction which holds the current MBB.  This is used when
2509   // inserting any additional MBBs necessary to represent the switch.
2510   MachineFunction *CurMF = FuncInfo.MF;
2511
2512   // If target does not have legal shift left, do not emit bit tests at all.
2513   if (!TLI.isOperationLegal(ISD::SHL, PTy))
2514     return false;
2515
2516   size_t numCmps = 0;
2517   for (CaseItr I = CR.Range.first, E = CR.Range.second;
2518        I!=E; ++I) {
2519     // Single case counts one, case range - two.
2520     numCmps += (I->Low == I->High ? 1 : 2);
2521   }
2522
2523   // Count unique destinations
2524   SmallSet<MachineBasicBlock*, 4> Dests;
2525   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2526     Dests.insert(I->BB);
2527     if (Dests.size() > 3)
2528       // Don't bother the code below, if there are too much unique destinations
2529       return false;
2530   }
2531   DEBUG(dbgs() << "Total number of unique destinations: "
2532         << Dests.size() << '\n'
2533         << "Total number of comparisons: " << numCmps << '\n');
2534
2535   // Compute span of values.
2536   const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2537   const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2538   APInt cmpRange = maxValue - minValue;
2539
2540   DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2541                << "Low bound: " << minValue << '\n'
2542                << "High bound: " << maxValue << '\n');
2543
2544   if (cmpRange.uge(IntPtrBits) ||
2545       (!(Dests.size() == 1 && numCmps >= 3) &&
2546        !(Dests.size() == 2 && numCmps >= 5) &&
2547        !(Dests.size() >= 3 && numCmps >= 6)))
2548     return false;
2549
2550   DEBUG(dbgs() << "Emitting bit tests\n");
2551   APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2552
2553   // Optimize the case where all the case values fit in a
2554   // word without having to subtract minValue. In this case,
2555   // we can optimize away the subtraction.
2556   if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2557     cmpRange = maxValue;
2558   } else {
2559     lowBound = minValue;
2560   }
2561
2562   CaseBitsVector CasesBits;
2563   unsigned i, count = 0;
2564
2565   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2566     MachineBasicBlock* Dest = I->BB;
2567     for (i = 0; i < count; ++i)
2568       if (Dest == CasesBits[i].BB)
2569         break;
2570
2571     if (i == count) {
2572       assert((count < 3) && "Too much destinations to test!");
2573       CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2574       count++;
2575     }
2576
2577     const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2578     const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2579
2580     uint64_t lo = (lowValue - lowBound).getZExtValue();
2581     uint64_t hi = (highValue - lowBound).getZExtValue();
2582     CasesBits[i].ExtraWeight += I->ExtraWeight;
2583
2584     for (uint64_t j = lo; j <= hi; j++) {
2585       CasesBits[i].Mask |=  1ULL << j;
2586       CasesBits[i].Bits++;
2587     }
2588
2589   }
2590   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2591
2592   BitTestInfo BTC;
2593
2594   // Figure out which block is immediately after the current one.
2595   MachineFunction::iterator BBI = CR.CaseBB;
2596   ++BBI;
2597
2598   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2599
2600   DEBUG(dbgs() << "Cases:\n");
2601   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2602     DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2603                  << ", Bits: " << CasesBits[i].Bits
2604                  << ", BB: " << CasesBits[i].BB << '\n');
2605
2606     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2607     CurMF->insert(BBI, CaseBB);
2608     BTC.push_back(BitTestCase(CasesBits[i].Mask,
2609                               CaseBB,
2610                               CasesBits[i].BB, CasesBits[i].ExtraWeight));
2611
2612     // Put SV in a virtual register to make it available from the new blocks.
2613     ExportFromCurrentBlock(SV);
2614   }
2615
2616   BitTestBlock BTB(lowBound, cmpRange, SV,
2617                    -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2618                    CR.CaseBB, Default, std::move(BTC));
2619
2620   if (CR.CaseBB == SwitchBB)
2621     visitBitTestHeader(BTB, SwitchBB);
2622
2623   BitTestCases.push_back(std::move(BTB));
2624
2625   return true;
2626 }
2627
2628 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2629 void SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2630                                      const SwitchInst& SI) {
2631   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2632   // Start with "simple" cases
2633   for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2634        i != e; ++i) {
2635     const BasicBlock *SuccBB = i.getCaseSuccessor();
2636     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2637
2638     uint32_t ExtraWeight =
2639       BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2640
2641     Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2642                          SMBB, ExtraWeight));
2643   }
2644   std::sort(Cases.begin(), Cases.end(), CaseCmp());
2645
2646   // Merge case into clusters
2647   if (Cases.size() >= 2)
2648     // Must recompute end() each iteration because it may be
2649     // invalidated by erase if we hold on to it
2650     for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
2651          J != Cases.end(); ) {
2652       const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2653       const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2654       MachineBasicBlock* nextBB = J->BB;
2655       MachineBasicBlock* currentBB = I->BB;
2656
2657       // If the two neighboring cases go to the same destination, merge them
2658       // into a single case.
2659       if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2660         I->High = J->High;
2661         I->ExtraWeight += J->ExtraWeight;
2662         J = Cases.erase(J);
2663       } else {
2664         I = J++;
2665       }
2666     }
2667
2668   DEBUG({
2669       size_t numCmps = 0;
2670       for (auto &I : Cases)
2671         // A range counts double, since it requires two compares.
2672         numCmps += I.Low != I.High ? 2 : 1;
2673
2674       dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2675              << ". Total compares: " << numCmps << '\n';
2676     });
2677 }
2678
2679 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2680                                            MachineBasicBlock *Last) {
2681   // Update JTCases.
2682   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2683     if (JTCases[i].first.HeaderBB == First)
2684       JTCases[i].first.HeaderBB = Last;
2685
2686   // Update BitTestCases.
2687   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2688     if (BitTestCases[i].Parent == First)
2689       BitTestCases[i].Parent = Last;
2690 }
2691
2692 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2693   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2694
2695   // Figure out which block is immediately after the current one.
2696   MachineBasicBlock *NextBlock = nullptr;
2697   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2698
2699   // If there is only the default destination, branch to it if it is not the
2700   // next basic block.  Otherwise, just fall through.
2701   if (!SI.getNumCases()) {
2702     // Update machine-CFG edges.
2703
2704     // If this is not a fall-through branch, emit the branch.
2705     SwitchMBB->addSuccessor(Default);
2706     if (Default != NextBlock)
2707       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2708                               MVT::Other, getControlRoot(),
2709                               DAG.getBasicBlock(Default)));
2710
2711     return;
2712   }
2713
2714   // If there are any non-default case statements, create a vector of Cases
2715   // representing each one, and sort the vector so that we can efficiently
2716   // create a binary search tree from them.
2717   CaseVector Cases;
2718   Clusterify(Cases, SI);
2719
2720   // Get the Value to be switched on and default basic blocks, which will be
2721   // inserted into CaseBlock records, representing basic blocks in the binary
2722   // search tree.
2723   const Value *SV = SI.getCondition();
2724
2725   // Push the initial CaseRec onto the worklist
2726   CaseRecVector WorkList;
2727   WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
2728                              CaseRange(Cases.begin(),Cases.end())));
2729
2730   while (!WorkList.empty()) {
2731     // Grab a record representing a case range to process off the worklist
2732     CaseRec CR = WorkList.back();
2733     WorkList.pop_back();
2734
2735     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2736       continue;
2737
2738     // If the range has few cases (two or less) emit a series of specific
2739     // tests.
2740     if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2741       continue;
2742
2743     // If the switch has more than N blocks, and is at least 40% dense, and the
2744     // target supports indirect branches, then emit a jump table rather than
2745     // lowering the switch to a binary tree of conditional branches.
2746     // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2747     if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2748       continue;
2749
2750     // Emit binary tree. We need to pick a pivot, and push left and right ranges
2751     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2752     handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
2753   }
2754 }
2755
2756 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2757   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2758
2759   // Update machine-CFG edges with unique successors.
2760   SmallSet<BasicBlock*, 32> Done;
2761   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2762     BasicBlock *BB = I.getSuccessor(i);
2763     bool Inserted = Done.insert(BB);
2764     if (!Inserted)
2765         continue;
2766
2767     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2768     addSuccessorWithWeight(IndirectBrMBB, Succ);
2769   }
2770
2771   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2772                           MVT::Other, getControlRoot(),
2773                           getValue(I.getAddress())));
2774 }
2775
2776 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2777   if (DAG.getTarget().Options.TrapUnreachable)
2778     DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2779 }
2780
2781 void SelectionDAGBuilder::visitFSub(const User &I) {
2782   // -0.0 - X --> fneg
2783   Type *Ty = I.getType();
2784   if (isa<Constant>(I.getOperand(0)) &&
2785       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2786     SDValue Op2 = getValue(I.getOperand(1));
2787     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2788                              Op2.getValueType(), Op2));
2789     return;
2790   }
2791
2792   visitBinary(I, ISD::FSUB);
2793 }
2794
2795 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2796   SDValue Op1 = getValue(I.getOperand(0));
2797   SDValue Op2 = getValue(I.getOperand(1));
2798
2799   bool nuw = false;
2800   bool nsw = false;
2801   bool exact = false;
2802   if (const OverflowingBinaryOperator *OFBinOp =
2803           dyn_cast<const OverflowingBinaryOperator>(&I)) {
2804     nuw = OFBinOp->hasNoUnsignedWrap();
2805     nsw = OFBinOp->hasNoSignedWrap();
2806   }
2807   if (const PossiblyExactOperator *ExactOp =
2808           dyn_cast<const PossiblyExactOperator>(&I))
2809     exact = ExactOp->isExact();
2810
2811   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2812                                      Op1, Op2, nuw, nsw, exact);
2813   setValue(&I, BinNodeValue);
2814 }
2815
2816 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2817   SDValue Op1 = getValue(I.getOperand(0));
2818   SDValue Op2 = getValue(I.getOperand(1));
2819
2820   EVT ShiftTy =
2821       DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
2822
2823   // Coerce the shift amount to the right type if we can.
2824   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2825     unsigned ShiftSize = ShiftTy.getSizeInBits();
2826     unsigned Op2Size = Op2.getValueType().getSizeInBits();
2827     SDLoc DL = getCurSDLoc();
2828
2829     // If the operand is smaller than the shift count type, promote it.
2830     if (ShiftSize > Op2Size)
2831       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2832
2833     // If the operand is larger than the shift count type but the shift
2834     // count type has enough bits to represent any shift value, truncate
2835     // it now. This is a common case and it exposes the truncate to
2836     // optimization early.
2837     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2838       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2839     // Otherwise we'll need to temporarily settle for some other convenient
2840     // type.  Type legalization will make adjustments once the shiftee is split.
2841     else
2842       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2843   }
2844
2845   bool nuw = false;
2846   bool nsw = false;
2847   bool exact = false;
2848
2849   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2850
2851     if (const OverflowingBinaryOperator *OFBinOp =
2852             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2853       nuw = OFBinOp->hasNoUnsignedWrap();
2854       nsw = OFBinOp->hasNoSignedWrap();
2855     }
2856     if (const PossiblyExactOperator *ExactOp =
2857             dyn_cast<const PossiblyExactOperator>(&I))
2858       exact = ExactOp->isExact();
2859   }
2860
2861   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2862                             nuw, nsw, exact);
2863   setValue(&I, Res);
2864 }
2865
2866 void SelectionDAGBuilder::visitSDiv(const User &I) {
2867   SDValue Op1 = getValue(I.getOperand(0));
2868   SDValue Op2 = getValue(I.getOperand(1));
2869
2870   // Turn exact SDivs into multiplications.
2871   // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2872   // exact bit.
2873   if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2874       !isa<ConstantSDNode>(Op1) &&
2875       isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2876     setValue(&I, DAG.getTargetLoweringInfo()
2877                      .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
2878   else
2879     setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2880                              Op1, Op2));
2881 }
2882
2883 void SelectionDAGBuilder::visitICmp(const User &I) {
2884   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2885   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2886     predicate = IC->getPredicate();
2887   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2888     predicate = ICmpInst::Predicate(IC->getPredicate());
2889   SDValue Op1 = getValue(I.getOperand(0));
2890   SDValue Op2 = getValue(I.getOperand(1));
2891   ISD::CondCode Opcode = getICmpCondCode(predicate);
2892
2893   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2894   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2895 }
2896
2897 void SelectionDAGBuilder::visitFCmp(const User &I) {
2898   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2899   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2900     predicate = FC->getPredicate();
2901   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2902     predicate = FCmpInst::Predicate(FC->getPredicate());
2903   SDValue Op1 = getValue(I.getOperand(0));
2904   SDValue Op2 = getValue(I.getOperand(1));
2905   ISD::CondCode Condition = getFCmpCondCode(predicate);
2906   if (TM.Options.NoNaNsFPMath)
2907     Condition = getFCmpCodeWithoutNaN(Condition);
2908   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2909   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2910 }
2911
2912 void SelectionDAGBuilder::visitSelect(const User &I) {
2913   SmallVector<EVT, 4> ValueVTs;
2914   ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
2915   unsigned NumValues = ValueVTs.size();
2916   if (NumValues == 0) return;
2917
2918   SmallVector<SDValue, 4> Values(NumValues);
2919   SDValue Cond     = getValue(I.getOperand(0));
2920   SDValue TrueVal  = getValue(I.getOperand(1));
2921   SDValue FalseVal = getValue(I.getOperand(2));
2922   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2923     ISD::VSELECT : ISD::SELECT;
2924
2925   for (unsigned i = 0; i != NumValues; ++i)
2926     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2927                             TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2928                             Cond,
2929                             SDValue(TrueVal.getNode(),
2930                                     TrueVal.getResNo() + i),
2931                             SDValue(FalseVal.getNode(),
2932                                     FalseVal.getResNo() + i));
2933
2934   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2935                            DAG.getVTList(ValueVTs), Values));
2936 }
2937
2938 void SelectionDAGBuilder::visitTrunc(const User &I) {
2939   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2940   SDValue N = getValue(I.getOperand(0));
2941   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2942   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2943 }
2944
2945 void SelectionDAGBuilder::visitZExt(const User &I) {
2946   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2947   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2948   SDValue N = getValue(I.getOperand(0));
2949   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2950   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2951 }
2952
2953 void SelectionDAGBuilder::visitSExt(const User &I) {
2954   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2955   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2956   SDValue N = getValue(I.getOperand(0));
2957   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2958   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2959 }
2960
2961 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2962   // FPTrunc is never a no-op cast, no need to check
2963   SDValue N = getValue(I.getOperand(0));
2964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2965   EVT DestVT = TLI.getValueType(I.getType());
2966   setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
2967                            DAG.getTargetConstant(0, TLI.getPointerTy())));
2968 }
2969
2970 void SelectionDAGBuilder::visitFPExt(const User &I) {
2971   // FPExt is never a no-op cast, no need to check
2972   SDValue N = getValue(I.getOperand(0));
2973   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2974   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2975 }
2976
2977 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2978   // FPToUI is never a no-op cast, no need to check
2979   SDValue N = getValue(I.getOperand(0));
2980   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2981   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2982 }
2983
2984 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2985   // FPToSI is never a no-op cast, no need to check
2986   SDValue N = getValue(I.getOperand(0));
2987   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2988   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2989 }
2990
2991 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2992   // UIToFP is never a no-op cast, no need to check
2993   SDValue N = getValue(I.getOperand(0));
2994   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2995   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2996 }
2997
2998 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2999   // SIToFP is never a no-op cast, no need to check
3000   SDValue N = getValue(I.getOperand(0));
3001   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3002   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3003 }
3004
3005 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3006   // What to do depends on the size of the integer and the size of the pointer.
3007   // We can either truncate, zero extend, or no-op, accordingly.
3008   SDValue N = getValue(I.getOperand(0));
3009   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3010   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3011 }
3012
3013 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3014   // What to do depends on the size of the integer and the size of the pointer.
3015   // We can either truncate, zero extend, or no-op, accordingly.
3016   SDValue N = getValue(I.getOperand(0));
3017   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3018   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3019 }
3020
3021 void SelectionDAGBuilder::visitBitCast(const User &I) {
3022   SDValue N = getValue(I.getOperand(0));
3023   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3024
3025   // BitCast assures us that source and destination are the same size so this is
3026   // either a BITCAST or a no-op.
3027   if (DestVT != N.getValueType())
3028     setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
3029                              DestVT, N)); // convert types.
3030   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3031   // might fold any kind of constant expression to an integer constant and that
3032   // is not what we are looking for. Only regcognize a bitcast of a genuine
3033   // constant integer as an opaque constant.
3034   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3035     setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
3036                                  /*isOpaque*/true));
3037   else
3038     setValue(&I, N);            // noop cast.
3039 }
3040
3041 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3042   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3043   const Value *SV = I.getOperand(0);
3044   SDValue N = getValue(SV);
3045   EVT DestVT = TLI.getValueType(I.getType());
3046
3047   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3048   unsigned DestAS = I.getType()->getPointerAddressSpace();
3049
3050   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3051     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3052
3053   setValue(&I, N);
3054 }
3055
3056 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3057   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3058   SDValue InVec = getValue(I.getOperand(0));
3059   SDValue InVal = getValue(I.getOperand(1));
3060   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3061                                      getCurSDLoc(), TLI.getVectorIdxTy());
3062   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3063                            TLI.getValueType(I.getType()), InVec, InVal, InIdx));
3064 }
3065
3066 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3068   SDValue InVec = getValue(I.getOperand(0));
3069   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3070                                      getCurSDLoc(), TLI.getVectorIdxTy());
3071   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3072                            TLI.getValueType(I.getType()), InVec, InIdx));
3073 }
3074
3075 // Utility for visitShuffleVector - Return true if every element in Mask,
3076 // beginning from position Pos and ending in Pos+Size, falls within the
3077 // specified sequential range [L, L+Pos). or is undef.
3078 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
3079                                 unsigned Pos, unsigned Size, int Low) {
3080   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3081     if (Mask[i] >= 0 && Mask[i] != Low)
3082       return false;
3083   return true;
3084 }
3085
3086 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3087   SDValue Src1 = getValue(I.getOperand(0));
3088   SDValue Src2 = getValue(I.getOperand(1));
3089
3090   SmallVector<int, 8> Mask;
3091   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3092   unsigned MaskNumElts = Mask.size();
3093
3094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3095   EVT VT = TLI.getValueType(I.getType());
3096   EVT SrcVT = Src1.getValueType();
3097   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3098
3099   if (SrcNumElts == MaskNumElts) {
3100     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3101                                       &Mask[0]));
3102     return;
3103   }
3104
3105   // Normalize the shuffle vector since mask and vector length don't match.
3106   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3107     // Mask is longer than the source vectors and is a multiple of the source
3108     // vectors.  We can use concatenate vector to make the mask and vectors
3109     // lengths match.
3110     if (SrcNumElts*2 == MaskNumElts) {
3111       // First check for Src1 in low and Src2 in high
3112       if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3113           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3114         // The shuffle is concatenating two vectors together.
3115         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3116                                  VT, Src1, Src2));
3117         return;
3118       }
3119       // Then check for Src2 in low and Src1 in high
3120       if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3121           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3122         // The shuffle is concatenating two vectors together.
3123         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3124                                  VT, Src2, Src1));
3125         return;
3126       }
3127     }
3128
3129     // Pad both vectors with undefs to make them the same length as the mask.
3130     unsigned NumConcat = MaskNumElts / SrcNumElts;
3131     bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3132     bool Src2U = Src2.getOpcode() == ISD::UNDEF;
3133     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3134
3135     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3136     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3137     MOps1[0] = Src1;
3138     MOps2[0] = Src2;
3139
3140     Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3141                                                   getCurSDLoc(), VT, MOps1);
3142     Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3143                                                   getCurSDLoc(), VT, MOps2);
3144
3145     // Readjust mask for new input vector length.
3146     SmallVector<int, 8> MappedOps;
3147     for (unsigned i = 0; i != MaskNumElts; ++i) {
3148       int Idx = Mask[i];
3149       if (Idx >= (int)SrcNumElts)
3150         Idx -= SrcNumElts - MaskNumElts;
3151       MappedOps.push_back(Idx);
3152     }
3153
3154     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3155                                       &MappedOps[0]));
3156     return;
3157   }
3158
3159   if (SrcNumElts > MaskNumElts) {
3160     // Analyze the access pattern of the vector to see if we can extract
3161     // two subvectors and do the shuffle. The analysis is done by calculating
3162     // the range of elements the mask access on both vectors.
3163     int MinRange[2] = { static_cast<int>(SrcNumElts),
3164                         static_cast<int>(SrcNumElts)};
3165     int MaxRange[2] = {-1, -1};
3166
3167     for (unsigned i = 0; i != MaskNumElts; ++i) {
3168       int Idx = Mask[i];
3169       unsigned Input = 0;
3170       if (Idx < 0)
3171         continue;
3172
3173       if (Idx >= (int)SrcNumElts) {
3174         Input = 1;
3175         Idx -= SrcNumElts;
3176       }
3177       if (Idx > MaxRange[Input])
3178         MaxRange[Input] = Idx;
3179       if (Idx < MinRange[Input])
3180         MinRange[Input] = Idx;
3181     }
3182
3183     // Check if the access is smaller than the vector size and can we find
3184     // a reasonable extract index.
3185     int RangeUse[2] = { -1, -1 };  // 0 = Unused, 1 = Extract, -1 = Can not
3186                                    // Extract.
3187     int StartIdx[2];  // StartIdx to extract from
3188     for (unsigned Input = 0; Input < 2; ++Input) {
3189       if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
3190         RangeUse[Input] = 0; // Unused
3191         StartIdx[Input] = 0;
3192         continue;
3193       }
3194
3195       // Find a good start index that is a multiple of the mask length. Then
3196       // see if the rest of the elements are in range.
3197       StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3198       if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3199           StartIdx[Input] + MaskNumElts <= SrcNumElts)
3200         RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3201     }
3202
3203     if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3204       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3205       return;
3206     }
3207     if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3208       // Extract appropriate subvector and generate a vector shuffle
3209       for (unsigned Input = 0; Input < 2; ++Input) {
3210         SDValue &Src = Input == 0 ? Src1 : Src2;
3211         if (RangeUse[Input] == 0)
3212           Src = DAG.getUNDEF(VT);
3213         else
3214           Src = DAG.getNode(
3215               ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT, Src,
3216               DAG.getConstant(StartIdx[Input], TLI.getVectorIdxTy()));
3217       }
3218
3219       // Calculate new mask.
3220       SmallVector<int, 8> MappedOps;
3221       for (unsigned i = 0; i != MaskNumElts; ++i) {
3222         int Idx = Mask[i];
3223         if (Idx >= 0) {
3224           if (Idx < (int)SrcNumElts)
3225             Idx -= StartIdx[0];
3226           else
3227             Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3228         }
3229         MappedOps.push_back(Idx);
3230       }
3231
3232       setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3233                                         &MappedOps[0]));
3234       return;
3235     }
3236   }
3237
3238   // We can't use either concat vectors or extract subvectors so fall back to
3239   // replacing the shuffle with extract and build vector.
3240   // to insert and build vector.
3241   EVT EltVT = VT.getVectorElementType();
3242   EVT IdxVT = TLI.getVectorIdxTy();
3243   SmallVector<SDValue,8> Ops;
3244   for (unsigned i = 0; i != MaskNumElts; ++i) {
3245     int Idx = Mask[i];
3246     SDValue Res;
3247
3248     if (Idx < 0) {
3249       Res = DAG.getUNDEF(EltVT);
3250     } else {
3251       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3252       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3253
3254       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3255                         EltVT, Src, DAG.getConstant(Idx, IdxVT));
3256     }
3257
3258     Ops.push_back(Res);
3259   }
3260
3261   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
3262 }
3263
3264 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3265   const Value *Op0 = I.getOperand(0);
3266   const Value *Op1 = I.getOperand(1);
3267   Type *AggTy = I.getType();
3268   Type *ValTy = Op1->getType();
3269   bool IntoUndef = isa<UndefValue>(Op0);
3270   bool FromUndef = isa<UndefValue>(Op1);
3271
3272   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3273
3274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3275   SmallVector<EVT, 4> AggValueVTs;
3276   ComputeValueVTs(TLI, AggTy, AggValueVTs);
3277   SmallVector<EVT, 4> ValValueVTs;
3278   ComputeValueVTs(TLI, ValTy, ValValueVTs);
3279
3280   unsigned NumAggValues = AggValueVTs.size();
3281   unsigned NumValValues = ValValueVTs.size();
3282   SmallVector<SDValue, 4> Values(NumAggValues);
3283
3284   // Ignore an insertvalue that produces an empty object
3285   if (!NumAggValues) {
3286     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3287     return;
3288   }
3289
3290   SDValue Agg = getValue(Op0);
3291   unsigned i = 0;
3292   // Copy the beginning value(s) from the original aggregate.
3293   for (; i != LinearIndex; ++i)
3294     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3295                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3296   // Copy values from the inserted value(s).
3297   if (NumValValues) {
3298     SDValue Val = getValue(Op1);
3299     for (; i != LinearIndex + NumValValues; ++i)
3300       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3301                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3302   }
3303   // Copy remaining value(s) from the original aggregate.
3304   for (; i != NumAggValues; ++i)
3305     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3306                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3307
3308   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3309                            DAG.getVTList(AggValueVTs), Values));
3310 }
3311
3312 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3313   const Value *Op0 = I.getOperand(0);
3314   Type *AggTy = Op0->getType();
3315   Type *ValTy = I.getType();
3316   bool OutOfUndef = isa<UndefValue>(Op0);
3317
3318   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3319
3320   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3321   SmallVector<EVT, 4> ValValueVTs;
3322   ComputeValueVTs(TLI, ValTy, ValValueVTs);
3323
3324   unsigned NumValValues = ValValueVTs.size();
3325
3326   // Ignore a extractvalue that produces an empty object
3327   if (!NumValValues) {
3328     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3329     return;
3330   }
3331
3332   SmallVector<SDValue, 4> Values(NumValValues);
3333
3334   SDValue Agg = getValue(Op0);
3335   // Copy out the selected value(s).
3336   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3337     Values[i - LinearIndex] =
3338       OutOfUndef ?
3339         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3340         SDValue(Agg.getNode(), Agg.getResNo() + i);
3341
3342   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3343                            DAG.getVTList(ValValueVTs), Values));
3344 }
3345
3346 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3347   Value *Op0 = I.getOperand(0);
3348   // Note that the pointer operand may be a vector of pointers. Take the scalar
3349   // element which holds a pointer.
3350   Type *Ty = Op0->getType()->getScalarType();
3351   unsigned AS = Ty->getPointerAddressSpace();
3352   SDValue N = getValue(Op0);
3353
3354   for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3355        OI != E; ++OI) {
3356     const Value *Idx = *OI;
3357     if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3358       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3359       if (Field) {
3360         // N = N + Offset
3361         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3362         N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3363                         DAG.getConstant(Offset, N.getValueType()));
3364       }
3365
3366       Ty = StTy->getElementType(Field);
3367     } else {
3368       Ty = cast<SequentialType>(Ty)->getElementType();
3369
3370       // If this is a constant subscript, handle it quickly.
3371       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3372       if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3373         if (CI->isZero()) continue;
3374         uint64_t Offs =
3375             DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3376         SDValue OffsVal;
3377         EVT PTy = TLI.getPointerTy(AS);
3378         unsigned PtrBits = PTy.getSizeInBits();
3379         if (PtrBits < 64)
3380           OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
3381                                 DAG.getConstant(Offs, MVT::i64));
3382         else
3383           OffsVal = DAG.getConstant(Offs, PTy);
3384
3385         N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3386                         OffsVal);
3387         continue;
3388       }
3389
3390       // N = N + Idx * ElementSize;
3391       APInt ElementSize =
3392           APInt(TLI.getPointerSizeInBits(AS), DL->getTypeAllocSize(Ty));
3393       SDValue IdxN = getValue(Idx);
3394
3395       // If the index is smaller or larger than intptr_t, truncate or extend
3396       // it.
3397       IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
3398
3399       // If this is a multiply by a power of two, turn it into a shl
3400       // immediately.  This is a very common case.
3401       if (ElementSize != 1) {
3402         if (ElementSize.isPowerOf2()) {
3403           unsigned Amt = ElementSize.logBase2();
3404           IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
3405                              N.getValueType(), IdxN,
3406                              DAG.getConstant(Amt, IdxN.getValueType()));
3407         } else {
3408           SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
3409           IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
3410                              N.getValueType(), IdxN, Scale);
3411         }
3412       }
3413
3414       N = DAG.getNode(ISD::ADD, getCurSDLoc(),
3415                       N.getValueType(), N, IdxN);
3416     }
3417   }
3418
3419   setValue(&I, N);
3420 }
3421
3422 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3423   // If this is a fixed sized alloca in the entry block of the function,
3424   // allocate it statically on the stack.
3425   if (FuncInfo.StaticAllocaMap.count(&I))
3426     return;   // getValue will auto-populate this.
3427
3428   Type *Ty = I.getAllocatedType();
3429   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3430   uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
3431   unsigned Align =
3432       std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
3433                I.getAlignment());
3434
3435   SDValue AllocSize = getValue(I.getArraySize());
3436
3437   EVT IntPtr = TLI.getPointerTy();
3438   if (AllocSize.getValueType() != IntPtr)
3439     AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
3440
3441   AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
3442                           AllocSize,
3443                           DAG.getConstant(TySize, IntPtr));
3444
3445   // Handle alignment.  If the requested alignment is less than or equal to
3446   // the stack alignment, ignore it.  If the size is greater than or equal to
3447   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3448   unsigned StackAlign =
3449       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3450   if (Align <= StackAlign)
3451     Align = 0;
3452
3453   // Round the size of the allocation up to the stack alignment size
3454   // by add SA-1 to the size.
3455   AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
3456                           AllocSize.getValueType(), AllocSize,
3457                           DAG.getIntPtrConstant(StackAlign-1));
3458
3459   // Mask out the low bits for alignment purposes.
3460   AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
3461                           AllocSize.getValueType(), AllocSize,
3462                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3463
3464   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3465   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3466   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
3467   setValue(&I, DSA);
3468   DAG.setRoot(DSA.getValue(1));
3469
3470   assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
3471 }
3472
3473 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3474   if (I.isAtomic())
3475     return visitAtomicLoad(I);
3476
3477   const Value *SV = I.getOperand(0);
3478   SDValue Ptr = getValue(SV);
3479
3480   Type *Ty = I.getType();
3481
3482   bool isVolatile = I.isVolatile();
3483   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3484   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3485   unsigned Alignment = I.getAlignment();
3486
3487   AAMDNodes AAInfo;
3488   I.getAAMetadata(AAInfo);
3489   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3490
3491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3492   SmallVector<EVT, 4> ValueVTs;
3493   SmallVector<uint64_t, 4> Offsets;
3494   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3495   unsigned NumValues = ValueVTs.size();
3496   if (NumValues == 0)
3497     return;
3498
3499   SDValue Root;
3500   bool ConstantMemory = false;
3501   if (isVolatile || NumValues > MaxParallelChains)
3502     // Serialize volatile loads with other side effects.
3503     Root = getRoot();
3504   else if (AA->pointsToConstantMemory(
3505              AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
3506     // Do not serialize (non-volatile) loads of constant memory with anything.
3507     Root = DAG.getEntryNode();
3508     ConstantMemory = true;
3509   } else {
3510     // Do not serialize non-volatile loads against each other.
3511     Root = DAG.getRoot();
3512   }
3513
3514   if (isVolatile)
3515     Root = TLI.prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
3516
3517   SmallVector<SDValue, 4> Values(NumValues);
3518   SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3519                                           NumValues));
3520   EVT PtrVT = Ptr.getValueType();
3521   unsigned ChainI = 0;
3522   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3523     // Serializing loads here may result in excessive register pressure, and
3524     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3525     // could recover a bit by hoisting nodes upward in the chain by recognizing
3526     // they are side-effect free or do not alias. The optimizer should really
3527     // avoid this case by converting large object/array copies to llvm.memcpy
3528     // (MaxParallelChains should always remain as failsafe).
3529     if (ChainI == MaxParallelChains) {
3530       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3531       SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3532                                   makeArrayRef(Chains.data(), ChainI));
3533       Root = Chain;
3534       ChainI = 0;
3535     }
3536     SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
3537                             PtrVT, Ptr,
3538                             DAG.getConstant(Offsets[i], PtrVT));
3539     SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
3540                             A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3541                             isNonTemporal, isInvariant, Alignment, AAInfo,
3542                             Ranges);
3543
3544     Values[i] = L;
3545     Chains[ChainI] = L.getValue(1);
3546   }
3547
3548   if (!ConstantMemory) {
3549     SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3550                                 makeArrayRef(Chains.data(), ChainI));
3551     if (isVolatile)
3552       DAG.setRoot(Chain);
3553     else
3554       PendingLoads.push_back(Chain);
3555   }
3556
3557   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3558                            DAG.getVTList(ValueVTs), Values));
3559 }
3560
3561 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3562   if (I.isAtomic())
3563     return visitAtomicStore(I);
3564
3565   const Value *SrcV = I.getOperand(0);
3566   const Value *PtrV = I.getOperand(1);
3567
3568   SmallVector<EVT, 4> ValueVTs;
3569   SmallVector<uint64_t, 4> Offsets;
3570   ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
3571                   ValueVTs, &Offsets);
3572   unsigned NumValues = ValueVTs.size();
3573   if (NumValues == 0)
3574     return;
3575
3576   // Get the lowered operands. Note that we do this after
3577   // checking if NumResults is zero, because with zero results
3578   // the operands won't have values in the map.
3579   SDValue Src = getValue(SrcV);
3580   SDValue Ptr = getValue(PtrV);
3581
3582   SDValue Root = getRoot();
3583   SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3584                                           NumValues));
3585   EVT PtrVT = Ptr.getValueType();
3586   bool isVolatile = I.isVolatile();
3587   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3588   unsigned Alignment = I.getAlignment();
3589
3590   AAMDNodes AAInfo;
3591   I.getAAMetadata(AAInfo);
3592
3593   unsigned ChainI = 0;
3594   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3595     // See visitLoad comments.
3596     if (ChainI == MaxParallelChains) {
3597       SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3598                                   makeArrayRef(Chains.data(), ChainI));
3599       Root = Chain;
3600       ChainI = 0;
3601     }
3602     SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
3603                               DAG.getConstant(Offsets[i], PtrVT));
3604     SDValue St = DAG.getStore(Root, getCurSDLoc(),
3605                               SDValue(Src.getNode(), Src.getResNo() + i),
3606                               Add, MachinePointerInfo(PtrV, Offsets[i]),
3607                               isVolatile, isNonTemporal, Alignment, AAInfo);
3608     Chains[ChainI] = St;
3609   }
3610
3611   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3612                                   makeArrayRef(Chains.data(), ChainI));
3613   DAG.setRoot(StoreNode);
3614 }
3615
3616 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3617   SDLoc dl = getCurSDLoc();
3618   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3619   AtomicOrdering FailureOrder = I.getFailureOrdering();
3620   SynchronizationScope Scope = I.getSynchScope();
3621
3622   SDValue InChain = getRoot();
3623
3624   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3625   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3626   SDValue L = DAG.getAtomicCmpSwap(
3627       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3628       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3629       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3630       /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3631
3632   SDValue OutChain = L.getValue(2);
3633
3634   setValue(&I, L);
3635   DAG.setRoot(OutChain);
3636 }
3637
3638 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3639   SDLoc dl = getCurSDLoc();
3640   ISD::NodeType NT;
3641   switch (I.getOperation()) {
3642   default: llvm_unreachable("Unknown atomicrmw operation");
3643   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3644   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
3645   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
3646   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
3647   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3648   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
3649   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
3650   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
3651   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
3652   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3653   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3654   }
3655   AtomicOrdering Order = I.getOrdering();
3656   SynchronizationScope Scope = I.getSynchScope();
3657
3658   SDValue InChain = getRoot();
3659
3660   SDValue L =
3661     DAG.getAtomic(NT, dl,
3662                   getValue(I.getValOperand()).getSimpleValueType(),
3663                   InChain,
3664                   getValue(I.getPointerOperand()),
3665                   getValue(I.getValOperand()),
3666                   I.getPointerOperand(),
3667                   /* Alignment=*/ 0, Order, Scope);
3668
3669   SDValue OutChain = L.getValue(1);
3670
3671   setValue(&I, L);
3672   DAG.setRoot(OutChain);
3673 }
3674
3675 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3676   SDLoc dl = getCurSDLoc();
3677   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3678   SDValue Ops[3];
3679   Ops[0] = getRoot();
3680   Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3681   Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
3682   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3683 }
3684
3685 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3686   SDLoc dl = getCurSDLoc();
3687   AtomicOrdering Order = I.getOrdering();
3688   SynchronizationScope Scope = I.getSynchScope();
3689
3690   SDValue InChain = getRoot();
3691
3692   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3693   EVT VT = TLI.getValueType(I.getType());
3694
3695   if (I.getAlignment() < VT.getSizeInBits() / 8)
3696     report_fatal_error("Cannot generate unaligned atomic load");
3697
3698   MachineMemOperand *MMO =
3699       DAG.getMachineFunction().
3700       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3701                            MachineMemOperand::MOVolatile |
3702                            MachineMemOperand::MOLoad,
3703                            VT.getStoreSize(),
3704                            I.getAlignment() ? I.getAlignment() :
3705                                               DAG.getEVTAlignment(VT));
3706
3707   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3708   SDValue L =
3709       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3710                     getValue(I.getPointerOperand()), MMO,
3711