LLVM  mainline
SelectionDAGBuilder.cpp
Go to the documentation of this file.
00001 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements routines for translating from LLVM IR into SelectionDAG IR.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "SelectionDAGBuilder.h"
00015 #include "SDNodeDbgValue.h"
00016 #include "llvm/ADT/BitVector.h"
00017 #include "llvm/ADT/Optional.h"
00018 #include "llvm/ADT/SmallSet.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/Analysis/BranchProbabilityInfo.h"
00022 #include "llvm/Analysis/ConstantFolding.h"
00023 #include "llvm/Analysis/TargetLibraryInfo.h"
00024 #include "llvm/Analysis/ValueTracking.h"
00025 #include "llvm/CodeGen/FastISel.h"
00026 #include "llvm/CodeGen/FunctionLoweringInfo.h"
00027 #include "llvm/CodeGen/GCMetadata.h"
00028 #include "llvm/CodeGen/GCStrategy.h"
00029 #include "llvm/CodeGen/MachineFrameInfo.h"
00030 #include "llvm/CodeGen/MachineFunction.h"
00031 #include "llvm/CodeGen/MachineInstrBuilder.h"
00032 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00033 #include "llvm/CodeGen/MachineModuleInfo.h"
00034 #include "llvm/CodeGen/MachineRegisterInfo.h"
00035 #include "llvm/CodeGen/SelectionDAG.h"
00036 #include "llvm/CodeGen/StackMaps.h"
00037 #include "llvm/CodeGen/WinEHFuncInfo.h"
00038 #include "llvm/IR/CallingConv.h"
00039 #include "llvm/IR/Constants.h"
00040 #include "llvm/IR/DataLayout.h"
00041 #include "llvm/IR/DebugInfo.h"
00042 #include "llvm/IR/DerivedTypes.h"
00043 #include "llvm/IR/Function.h"
00044 #include "llvm/IR/GlobalVariable.h"
00045 #include "llvm/IR/InlineAsm.h"
00046 #include "llvm/IR/Instructions.h"
00047 #include "llvm/IR/IntrinsicInst.h"
00048 #include "llvm/IR/Intrinsics.h"
00049 #include "llvm/IR/LLVMContext.h"
00050 #include "llvm/IR/Module.h"
00051 #include "llvm/IR/Statepoint.h"
00052 #include "llvm/MC/MCSymbol.h"
00053 #include "llvm/Support/CommandLine.h"
00054 #include "llvm/Support/Debug.h"
00055 #include "llvm/Support/ErrorHandling.h"
00056 #include "llvm/Support/MathExtras.h"
00057 #include "llvm/Support/raw_ostream.h"
00058 #include "llvm/Target/TargetFrameLowering.h"
00059 #include "llvm/Target/TargetInstrInfo.h"
00060 #include "llvm/Target/TargetIntrinsicInfo.h"
00061 #include "llvm/Target/TargetLowering.h"
00062 #include "llvm/Target/TargetOptions.h"
00063 #include "llvm/Target/TargetSelectionDAGInfo.h"
00064 #include "llvm/Target/TargetSubtargetInfo.h"
00065 #include <algorithm>
00066 using namespace llvm;
00067 
00068 #define DEBUG_TYPE "isel"
00069 
00070 /// LimitFloatPrecision - Generate low-precision inline sequences for
00071 /// some float libcalls (6, 8 or 12 bits).
00072 static unsigned LimitFloatPrecision;
00073 
00074 static cl::opt<unsigned, true>
00075 LimitFPPrecision("limit-float-precision",
00076                  cl::desc("Generate low-precision inline sequences "
00077                           "for some float libcalls"),
00078                  cl::location(LimitFloatPrecision),
00079                  cl::init(0));
00080 
00081 // Limit the width of DAG chains. This is important in general to prevent
00082 // prevent DAG-based analysis from blowing up. For example, alias analysis and
00083 // load clustering may not complete in reasonable time. It is difficult to
00084 // recognize and avoid this situation within each individual analysis, and
00085 // future analyses are likely to have the same behavior. Limiting DAG width is
00086 // the safe approach, and will be especially important with global DAGs.
00087 //
00088 // MaxParallelChains default is arbitrarily high to avoid affecting
00089 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
00090 // sequence over this should have been converted to llvm.memcpy by the
00091 // frontend. It easy to induce this behavior with .ll code such as:
00092 // %buffer = alloca [4096 x i8]
00093 // %data = load [4096 x i8]* %argPtr
00094 // store [4096 x i8] %data, [4096 x i8]* %buffer
00095 static const unsigned MaxParallelChains = 64;
00096 
00097 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
00098                                       const SDValue *Parts, unsigned NumParts,
00099                                       MVT PartVT, EVT ValueVT, const Value *V);
00100 
00101 /// getCopyFromParts - Create a value that contains the specified legal parts
00102 /// combined into the value they represent.  If the parts combine to a type
00103 /// larger then ValueVT then AssertOp can be used to specify whether the extra
00104 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
00105 /// (ISD::AssertSext).
00106 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
00107                                 const SDValue *Parts,
00108                                 unsigned NumParts, MVT PartVT, EVT ValueVT,
00109                                 const Value *V,
00110                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
00111   if (ValueVT.isVector())
00112     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
00113                                   PartVT, ValueVT, V);
00114 
00115   assert(NumParts > 0 && "No parts to assemble!");
00116   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00117   SDValue Val = Parts[0];
00118 
00119   if (NumParts > 1) {
00120     // Assemble the value from multiple parts.
00121     if (ValueVT.isInteger()) {
00122       unsigned PartBits = PartVT.getSizeInBits();
00123       unsigned ValueBits = ValueVT.getSizeInBits();
00124 
00125       // Assemble the power of 2 part.
00126       unsigned RoundParts = NumParts & (NumParts - 1) ?
00127         1 << Log2_32(NumParts) : NumParts;
00128       unsigned RoundBits = PartBits * RoundParts;
00129       EVT RoundVT = RoundBits == ValueBits ?
00130         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
00131       SDValue Lo, Hi;
00132 
00133       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
00134 
00135       if (RoundParts > 2) {
00136         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
00137                               PartVT, HalfVT, V);
00138         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
00139                               RoundParts / 2, PartVT, HalfVT, V);
00140       } else {
00141         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
00142         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
00143       }
00144 
00145       if (TLI.isBigEndian())
00146         std::swap(Lo, Hi);
00147 
00148       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
00149 
00150       if (RoundParts < NumParts) {
00151         // Assemble the trailing non-power-of-2 part.
00152         unsigned OddParts = NumParts - RoundParts;
00153         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
00154         Hi = getCopyFromParts(DAG, DL,
00155                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
00156 
00157         // Combine the round and odd parts.
00158         Lo = Val;
00159         if (TLI.isBigEndian())
00160           std::swap(Lo, Hi);
00161         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00162         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
00163         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
00164                          DAG.getConstant(Lo.getValueType().getSizeInBits(), DL,
00165                                          TLI.getPointerTy()));
00166         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
00167         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
00168       }
00169     } else if (PartVT.isFloatingPoint()) {
00170       // FP split into multiple FP parts (for ppcf128)
00171       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
00172              "Unexpected split");
00173       SDValue Lo, Hi;
00174       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
00175       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
00176       if (TLI.hasBigEndianPartOrdering(ValueVT))
00177         std::swap(Lo, Hi);
00178       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
00179     } else {
00180       // FP split into integer parts (soft fp)
00181       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
00182              !PartVT.isVector() && "Unexpected split");
00183       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
00184       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
00185     }
00186   }
00187 
00188   // There is now one part, held in Val.  Correct it to match ValueVT.
00189   EVT PartEVT = Val.getValueType();
00190 
00191   if (PartEVT == ValueVT)
00192     return Val;
00193 
00194   if (PartEVT.isInteger() && ValueVT.isInteger()) {
00195     if (ValueVT.bitsLT(PartEVT)) {
00196       // For a truncate, see if we have any information to
00197       // indicate whether the truncated bits will always be
00198       // zero or sign-extension.
00199       if (AssertOp != ISD::DELETED_NODE)
00200         Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
00201                           DAG.getValueType(ValueVT));
00202       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
00203     }
00204     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
00205   }
00206 
00207   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
00208     // FP_ROUND's are always exact here.
00209     if (ValueVT.bitsLT(Val.getValueType()))
00210       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
00211                          DAG.getTargetConstant(1, DL, TLI.getPointerTy()));
00212 
00213     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
00214   }
00215 
00216   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
00217     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
00218 
00219   llvm_unreachable("Unknown mismatch!");
00220 }
00221 
00222 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
00223                                               const Twine &ErrMsg) {
00224   const Instruction *I = dyn_cast_or_null<Instruction>(V);
00225   if (!V)
00226     return Ctx.emitError(ErrMsg);
00227 
00228   const char *AsmError = ", possible invalid constraint for vector type";
00229   if (const CallInst *CI = dyn_cast<CallInst>(I))
00230     if (isa<InlineAsm>(CI->getCalledValue()))
00231       return Ctx.emitError(I, ErrMsg + AsmError);
00232 
00233   return Ctx.emitError(I, ErrMsg);
00234 }
00235 
00236 /// getCopyFromPartsVector - Create a value that contains the specified legal
00237 /// parts combined into the value they represent.  If the parts combine to a
00238 /// type larger then ValueVT then AssertOp can be used to specify whether the
00239 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
00240 /// ValueVT (ISD::AssertSext).
00241 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
00242                                       const SDValue *Parts, unsigned NumParts,
00243                                       MVT PartVT, EVT ValueVT, const Value *V) {
00244   assert(ValueVT.isVector() && "Not a vector value");
00245   assert(NumParts > 0 && "No parts to assemble!");
00246   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00247   SDValue Val = Parts[0];
00248 
00249   // Handle a multi-element vector.
00250   if (NumParts > 1) {
00251     EVT IntermediateVT;
00252     MVT RegisterVT;
00253     unsigned NumIntermediates;
00254     unsigned NumRegs =
00255     TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
00256                                NumIntermediates, RegisterVT);
00257     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
00258     NumParts = NumRegs; // Silence a compiler warning.
00259     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
00260     assert(RegisterVT == Parts[0].getSimpleValueType() &&
00261            "Part type doesn't match part!");
00262 
00263     // Assemble the parts into intermediate operands.
00264     SmallVector<SDValue, 8> Ops(NumIntermediates);
00265     if (NumIntermediates == NumParts) {
00266       // If the register was not expanded, truncate or copy the value,
00267       // as appropriate.
00268       for (unsigned i = 0; i != NumParts; ++i)
00269         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
00270                                   PartVT, IntermediateVT, V);
00271     } else if (NumParts > 0) {
00272       // If the intermediate type was expanded, build the intermediate
00273       // operands from the parts.
00274       assert(NumParts % NumIntermediates == 0 &&
00275              "Must expand into a divisible number of parts!");
00276       unsigned Factor = NumParts / NumIntermediates;
00277       for (unsigned i = 0; i != NumIntermediates; ++i)
00278         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
00279                                   PartVT, IntermediateVT, V);
00280     }
00281 
00282     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
00283     // intermediate operands.
00284     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
00285                                                 : ISD::BUILD_VECTOR,
00286                       DL, ValueVT, Ops);
00287   }
00288 
00289   // There is now one part, held in Val.  Correct it to match ValueVT.
00290   EVT PartEVT = Val.getValueType();
00291 
00292   if (PartEVT == ValueVT)
00293     return Val;
00294 
00295   if (PartEVT.isVector()) {
00296     // If the element type of the source/dest vectors are the same, but the
00297     // parts vector has more elements than the value vector, then we have a
00298     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
00299     // elements we want.
00300     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
00301       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
00302              "Cannot narrow, it would be a lossy transformation");
00303       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
00304                          DAG.getConstant(0, DL, TLI.getVectorIdxTy()));
00305     }
00306 
00307     // Vector/Vector bitcast.
00308     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
00309       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
00310 
00311     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
00312       "Cannot handle this kind of promotion");
00313     // Promoted vector extract
00314     bool Smaller = ValueVT.bitsLE(PartEVT);
00315     return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00316                        DL, ValueVT, Val);
00317 
00318   }
00319 
00320   // Trivial bitcast if the types are the same size and the destination
00321   // vector type is legal.
00322   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
00323       TLI.isTypeLegal(ValueVT))
00324     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
00325 
00326   // Handle cases such as i8 -> <1 x i1>
00327   if (ValueVT.getVectorNumElements() != 1) {
00328     diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
00329                                       "non-trivial scalar-to-vector conversion");
00330     return DAG.getUNDEF(ValueVT);
00331   }
00332 
00333   if (ValueVT.getVectorNumElements() == 1 &&
00334       ValueVT.getVectorElementType() != PartEVT) {
00335     bool Smaller = ValueVT.bitsLE(PartEVT);
00336     Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00337                        DL, ValueVT.getScalarType(), Val);
00338   }
00339 
00340   return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
00341 }
00342 
00343 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
00344                                  SDValue Val, SDValue *Parts, unsigned NumParts,
00345                                  MVT PartVT, const Value *V);
00346 
00347 /// getCopyToParts - Create a series of nodes that contain the specified value
00348 /// split into legal parts.  If the parts contain more bits than Val, then, for
00349 /// integers, ExtendKind can be used to specify how to generate the extra bits.
00350 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
00351                            SDValue Val, SDValue *Parts, unsigned NumParts,
00352                            MVT PartVT, const Value *V,
00353                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
00354   EVT ValueVT = Val.getValueType();
00355 
00356   // Handle the vector case separately.
00357   if (ValueVT.isVector())
00358     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
00359 
00360   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00361   unsigned PartBits = PartVT.getSizeInBits();
00362   unsigned OrigNumParts = NumParts;
00363   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
00364 
00365   if (NumParts == 0)
00366     return;
00367 
00368   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
00369   EVT PartEVT = PartVT;
00370   if (PartEVT == ValueVT) {
00371     assert(NumParts == 1 && "No-op copy with multiple parts!");
00372     Parts[0] = Val;
00373     return;
00374   }
00375 
00376   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
00377     // If the parts cover more bits than the value has, promote the value.
00378     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
00379       assert(NumParts == 1 && "Do not know what to promote to!");
00380       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
00381     } else {
00382       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
00383              ValueVT.isInteger() &&
00384              "Unknown mismatch!");
00385       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00386       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
00387       if (PartVT == MVT::x86mmx)
00388         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00389     }
00390   } else if (PartBits == ValueVT.getSizeInBits()) {
00391     // Different types of the same size.
00392     assert(NumParts == 1 && PartEVT != ValueVT);
00393     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00394   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
00395     // If the parts cover less bits than value has, truncate the value.
00396     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
00397            ValueVT.isInteger() &&
00398            "Unknown mismatch!");
00399     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00400     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
00401     if (PartVT == MVT::x86mmx)
00402       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00403   }
00404 
00405   // The value may have changed - recompute ValueVT.
00406   ValueVT = Val.getValueType();
00407   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
00408          "Failed to tile the value with PartVT!");
00409 
00410   if (NumParts == 1) {
00411     if (PartEVT != ValueVT)
00412       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
00413                                         "scalar-to-vector conversion failed");
00414 
00415     Parts[0] = Val;
00416     return;
00417   }
00418 
00419   // Expand the value into multiple parts.
00420   if (NumParts & (NumParts - 1)) {
00421     // The number of parts is not a power of 2.  Split off and copy the tail.
00422     assert(PartVT.isInteger() && ValueVT.isInteger() &&
00423            "Do not know what to expand to!");
00424     unsigned RoundParts = 1 << Log2_32(NumParts);
00425     unsigned RoundBits = RoundParts * PartBits;
00426     unsigned OddParts = NumParts - RoundParts;
00427     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
00428                                  DAG.getIntPtrConstant(RoundBits, DL));
00429     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
00430 
00431     if (TLI.isBigEndian())
00432       // The odd parts were reversed by getCopyToParts - unreverse them.
00433       std::reverse(Parts + RoundParts, Parts + NumParts);
00434 
00435     NumParts = RoundParts;
00436     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00437     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
00438   }
00439 
00440   // The number of parts is a power of 2.  Repeatedly bisect the value using
00441   // EXTRACT_ELEMENT.
00442   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
00443                          EVT::getIntegerVT(*DAG.getContext(),
00444                                            ValueVT.getSizeInBits()),
00445                          Val);
00446 
00447   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
00448     for (unsigned i = 0; i < NumParts; i += StepSize) {
00449       unsigned ThisBits = StepSize * PartBits / 2;
00450       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
00451       SDValue &Part0 = Parts[i];
00452       SDValue &Part1 = Parts[i+StepSize/2];
00453 
00454       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
00455                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
00456       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
00457                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
00458 
00459       if (ThisBits == PartBits && ThisVT != PartVT) {
00460         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
00461         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
00462       }
00463     }
00464   }
00465 
00466   if (TLI.isBigEndian())
00467     std::reverse(Parts, Parts + OrigNumParts);
00468 }
00469 
00470 
00471 /// getCopyToPartsVector - Create a series of nodes that contain the specified
00472 /// value split into legal parts.
00473 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
00474                                  SDValue Val, SDValue *Parts, unsigned NumParts,
00475                                  MVT PartVT, const Value *V) {
00476   EVT ValueVT = Val.getValueType();
00477   assert(ValueVT.isVector() && "Not a vector");
00478   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00479 
00480   if (NumParts == 1) {
00481     EVT PartEVT = PartVT;
00482     if (PartEVT == ValueVT) {
00483       // Nothing to do.
00484     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
00485       // Bitconvert vector->vector case.
00486       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00487     } else if (PartVT.isVector() &&
00488                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
00489                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
00490       EVT ElementVT = PartVT.getVectorElementType();
00491       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
00492       // undef elements.
00493       SmallVector<SDValue, 16> Ops;
00494       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
00495         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
00496                                   ElementVT, Val, DAG.getConstant(i, DL,
00497                                                   TLI.getVectorIdxTy())));
00498 
00499       for (unsigned i = ValueVT.getVectorNumElements(),
00500            e = PartVT.getVectorNumElements(); i != e; ++i)
00501         Ops.push_back(DAG.getUNDEF(ElementVT));
00502 
00503       Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
00504 
00505       // FIXME: Use CONCAT for 2x -> 4x.
00506 
00507       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
00508       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
00509     } else if (PartVT.isVector() &&
00510                PartEVT.getVectorElementType().bitsGE(
00511                  ValueVT.getVectorElementType()) &&
00512                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
00513 
00514       // Promoted vector extract
00515       bool Smaller = PartEVT.bitsLE(ValueVT);
00516       Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00517                         DL, PartVT, Val);
00518     } else{
00519       // Vector -> scalar conversion.
00520       assert(ValueVT.getVectorNumElements() == 1 &&
00521              "Only trivial vector-to-scalar conversions should get here!");
00522       Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
00523                         PartVT, Val,
00524                         DAG.getConstant(0, DL, TLI.getVectorIdxTy()));
00525 
00526       bool Smaller = ValueVT.bitsLE(PartVT);
00527       Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00528                          DL, PartVT, Val);
00529     }
00530 
00531     Parts[0] = Val;
00532     return;
00533   }
00534 
00535   // Handle a multi-element vector.
00536   EVT IntermediateVT;
00537   MVT RegisterVT;
00538   unsigned NumIntermediates;
00539   unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
00540                                                 IntermediateVT,
00541                                                 NumIntermediates, RegisterVT);
00542   unsigned NumElements = ValueVT.getVectorNumElements();
00543 
00544   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
00545   NumParts = NumRegs; // Silence a compiler warning.
00546   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
00547 
00548   // Split the vector into intermediate operands.
00549   SmallVector<SDValue, 8> Ops(NumIntermediates);
00550   for (unsigned i = 0; i != NumIntermediates; ++i) {
00551     if (IntermediateVT.isVector())
00552       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
00553                            IntermediateVT, Val,
00554                    DAG.getConstant(i * (NumElements / NumIntermediates), DL,
00555                                    TLI.getVectorIdxTy()));
00556     else
00557       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
00558                            IntermediateVT, Val,
00559                            DAG.getConstant(i, DL, TLI.getVectorIdxTy()));
00560   }
00561 
00562   // Split the intermediate operands into legal parts.
00563   if (NumParts == NumIntermediates) {
00564     // If the register was not expanded, promote or copy the value,
00565     // as appropriate.
00566     for (unsigned i = 0; i != NumParts; ++i)
00567       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
00568   } else if (NumParts > 0) {
00569     // If the intermediate type was expanded, split each the value into
00570     // legal parts.
00571     assert(NumIntermediates != 0 && "division by zero");
00572     assert(NumParts % NumIntermediates == 0 &&
00573            "Must expand into a divisible number of parts!");
00574     unsigned Factor = NumParts / NumIntermediates;
00575     for (unsigned i = 0; i != NumIntermediates; ++i)
00576       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
00577   }
00578 }
00579 
00580 RegsForValue::RegsForValue() {}
00581 
00582 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
00583                            EVT valuevt)
00584     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
00585 
00586 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &tli,
00587                            unsigned Reg, Type *Ty) {
00588   ComputeValueVTs(tli, Ty, ValueVTs);
00589 
00590   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
00591     EVT ValueVT = ValueVTs[Value];
00592     unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
00593     MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
00594     for (unsigned i = 0; i != NumRegs; ++i)
00595       Regs.push_back(Reg + i);
00596     RegVTs.push_back(RegisterVT);
00597     Reg += NumRegs;
00598   }
00599 }
00600 
00601 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
00602 /// this value and returns the result as a ValueVT value.  This uses
00603 /// Chain/Flag as the input and updates them for the output Chain/Flag.
00604 /// If the Flag pointer is NULL, no flag is used.
00605 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
00606                                       FunctionLoweringInfo &FuncInfo,
00607                                       SDLoc dl,
00608                                       SDValue &Chain, SDValue *Flag,
00609                                       const Value *V) const {
00610   // A Value with type {} or [0 x %t] needs no registers.
00611   if (ValueVTs.empty())
00612     return SDValue();
00613 
00614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00615 
00616   // Assemble the legal parts into the final values.
00617   SmallVector<SDValue, 4> Values(ValueVTs.size());
00618   SmallVector<SDValue, 8> Parts;
00619   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
00620     // Copy the legal parts from the registers.
00621     EVT ValueVT = ValueVTs[Value];
00622     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
00623     MVT RegisterVT = RegVTs[Value];
00624 
00625     Parts.resize(NumRegs);
00626     for (unsigned i = 0; i != NumRegs; ++i) {
00627       SDValue P;
00628       if (!Flag) {
00629         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
00630       } else {
00631         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
00632         *Flag = P.getValue(2);
00633       }
00634 
00635       Chain = P.getValue(1);
00636       Parts[i] = P;
00637 
00638       // If the source register was virtual and if we know something about it,
00639       // add an assert node.
00640       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
00641           !RegisterVT.isInteger() || RegisterVT.isVector())
00642         continue;
00643 
00644       const FunctionLoweringInfo::LiveOutInfo *LOI =
00645         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
00646       if (!LOI)
00647         continue;
00648 
00649       unsigned RegSize = RegisterVT.getSizeInBits();
00650       unsigned NumSignBits = LOI->NumSignBits;
00651       unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
00652 
00653       if (NumZeroBits == RegSize) {
00654         // The current value is a zero.
00655         // Explicitly express that as it would be easier for
00656         // optimizations to kick in.
00657         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
00658         continue;
00659       }
00660 
00661       // FIXME: We capture more information than the dag can represent.  For
00662       // now, just use the tightest assertzext/assertsext possible.
00663       bool isSExt = true;
00664       EVT FromVT(MVT::Other);
00665       if (NumSignBits == RegSize)
00666         isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
00667       else if (NumZeroBits >= RegSize-1)
00668         isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
00669       else if (NumSignBits > RegSize-8)
00670         isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
00671       else if (NumZeroBits >= RegSize-8)
00672         isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
00673       else if (NumSignBits > RegSize-16)
00674         isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
00675       else if (NumZeroBits >= RegSize-16)
00676         isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
00677       else if (NumSignBits > RegSize-32)
00678         isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
00679       else if (NumZeroBits >= RegSize-32)
00680         isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
00681       else
00682         continue;
00683 
00684       // Add an assertion node.
00685       assert(FromVT != MVT::Other);
00686       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
00687                              RegisterVT, P, DAG.getValueType(FromVT));
00688     }
00689 
00690     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
00691                                      NumRegs, RegisterVT, ValueVT, V);
00692     Part += NumRegs;
00693     Parts.clear();
00694   }
00695 
00696   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
00697 }
00698 
00699 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
00700 /// specified value into the registers specified by this object.  This uses
00701 /// Chain/Flag as the input and updates them for the output Chain/Flag.
00702 /// If the Flag pointer is NULL, no flag is used.
00703 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
00704                                  SDValue &Chain, SDValue *Flag, const Value *V,
00705                                  ISD::NodeType PreferredExtendType) const {
00706   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00707   ISD::NodeType ExtendKind = PreferredExtendType;
00708 
00709   // Get the list of the values's legal parts.
00710   unsigned NumRegs = Regs.size();
00711   SmallVector<SDValue, 8> Parts(NumRegs);
00712   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
00713     EVT ValueVT = ValueVTs[Value];
00714     unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
00715     MVT RegisterVT = RegVTs[Value];
00716 
00717     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
00718       ExtendKind = ISD::ZERO_EXTEND;
00719 
00720     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
00721                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
00722     Part += NumParts;
00723   }
00724 
00725   // Copy the parts into the registers.
00726   SmallVector<SDValue, 8> Chains(NumRegs);
00727   for (unsigned i = 0; i != NumRegs; ++i) {
00728     SDValue Part;
00729     if (!Flag) {
00730       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
00731     } else {
00732       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
00733       *Flag = Part.getValue(1);
00734     }
00735 
00736     Chains[i] = Part.getValue(0);
00737   }
00738 
00739   if (NumRegs == 1 || Flag)
00740     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
00741     // flagged to it. That is the CopyToReg nodes and the user are considered
00742     // a single scheduling unit. If we create a TokenFactor and return it as
00743     // chain, then the TokenFactor is both a predecessor (operand) of the
00744     // user as well as a successor (the TF operands are flagged to the user).
00745     // c1, f1 = CopyToReg
00746     // c2, f2 = CopyToReg
00747     // c3     = TokenFactor c1, c2
00748     // ...
00749     //        = op c3, ..., f2
00750     Chain = Chains[NumRegs-1];
00751   else
00752     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
00753 }
00754 
00755 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
00756 /// operand list.  This adds the code marker and includes the number of
00757 /// values added into it.
00758 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
00759                                         unsigned MatchingIdx, SDLoc dl,
00760                                         SelectionDAG &DAG,
00761                                         std::vector<SDValue> &Ops) const {
00762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00763 
00764   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
00765   if (HasMatching)
00766     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
00767   else if (!Regs.empty() &&
00768            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
00769     // Put the register class of the virtual registers in the flag word.  That
00770     // way, later passes can recompute register class constraints for inline
00771     // assembly as well as normal instructions.
00772     // Don't do this for tied operands that can use the regclass information
00773     // from the def.
00774     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
00775     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
00776     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
00777   }
00778 
00779   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
00780   Ops.push_back(Res);
00781 
00782   unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
00783   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
00784     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
00785     MVT RegisterVT = RegVTs[Value];
00786     for (unsigned i = 0; i != NumRegs; ++i) {
00787       assert(Reg < Regs.size() && "Mismatch in # registers expected");
00788       unsigned TheReg = Regs[Reg++];
00789       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
00790 
00791       if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
00792         // If we clobbered the stack pointer, MFI should know about it.
00793         assert(DAG.getMachineFunction().getFrameInfo()->
00794             hasInlineAsmWithSPAdjust());
00795       }
00796     }
00797   }
00798 }
00799 
00800 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
00801                                const TargetLibraryInfo *li) {
00802   AA = &aa;
00803   GFI = gfi;
00804   LibInfo = li;
00805   DL = DAG.getTarget().getDataLayout();
00806   Context = DAG.getContext();
00807   LPadToCallSiteMap.clear();
00808 }
00809 
00810 /// clear - Clear out the current SelectionDAG and the associated
00811 /// state and prepare this SelectionDAGBuilder object to be used
00812 /// for a new block. This doesn't clear out information about
00813 /// additional blocks that are needed to complete switch lowering
00814 /// or PHI node updating; that information is cleared out as it is
00815 /// consumed.
00816 void SelectionDAGBuilder::clear() {
00817   NodeMap.clear();
00818   UnusedArgNodeMap.clear();
00819   PendingLoads.clear();
00820   PendingExports.clear();
00821   CurInst = nullptr;
00822   HasTailCall = false;
00823   SDNodeOrder = LowestSDNodeOrder;
00824   StatepointLowering.clear();
00825 }
00826 
00827 /// clearDanglingDebugInfo - Clear the dangling debug information
00828 /// map. This function is separated from the clear so that debug
00829 /// information that is dangling in a basic block can be properly
00830 /// resolved in a different basic block. This allows the
00831 /// SelectionDAG to resolve dangling debug information attached
00832 /// to PHI nodes.
00833 void SelectionDAGBuilder::clearDanglingDebugInfo() {
00834   DanglingDebugInfoMap.clear();
00835 }
00836 
00837 /// getRoot - Return the current virtual root of the Selection DAG,
00838 /// flushing any PendingLoad items. This must be done before emitting
00839 /// a store or any other node that may need to be ordered after any
00840 /// prior load instructions.
00841 ///
00842 SDValue SelectionDAGBuilder::getRoot() {
00843   if (PendingLoads.empty())
00844     return DAG.getRoot();
00845 
00846   if (PendingLoads.size() == 1) {
00847     SDValue Root = PendingLoads[0];
00848     DAG.setRoot(Root);
00849     PendingLoads.clear();
00850     return Root;
00851   }
00852 
00853   // Otherwise, we have to make a token factor node.
00854   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
00855                              PendingLoads);
00856   PendingLoads.clear();
00857   DAG.setRoot(Root);
00858   return Root;
00859 }
00860 
00861 /// getControlRoot - Similar to getRoot, but instead of flushing all the
00862 /// PendingLoad items, flush all the PendingExports items. It is necessary
00863 /// to do this before emitting a terminator instruction.
00864 ///
00865 SDValue SelectionDAGBuilder::getControlRoot() {
00866   SDValue Root = DAG.getRoot();
00867 
00868   if (PendingExports.empty())
00869     return Root;
00870 
00871   // Turn all of the CopyToReg chains into one factored node.
00872   if (Root.getOpcode() != ISD::EntryToken) {
00873     unsigned i = 0, e = PendingExports.size();
00874     for (; i != e; ++i) {
00875       assert(PendingExports[i].getNode()->getNumOperands() > 1);
00876       if (PendingExports[i].getNode()->getOperand(0) == Root)
00877         break;  // Don't add the root if we already indirectly depend on it.
00878     }
00879 
00880     if (i == e)
00881       PendingExports.push_back(Root);
00882   }
00883 
00884   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
00885                      PendingExports);
00886   PendingExports.clear();
00887   DAG.setRoot(Root);
00888   return Root;
00889 }
00890 
00891 void SelectionDAGBuilder::visit(const Instruction &I) {
00892   // Set up outgoing PHI node register values before emitting the terminator.
00893   if (isa<TerminatorInst>(&I))
00894     HandlePHINodesInSuccessorBlocks(I.getParent());
00895 
00896   ++SDNodeOrder;
00897 
00898   CurInst = &I;
00899 
00900   visit(I.getOpcode(), I);
00901 
00902   if (!isa<TerminatorInst>(&I) && !HasTailCall)
00903     CopyToExportRegsIfNeeded(&I);
00904 
00905   CurInst = nullptr;
00906 }
00907 
00908 void SelectionDAGBuilder::visitPHI(const PHINode &) {
00909   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
00910 }
00911 
00912 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
00913   // Note: this doesn't use InstVisitor, because it has to work with
00914   // ConstantExpr's in addition to instructions.
00915   switch (Opcode) {
00916   default: llvm_unreachable("Unknown instruction type encountered!");
00917     // Build the switch statement using the Instruction.def file.
00918 #define HANDLE_INST(NUM, OPCODE, CLASS) \
00919     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
00920 #include "llvm/IR/Instruction.def"
00921   }
00922 }
00923 
00924 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
00925 // generate the debug data structures now that we've seen its definition.
00926 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
00927                                                    SDValue Val) {
00928   DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
00929   if (DDI.getDI()) {
00930     const DbgValueInst *DI = DDI.getDI();
00931     DebugLoc dl = DDI.getdl();
00932     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
00933     DILocalVariable *Variable = DI->getVariable();
00934     DIExpression *Expr = DI->getExpression();
00935     assert(Variable->isValidLocationForIntrinsic(dl) &&
00936            "Expected inlined-at fields to agree");
00937     uint64_t Offset = DI->getOffset();
00938     // A dbg.value for an alloca is always indirect.
00939     bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
00940     SDDbgValue *SDV;
00941     if (Val.getNode()) {
00942       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, IsIndirect,
00943                                     Val)) {
00944         SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
00945                               IsIndirect, Offset, dl, DbgSDNodeOrder);
00946         DAG.AddDbgValue(SDV, Val.getNode(), false);
00947       }
00948     } else
00949       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
00950     DanglingDebugInfoMap[V] = DanglingDebugInfo();
00951   }
00952 }
00953 
00954 /// getCopyFromRegs - If there was virtual register allocated for the value V
00955 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
00956 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
00957   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
00958   SDValue Result;
00959 
00960   if (It != FuncInfo.ValueMap.end()) {
00961     unsigned InReg = It->second;
00962     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
00963                      Ty);
00964     SDValue Chain = DAG.getEntryNode();
00965     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
00966     resolveDanglingDebugInfo(V, Result);
00967   }
00968 
00969   return Result;
00970 }
00971 
00972 /// getValue - Return an SDValue for the given Value.
00973 SDValue SelectionDAGBuilder::getValue(const Value *V) {
00974   // If we already have an SDValue for this value, use it. It's important
00975   // to do this first, so that we don't create a CopyFromReg if we already
00976   // have a regular SDValue.
00977   SDValue &N = NodeMap[V];
00978   if (N.getNode()) return N;
00979 
00980   // If there's a virtual register allocated and initialized for this
00981   // value, use it.
00982   SDValue copyFromReg = getCopyFromRegs(V, V->getType());
00983   if (copyFromReg.getNode()) {
00984     return copyFromReg;
00985   }
00986 
00987   // Otherwise create a new SDValue and remember it.
00988   SDValue Val = getValueImpl(V);
00989   NodeMap[V] = Val;
00990   resolveDanglingDebugInfo(V, Val);
00991   return Val;
00992 }
00993 
00994 // Return true if SDValue exists for the given Value
00995 bool SelectionDAGBuilder::findValue(const Value *V) const {
00996   return (NodeMap.find(V) != NodeMap.end()) ||
00997     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
00998 }
00999 
01000 /// getNonRegisterValue - Return an SDValue for the given Value, but
01001 /// don't look in FuncInfo.ValueMap for a virtual register.
01002 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
01003   // If we already have an SDValue for this value, use it.
01004   SDValue &N = NodeMap[V];
01005   if (N.getNode()) return N;
01006 
01007   // Otherwise create a new SDValue and remember it.
01008   SDValue Val = getValueImpl(V);
01009   NodeMap[V] = Val;
01010   resolveDanglingDebugInfo(V, Val);
01011   return Val;
01012 }
01013 
01014 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
01015 /// Create an SDValue for the given value.
01016 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
01017   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01018 
01019   if (const Constant *C = dyn_cast<Constant>(V)) {
01020     EVT VT = TLI.getValueType(V->getType(), true);
01021 
01022     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
01023       return DAG.getConstant(*CI, getCurSDLoc(), VT);
01024 
01025     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
01026       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
01027 
01028     if (isa<ConstantPointerNull>(C)) {
01029       unsigned AS = V->getType()->getPointerAddressSpace();
01030       return DAG.getConstant(0, getCurSDLoc(), TLI.getPointerTy(AS));
01031     }
01032 
01033     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
01034       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
01035 
01036     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
01037       return DAG.getUNDEF(VT);
01038 
01039     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
01040       visit(CE->getOpcode(), *CE);
01041       SDValue N1 = NodeMap[V];
01042       assert(N1.getNode() && "visit didn't populate the NodeMap!");
01043       return N1;
01044     }
01045 
01046     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
01047       SmallVector<SDValue, 4> Constants;
01048       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
01049            OI != OE; ++OI) {
01050         SDNode *Val = getValue(*OI).getNode();
01051         // If the operand is an empty aggregate, there are no values.
01052         if (!Val) continue;
01053         // Add each leaf value from the operand to the Constants list
01054         // to form a flattened list of all the values.
01055         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
01056           Constants.push_back(SDValue(Val, i));
01057       }
01058 
01059       return DAG.getMergeValues(Constants, getCurSDLoc());
01060     }
01061 
01062     if (const ConstantDataSequential *CDS =
01063           dyn_cast<ConstantDataSequential>(C)) {
01064       SmallVector<SDValue, 4> Ops;
01065       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01066         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
01067         // Add each leaf value from the operand to the Constants list
01068         // to form a flattened list of all the values.
01069         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
01070           Ops.push_back(SDValue(Val, i));
01071       }
01072 
01073       if (isa<ArrayType>(CDS->getType()))
01074         return DAG.getMergeValues(Ops, getCurSDLoc());
01075       return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
01076                                       VT, Ops);
01077     }
01078 
01079     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
01080       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
01081              "Unknown struct or array constant!");
01082 
01083       SmallVector<EVT, 4> ValueVTs;
01084       ComputeValueVTs(TLI, C->getType(), ValueVTs);
01085       unsigned NumElts = ValueVTs.size();
01086       if (NumElts == 0)
01087         return SDValue(); // empty struct
01088       SmallVector<SDValue, 4> Constants(NumElts);
01089       for (unsigned i = 0; i != NumElts; ++i) {
01090         EVT EltVT = ValueVTs[i];
01091         if (isa<UndefValue>(C))
01092           Constants[i] = DAG.getUNDEF(EltVT);
01093         else if (EltVT.isFloatingPoint())
01094           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
01095         else
01096           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
01097       }
01098 
01099       return DAG.getMergeValues(Constants, getCurSDLoc());
01100     }
01101 
01102     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
01103       return DAG.getBlockAddress(BA, VT);
01104 
01105     VectorType *VecTy = cast<VectorType>(V->getType());
01106     unsigned NumElements = VecTy->getNumElements();
01107 
01108     // Now that we know the number and type of the elements, get that number of
01109     // elements into the Ops array based on what kind of constant it is.
01110     SmallVector<SDValue, 16> Ops;
01111     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
01112       for (unsigned i = 0; i != NumElements; ++i)
01113         Ops.push_back(getValue(CV->getOperand(i)));
01114     } else {
01115       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
01116       EVT EltVT = TLI.getValueType(VecTy->getElementType());
01117 
01118       SDValue Op;
01119       if (EltVT.isFloatingPoint())
01120         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
01121       else
01122         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
01123       Ops.assign(NumElements, Op);
01124     }
01125 
01126     // Create a BUILD_VECTOR node.
01127     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
01128   }
01129 
01130   // If this is a static alloca, generate it as the frameindex instead of
01131   // computation.
01132   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
01133     DenseMap<const AllocaInst*, int>::iterator SI =
01134       FuncInfo.StaticAllocaMap.find(AI);
01135     if (SI != FuncInfo.StaticAllocaMap.end())
01136       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
01137   }
01138 
01139   // If this is an instruction which fast-isel has deferred, select it now.
01140   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
01141     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
01142     RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
01143     SDValue Chain = DAG.getEntryNode();
01144     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
01145   }
01146 
01147   llvm_unreachable("Can't get register for value!");
01148 }
01149 
01150 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
01151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01152   SDValue Chain = getControlRoot();
01153   SmallVector<ISD::OutputArg, 8> Outs;
01154   SmallVector<SDValue, 8> OutVals;
01155 
01156   if (!FuncInfo.CanLowerReturn) {
01157     unsigned DemoteReg = FuncInfo.DemoteRegister;
01158     const Function *F = I.getParent()->getParent();
01159 
01160     // Emit a store of the return value through the virtual register.
01161     // Leave Outs empty so that LowerReturn won't try to load return
01162     // registers the usual way.
01163     SmallVector<EVT, 1> PtrValueVTs;
01164     ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
01165                     PtrValueVTs);
01166 
01167     SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
01168     SDValue RetOp = getValue(I.getOperand(0));
01169 
01170     SmallVector<EVT, 4> ValueVTs;
01171     SmallVector<uint64_t, 4> Offsets;
01172     ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
01173     unsigned NumValues = ValueVTs.size();
01174 
01175     SmallVector<SDValue, 4> Chains(NumValues);
01176     for (unsigned i = 0; i != NumValues; ++i) {
01177       SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
01178                                 RetPtr.getValueType(), RetPtr,
01179                                 DAG.getIntPtrConstant(Offsets[i],
01180                                                       getCurSDLoc()));
01181       Chains[i] =
01182         DAG.getStore(Chain, getCurSDLoc(),
01183                      SDValue(RetOp.getNode(), RetOp.getResNo() + i),
01184                      // FIXME: better loc info would be nice.
01185                      Add, MachinePointerInfo(), false, false, 0);
01186     }
01187 
01188     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
01189                         MVT::Other, Chains);
01190   } else if (I.getNumOperands() != 0) {
01191     SmallVector<EVT, 4> ValueVTs;
01192     ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
01193     unsigned NumValues = ValueVTs.size();
01194     if (NumValues) {
01195       SDValue RetOp = getValue(I.getOperand(0));
01196 
01197       const Function *F = I.getParent()->getParent();
01198 
01199       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
01200       if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
01201                                           Attribute::SExt))
01202         ExtendKind = ISD::SIGN_EXTEND;
01203       else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
01204                                                Attribute::ZExt))
01205         ExtendKind = ISD::ZERO_EXTEND;
01206 
01207       LLVMContext &Context = F->getContext();
01208       bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
01209                                                       Attribute::InReg);
01210 
01211       for (unsigned j = 0; j != NumValues; ++j) {
01212         EVT VT = ValueVTs[j];
01213 
01214         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
01215           VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind);
01216 
01217         unsigned NumParts = TLI.getNumRegisters(Context, VT);
01218         MVT PartVT = TLI.getRegisterType(Context, VT);
01219         SmallVector<SDValue, 4> Parts(NumParts);
01220         getCopyToParts(DAG, getCurSDLoc(),
01221                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
01222                        &Parts[0], NumParts, PartVT, &I, ExtendKind);
01223 
01224         // 'inreg' on function refers to return value
01225         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
01226         if (RetInReg)
01227           Flags.setInReg();
01228 
01229         // Propagate extension type if any
01230         if (ExtendKind == ISD::SIGN_EXTEND)
01231           Flags.setSExt();
01232         else if (ExtendKind == ISD::ZERO_EXTEND)
01233           Flags.setZExt();
01234 
01235         for (unsigned i = 0; i < NumParts; ++i) {
01236           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
01237                                         VT, /*isfixed=*/true, 0, 0));
01238           OutVals.push_back(Parts[i]);
01239         }
01240       }
01241     }
01242   }
01243 
01244   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
01245   CallingConv::ID CallConv =
01246     DAG.getMachineFunction().getFunction()->getCallingConv();
01247   Chain = DAG.getTargetLoweringInfo().LowerReturn(
01248       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
01249 
01250   // Verify that the target's LowerReturn behaved as expected.
01251   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
01252          "LowerReturn didn't return a valid chain!");
01253 
01254   // Update the DAG with the new chain value resulting from return lowering.
01255   DAG.setRoot(Chain);
01256 }
01257 
01258 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
01259 /// created for it, emit nodes to copy the value into the virtual
01260 /// registers.
01261 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
01262   // Skip empty types
01263   if (V->getType()->isEmptyTy())
01264     return;
01265 
01266   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
01267   if (VMI != FuncInfo.ValueMap.end()) {
01268     assert(!V->use_empty() && "Unused value assigned virtual registers!");
01269     CopyValueToVirtualRegister(V, VMI->second);
01270   }
01271 }
01272 
01273 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
01274 /// the current basic block, add it to ValueMap now so that we'll get a
01275 /// CopyTo/FromReg.
01276 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
01277   // No need to export constants.
01278   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
01279 
01280   // Already exported?
01281   if (FuncInfo.isExportedInst(V)) return;
01282 
01283   unsigned Reg = FuncInfo.InitializeRegForValue(V);
01284   CopyValueToVirtualRegister(V, Reg);
01285 }
01286 
01287 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
01288                                                      const BasicBlock *FromBB) {
01289   // The operands of the setcc have to be in this block.  We don't know
01290   // how to export them from some other block.
01291   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
01292     // Can export from current BB.
01293     if (VI->getParent() == FromBB)
01294       return true;
01295 
01296     // Is already exported, noop.
01297     return FuncInfo.isExportedInst(V);
01298   }
01299 
01300   // If this is an argument, we can export it if the BB is the entry block or
01301   // if it is already exported.
01302   if (isa<Argument>(V)) {
01303     if (FromBB == &FromBB->getParent()->getEntryBlock())
01304       return true;
01305 
01306     // Otherwise, can only export this if it is already exported.
01307     return FuncInfo.isExportedInst(V);
01308   }
01309 
01310   // Otherwise, constants can always be exported.
01311   return true;
01312 }
01313 
01314 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
01315 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
01316                                             const MachineBasicBlock *Dst) const {
01317   BranchProbabilityInfo *BPI = FuncInfo.BPI;
01318   if (!BPI)
01319     return 0;
01320   const BasicBlock *SrcBB = Src->getBasicBlock();
01321   const BasicBlock *DstBB = Dst->getBasicBlock();
01322   return BPI->getEdgeWeight(SrcBB, DstBB);
01323 }
01324 
01325 void SelectionDAGBuilder::
01326 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
01327                        uint32_t Weight /* = 0 */) {
01328   if (!Weight)
01329     Weight = getEdgeWeight(Src, Dst);
01330   Src->addSuccessor(Dst, Weight);
01331 }
01332 
01333 
01334 static bool InBlock(const Value *V, const BasicBlock *BB) {
01335   if (const Instruction *I = dyn_cast<Instruction>(V))
01336     return I->getParent() == BB;
01337   return true;
01338 }
01339 
01340 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
01341 /// This function emits a branch and is used at the leaves of an OR or an
01342 /// AND operator tree.
01343 ///
01344 void
01345 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
01346                                                   MachineBasicBlock *TBB,
01347                                                   MachineBasicBlock *FBB,
01348                                                   MachineBasicBlock *CurBB,
01349                                                   MachineBasicBlock *SwitchBB,
01350                                                   uint32_t TWeight,
01351                                                   uint32_t FWeight) {
01352   const BasicBlock *BB = CurBB->getBasicBlock();
01353 
01354   // If the leaf of the tree is a comparison, merge the condition into
01355   // the caseblock.
01356   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
01357     // The operands of the cmp have to be in this block.  We don't know
01358     // how to export them from some other block.  If this is the first block
01359     // of the sequence, no exporting is needed.
01360     if (CurBB == SwitchBB ||
01361         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
01362          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
01363       ISD::CondCode Condition;
01364       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
01365         Condition = getICmpCondCode(IC->getPredicate());
01366       } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
01367         Condition = getFCmpCondCode(FC->getPredicate());
01368         if (TM.Options.NoNaNsFPMath)
01369           Condition = getFCmpCodeWithoutNaN(Condition);
01370       } else {
01371         (void)Condition; // silence warning.
01372         llvm_unreachable("Unknown compare instruction");
01373       }
01374 
01375       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
01376                    TBB, FBB, CurBB, TWeight, FWeight);
01377       SwitchCases.push_back(CB);
01378       return;
01379     }
01380   }
01381 
01382   // Create a CaseBlock record representing this branch.
01383   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
01384                nullptr, TBB, FBB, CurBB, TWeight, FWeight);
01385   SwitchCases.push_back(CB);
01386 }
01387 
01388 /// Scale down both weights to fit into uint32_t.
01389 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
01390   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
01391   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
01392   NewTrue = NewTrue / Scale;
01393   NewFalse = NewFalse / Scale;
01394 }
01395 
01396 /// FindMergedConditions - If Cond is an expression like
01397 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
01398                                                MachineBasicBlock *TBB,
01399                                                MachineBasicBlock *FBB,
01400                                                MachineBasicBlock *CurBB,
01401                                                MachineBasicBlock *SwitchBB,
01402                                                unsigned Opc, uint32_t TWeight,
01403                                                uint32_t FWeight) {
01404   // If this node is not part of the or/and tree, emit it as a branch.
01405   const Instruction *BOp = dyn_cast<Instruction>(Cond);
01406   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
01407       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
01408       BOp->getParent() != CurBB->getBasicBlock() ||
01409       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
01410       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
01411     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
01412                                  TWeight, FWeight);
01413     return;
01414   }
01415 
01416   //  Create TmpBB after CurBB.
01417   MachineFunction::iterator BBI = CurBB;
01418   MachineFunction &MF = DAG.getMachineFunction();
01419   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
01420   CurBB->getParent()->insert(++BBI, TmpBB);
01421 
01422   if (Opc == Instruction::Or) {
01423     // Codegen X | Y as:
01424     // BB1:
01425     //   jmp_if_X TBB
01426     //   jmp TmpBB
01427     // TmpBB:
01428     //   jmp_if_Y TBB
01429     //   jmp FBB
01430     //
01431 
01432     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
01433     // The requirement is that
01434     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
01435     //     = TrueProb for orignal BB.
01436     // Assuming the orignal weights are A and B, one choice is to set BB1's
01437     // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
01438     // assumes that
01439     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
01440     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
01441     // TmpBB, but the math is more complicated.
01442 
01443     uint64_t NewTrueWeight = TWeight;
01444     uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
01445     ScaleWeights(NewTrueWeight, NewFalseWeight);
01446     // Emit the LHS condition.
01447     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
01448                          NewTrueWeight, NewFalseWeight);
01449 
01450     NewTrueWeight = TWeight;
01451     NewFalseWeight = 2 * (uint64_t)FWeight;
01452     ScaleWeights(NewTrueWeight, NewFalseWeight);
01453     // Emit the RHS condition into TmpBB.
01454     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
01455                          NewTrueWeight, NewFalseWeight);
01456   } else {
01457     assert(Opc == Instruction::And && "Unknown merge op!");
01458     // Codegen X & Y as:
01459     // BB1:
01460     //   jmp_if_X TmpBB
01461     //   jmp FBB
01462     // TmpBB:
01463     //   jmp_if_Y TBB
01464     //   jmp FBB
01465     //
01466     //  This requires creation of TmpBB after CurBB.
01467 
01468     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
01469     // The requirement is that
01470     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
01471     //     = FalseProb for orignal BB.
01472     // Assuming the orignal weights are A and B, one choice is to set BB1's
01473     // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
01474     // assumes that
01475     //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
01476 
01477     uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
01478     uint64_t NewFalseWeight = FWeight;
01479     ScaleWeights(NewTrueWeight, NewFalseWeight);
01480     // Emit the LHS condition.
01481     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
01482                          NewTrueWeight, NewFalseWeight);
01483 
01484     NewTrueWeight = 2 * (uint64_t)TWeight;
01485     NewFalseWeight = FWeight;
01486     ScaleWeights(NewTrueWeight, NewFalseWeight);
01487     // Emit the RHS condition into TmpBB.
01488     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
01489                          NewTrueWeight, NewFalseWeight);
01490   }
01491 }
01492 
01493 /// If the set of cases should be emitted as a series of branches, return true.
01494 /// If we should emit this as a bunch of and/or'd together conditions, return
01495 /// false.
01496 bool
01497 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
01498   if (Cases.size() != 2) return true;
01499 
01500   // If this is two comparisons of the same values or'd or and'd together, they
01501   // will get folded into a single comparison, so don't emit two blocks.
01502   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
01503        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
01504       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
01505        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
01506     return false;
01507   }
01508 
01509   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
01510   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
01511   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
01512       Cases[0].CC == Cases[1].CC &&
01513       isa<Constant>(Cases[0].CmpRHS) &&
01514       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
01515     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
01516       return false;
01517     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
01518       return false;
01519   }
01520 
01521   return true;
01522 }
01523 
01524 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
01525   MachineBasicBlock *BrMBB = FuncInfo.MBB;
01526 
01527   // Update machine-CFG edges.
01528   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
01529 
01530   if (I.isUnconditional()) {
01531     // Update machine-CFG edges.
01532     BrMBB->addSuccessor(Succ0MBB);
01533 
01534     // If this is not a fall-through branch or optimizations are switched off,
01535     // emit the branch.
01536     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
01537       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
01538                               MVT::Other, getControlRoot(),
01539                               DAG.getBasicBlock(Succ0MBB)));
01540 
01541     return;
01542   }
01543 
01544   // If this condition is one of the special cases we handle, do special stuff
01545   // now.
01546   const Value *CondVal = I.getCondition();
01547   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
01548 
01549   // If this is a series of conditions that are or'd or and'd together, emit
01550   // this as a sequence of branches instead of setcc's with and/or operations.
01551   // As long as jumps are not expensive, this should improve performance.
01552   // For example, instead of something like:
01553   //     cmp A, B
01554   //     C = seteq
01555   //     cmp D, E
01556   //     F = setle
01557   //     or C, F
01558   //     jnz foo
01559   // Emit:
01560   //     cmp A, B
01561   //     je foo
01562   //     cmp D, E
01563   //     jle foo
01564   //
01565   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
01566     if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
01567         BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
01568                              BOp->getOpcode() == Instruction::Or)) {
01569       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
01570                            BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
01571                            getEdgeWeight(BrMBB, Succ1MBB));
01572       // If the compares in later blocks need to use values not currently
01573       // exported from this block, export them now.  This block should always
01574       // be the first entry.
01575       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
01576 
01577       // Allow some cases to be rejected.
01578       if (ShouldEmitAsBranches(SwitchCases)) {
01579         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
01580           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
01581           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
01582         }
01583 
01584         // Emit the branch for this block.
01585         visitSwitchCase(SwitchCases[0], BrMBB);
01586         SwitchCases.erase(SwitchCases.begin());
01587         return;
01588       }
01589 
01590       // Okay, we decided not to do this, remove any inserted MBB's and clear
01591       // SwitchCases.
01592       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
01593         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
01594 
01595       SwitchCases.clear();
01596     }
01597   }
01598 
01599   // Create a CaseBlock record representing this branch.
01600   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
01601                nullptr, Succ0MBB, Succ1MBB, BrMBB);
01602 
01603   // Use visitSwitchCase to actually insert the fast branch sequence for this
01604   // cond branch.
01605   visitSwitchCase(CB, BrMBB);
01606 }
01607 
01608 /// visitSwitchCase - Emits the necessary code to represent a single node in
01609 /// the binary search tree resulting from lowering a switch instruction.
01610 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
01611                                           MachineBasicBlock *SwitchBB) {
01612   SDValue Cond;
01613   SDValue CondLHS = getValue(CB.CmpLHS);
01614   SDLoc dl = getCurSDLoc();
01615 
01616   // Build the setcc now.
01617   if (!CB.CmpMHS) {
01618     // Fold "(X == true)" to X and "(X == false)" to !X to
01619     // handle common cases produced by branch lowering.
01620     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
01621         CB.CC == ISD::SETEQ)
01622       Cond = CondLHS;
01623     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
01624              CB.CC == ISD::SETEQ) {
01625       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
01626       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
01627     } else
01628       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
01629   } else {
01630     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
01631 
01632     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
01633     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
01634 
01635     SDValue CmpOp = getValue(CB.CmpMHS);
01636     EVT VT = CmpOp.getValueType();
01637 
01638     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
01639       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
01640                           ISD::SETLE);
01641     } else {
01642       SDValue SUB = DAG.getNode(ISD::SUB, dl,
01643                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
01644       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
01645                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
01646     }
01647   }
01648 
01649   // Update successor info
01650   addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
01651   // TrueBB and FalseBB are always different unless the incoming IR is
01652   // degenerate. This only happens when running llc on weird IR.
01653   if (CB.TrueBB != CB.FalseBB)
01654     addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
01655 
01656   // If the lhs block is the next block, invert the condition so that we can
01657   // fall through to the lhs instead of the rhs block.
01658   if (CB.TrueBB == NextBlock(SwitchBB)) {
01659     std::swap(CB.TrueBB, CB.FalseBB);
01660     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
01661     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
01662   }
01663 
01664   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
01665                                MVT::Other, getControlRoot(), Cond,
01666                                DAG.getBasicBlock(CB.TrueBB));
01667 
01668   // Insert the false branch. Do this even if it's a fall through branch,
01669   // this makes it easier to do DAG optimizations which require inverting
01670   // the branch condition.
01671   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
01672                        DAG.getBasicBlock(CB.FalseBB));
01673 
01674   DAG.setRoot(BrCond);
01675 }
01676 
01677 /// visitJumpTable - Emit JumpTable node in the current MBB
01678 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
01679   // Emit the code for the jump table
01680   assert(JT.Reg != -1U && "Should lower JT Header first!");
01681   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
01682   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
01683                                      JT.Reg, PTy);
01684   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
01685   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
01686                                     MVT::Other, Index.getValue(1),
01687                                     Table, Index);
01688   DAG.setRoot(BrJumpTable);
01689 }
01690 
01691 /// visitJumpTableHeader - This function emits necessary code to produce index
01692 /// in the JumpTable from switch case.
01693 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
01694                                                JumpTableHeader &JTH,
01695                                                MachineBasicBlock *SwitchBB) {
01696   SDLoc dl = getCurSDLoc();
01697 
01698   // Subtract the lowest switch case value from the value being switched on and
01699   // conditional branch to default mbb if the result is greater than the
01700   // difference between smallest and largest cases.
01701   SDValue SwitchOp = getValue(JTH.SValue);
01702   EVT VT = SwitchOp.getValueType();
01703   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
01704                             DAG.getConstant(JTH.First, dl, VT));
01705 
01706   // The SDNode we just created, which holds the value being switched on minus
01707   // the smallest case value, needs to be copied to a virtual register so it
01708   // can be used as an index into the jump table in a subsequent basic block.
01709   // This value may be smaller or larger than the target's pointer type, and
01710   // therefore require extension or truncating.
01711   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01712   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy());
01713 
01714   unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
01715   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
01716                                     JumpTableReg, SwitchOp);
01717   JT.Reg = JumpTableReg;
01718 
01719   // Emit the range check for the jump table, and branch to the default block
01720   // for the switch statement if the value being switched on exceeds the largest
01721   // case in the switch.
01722   SDValue CMP =
01723       DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(),
01724                                               Sub.getValueType()),
01725                    Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT),
01726                    ISD::SETUGT);
01727 
01728   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
01729                                MVT::Other, CopyTo, CMP,
01730                                DAG.getBasicBlock(JT.Default));
01731 
01732   // Avoid emitting unnecessary branches to the next block.
01733   if (JT.MBB != NextBlock(SwitchBB))
01734     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
01735                          DAG.getBasicBlock(JT.MBB));
01736 
01737   DAG.setRoot(BrCond);
01738 }
01739 
01740 /// Codegen a new tail for a stack protector check ParentMBB which has had its
01741 /// tail spliced into a stack protector check success bb.
01742 ///
01743 /// For a high level explanation of how this fits into the stack protector
01744 /// generation see the comment on the declaration of class
01745 /// StackProtectorDescriptor.
01746 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
01747                                                   MachineBasicBlock *ParentBB) {
01748 
01749   // First create the loads to the guard/stack slot for the comparison.
01750   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01751   EVT PtrTy = TLI.getPointerTy();
01752 
01753   MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
01754   int FI = MFI->getStackProtectorIndex();
01755 
01756   const Value *IRGuard = SPD.getGuard();
01757   SDValue GuardPtr = getValue(IRGuard);
01758   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
01759 
01760   unsigned Align =
01761     TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
01762 
01763   SDValue Guard;
01764   SDLoc dl = getCurSDLoc();
01765 
01766   // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
01767   // guard value from the virtual register holding the value. Otherwise, emit a
01768   // volatile load to retrieve the stack guard value.
01769   unsigned GuardReg = SPD.getGuardReg();
01770 
01771   if (GuardReg && TLI.useLoadStackGuardNode())
01772     Guard = DAG.getCopyFromReg(DAG.getEntryNode(), dl, GuardReg,
01773                                PtrTy);
01774   else
01775     Guard = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
01776                         GuardPtr, MachinePointerInfo(IRGuard, 0),
01777                         true, false, false, Align);
01778 
01779   SDValue StackSlot = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
01780                                   StackSlotPtr,
01781                                   MachinePointerInfo::getFixedStack(FI),
01782                                   true, false, false, Align);
01783 
01784   // Perform the comparison via a subtract/getsetcc.
01785   EVT VT = Guard.getValueType();
01786   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
01787 
01788   SDValue Cmp =
01789       DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(),
01790                                                          Sub.getValueType()),
01791                    Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
01792 
01793   // If the sub is not 0, then we know the guard/stackslot do not equal, so
01794   // branch to failure MBB.
01795   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
01796                                MVT::Other, StackSlot.getOperand(0),
01797                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
01798   // Otherwise branch to success MBB.
01799   SDValue Br = DAG.getNode(ISD::BR, dl,
01800                            MVT::Other, BrCond,
01801                            DAG.getBasicBlock(SPD.getSuccessMBB()));
01802 
01803   DAG.setRoot(Br);
01804 }
01805 
01806 /// Codegen the failure basic block for a stack protector check.
01807 ///
01808 /// A failure stack protector machine basic block consists simply of a call to
01809 /// __stack_chk_fail().
01810 ///
01811 /// For a high level explanation of how this fits into the stack protector
01812 /// generation see the comment on the declaration of class
01813 /// StackProtectorDescriptor.
01814 void
01815 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
01816   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01817   SDValue Chain =
01818       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
01819                       nullptr, 0, false, getCurSDLoc(), false, false).second;
01820   DAG.setRoot(Chain);
01821 }
01822 
01823 /// visitBitTestHeader - This function emits necessary code to produce value
01824 /// suitable for "bit tests"
01825 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
01826                                              MachineBasicBlock *SwitchBB) {
01827   SDLoc dl = getCurSDLoc();
01828 
01829   // Subtract the minimum value
01830   SDValue SwitchOp = getValue(B.SValue);
01831   EVT VT = SwitchOp.getValueType();
01832   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
01833                             DAG.getConstant(B.First, dl, VT));
01834 
01835   // Check range
01836   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01837   SDValue RangeCmp =
01838       DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(),
01839                                               Sub.getValueType()),
01840                    Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
01841 
01842   // Determine the type of the test operands.
01843   bool UsePtrType = false;
01844   if (!TLI.isTypeLegal(VT))
01845     UsePtrType = true;
01846   else {
01847     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
01848       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
01849         // Switch table case range are encoded into series of masks.
01850         // Just use pointer type, it's guaranteed to fit.
01851         UsePtrType = true;
01852         break;
01853       }
01854   }
01855   if (UsePtrType) {
01856     VT = TLI.getPointerTy();
01857     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
01858   }
01859 
01860   B.RegVT = VT.getSimpleVT();
01861   B.Reg = FuncInfo.CreateReg(B.RegVT);
01862   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
01863 
01864   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
01865 
01866   addSuccessorWithWeight(SwitchBB, B.Default);
01867   addSuccessorWithWeight(SwitchBB, MBB);
01868 
01869   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
01870                                 MVT::Other, CopyTo, RangeCmp,
01871                                 DAG.getBasicBlock(B.Default));
01872 
01873   // Avoid emitting unnecessary branches to the next block.
01874   if (MBB != NextBlock(SwitchBB))
01875     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
01876                           DAG.getBasicBlock(MBB));
01877 
01878   DAG.setRoot(BrRange);
01879 }
01880 
01881 /// visitBitTestCase - this function produces one "bit test"
01882 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
01883                                            MachineBasicBlock* NextMBB,
01884                                            uint32_t BranchWeightToNext,
01885                                            unsigned Reg,
01886                                            BitTestCase &B,
01887                                            MachineBasicBlock *SwitchBB) {
01888   SDLoc dl = getCurSDLoc();
01889   MVT VT = BB.RegVT;
01890   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
01891   SDValue Cmp;
01892   unsigned PopCount = countPopulation(B.Mask);
01893   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01894   if (PopCount == 1) {
01895     // Testing for a single bit; just compare the shift count with what it
01896     // would need to be to shift a 1 bit in that position.
01897     Cmp = DAG.getSetCC(
01898         dl, TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
01899         DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), ISD::SETEQ);
01900   } else if (PopCount == BB.Range) {
01901     // There is only one zero bit in the range, test for it directly.
01902     Cmp = DAG.getSetCC(
01903         dl, TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
01904         DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), ISD::SETNE);
01905   } else {
01906     // Make desired shift
01907     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
01908                                     DAG.getConstant(1, dl, VT), ShiftOp);
01909 
01910     // Emit bit tests and jumps
01911     SDValue AndOp = DAG.getNode(ISD::AND, dl,
01912                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
01913     Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
01914                        DAG.getConstant(0, dl, VT), ISD::SETNE);
01915   }
01916 
01917   // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
01918   addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
01919   // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
01920   addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
01921 
01922   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
01923                               MVT::Other, getControlRoot(),
01924                               Cmp, DAG.getBasicBlock(B.TargetBB));
01925 
01926   // Avoid emitting unnecessary branches to the next block.
01927   if (NextMBB != NextBlock(SwitchBB))
01928     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
01929                         DAG.getBasicBlock(NextMBB));
01930 
01931   DAG.setRoot(BrAnd);
01932 }
01933 
01934 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
01935   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
01936 
01937   // Retrieve successors.
01938   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
01939   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
01940 
01941   const Value *Callee(I.getCalledValue());
01942   const Function *Fn = dyn_cast<Function>(Callee);
01943   if (isa<InlineAsm>(Callee))
01944     visitInlineAsm(&I);
01945   else if (Fn && Fn->isIntrinsic()) {
01946     switch (Fn->getIntrinsicID()) {
01947     default:
01948       llvm_unreachable("Cannot invoke this intrinsic");
01949     case Intrinsic::donothing:
01950       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
01951       break;
01952     case Intrinsic::experimental_patchpoint_void:
01953     case Intrinsic::experimental_patchpoint_i64:
01954       visitPatchpoint(&I, LandingPad);
01955       break;
01956     case Intrinsic::experimental_gc_statepoint:
01957       LowerStatepoint(ImmutableStatepoint(&I), LandingPad);
01958       break;
01959     }
01960   } else
01961     LowerCallTo(&I, getValue(Callee), false, LandingPad);
01962 
01963   // If the value of the invoke is used outside of its defining block, make it
01964   // available as a virtual register.
01965   // We already took care of the exported value for the statepoint instruction
01966   // during call to the LowerStatepoint.
01967   if (!isStatepoint(I)) {
01968     CopyToExportRegsIfNeeded(&I);
01969   }
01970 
01971   // Update successor info
01972   addSuccessorWithWeight(InvokeMBB, Return);
01973   addSuccessorWithWeight(InvokeMBB, LandingPad);
01974 
01975   // Drop into normal successor.
01976   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
01977                           MVT::Other, getControlRoot(),
01978                           DAG.getBasicBlock(Return)));
01979 }
01980 
01981 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
01982   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
01983 }
01984 
01985 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
01986   assert(FuncInfo.MBB->isLandingPad() &&
01987          "Call to landingpad not in landing pad!");
01988 
01989   MachineBasicBlock *MBB = FuncInfo.MBB;
01990   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
01991   AddLandingPadInfo(LP, MMI, MBB);
01992 
01993   // If there aren't registers to copy the values into (e.g., during SjLj
01994   // exceptions), then don't bother to create these DAG nodes.
01995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
01996   if (TLI.getExceptionPointerRegister() == 0 &&
01997       TLI.getExceptionSelectorRegister() == 0)
01998     return;
01999 
02000   SmallVector<EVT, 2> ValueVTs;
02001   SDLoc dl = getCurSDLoc();
02002   ComputeValueVTs(TLI, LP.getType(), ValueVTs);
02003   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
02004 
02005   // Get the two live-in registers as SDValues. The physregs have already been
02006   // copied into virtual registers.
02007   SDValue Ops[2];
02008   if (FuncInfo.ExceptionPointerVirtReg) {
02009     Ops[0] = DAG.getZExtOrTrunc(
02010         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
02011                            FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
02012         dl, ValueVTs[0]);
02013   } else {
02014     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy());
02015   }
02016   Ops[1] = DAG.getZExtOrTrunc(
02017       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
02018                          FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
02019       dl, ValueVTs[1]);
02020 
02021   // Merge into one.
02022   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
02023                             DAG.getVTList(ValueVTs), Ops);
02024   setValue(&LP, Res);
02025 }
02026 
02027 unsigned
02028 SelectionDAGBuilder::visitLandingPadClauseBB(GlobalValue *ClauseGV,
02029                                              MachineBasicBlock *LPadBB) {
02030   SDValue Chain = getControlRoot();
02031   SDLoc dl = getCurSDLoc();
02032 
02033   // Get the typeid that we will dispatch on later.
02034   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02035   const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy());
02036   unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
02037   unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(ClauseGV);
02038   SDValue Sel = DAG.getConstant(TypeID, dl, TLI.getPointerTy());
02039   Chain = DAG.getCopyToReg(Chain, dl, VReg, Sel);
02040 
02041   // Branch to the main landing pad block.
02042   MachineBasicBlock *ClauseMBB = FuncInfo.MBB;
02043   ClauseMBB->addSuccessor(LPadBB);
02044   DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, Chain,
02045                           DAG.getBasicBlock(LPadBB)));
02046   return VReg;
02047 }
02048 
02049 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
02050 #ifndef NDEBUG
02051   for (const CaseCluster &CC : Clusters)
02052     assert(CC.Low == CC.High && "Input clusters must be single-case");
02053 #endif
02054 
02055   std::sort(Clusters.begin(), Clusters.end(),
02056             [](const CaseCluster &a, const CaseCluster &b) {
02057     return a.Low->getValue().slt(b.Low->getValue());
02058   });
02059 
02060   // Merge adjacent clusters with the same destination.
02061   const unsigned N = Clusters.size();
02062   unsigned DstIndex = 0;
02063   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
02064     CaseCluster &CC = Clusters[SrcIndex];
02065     const ConstantInt *CaseVal = CC.Low;
02066     MachineBasicBlock *Succ = CC.MBB;
02067 
02068     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
02069         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
02070       // If this case has the same successor and is a neighbour, merge it into
02071       // the previous cluster.
02072       Clusters[DstIndex - 1].High = CaseVal;
02073       Clusters[DstIndex - 1].Weight += CC.Weight;
02074       assert(Clusters[DstIndex - 1].Weight >= CC.Weight && "Weight overflow!");
02075     } else {
02076       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
02077                    sizeof(Clusters[SrcIndex]));
02078     }
02079   }
02080   Clusters.resize(DstIndex);
02081 }
02082 
02083 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
02084                                            MachineBasicBlock *Last) {
02085   // Update JTCases.
02086   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
02087     if (JTCases[i].first.HeaderBB == First)
02088       JTCases[i].first.HeaderBB = Last;
02089 
02090   // Update BitTestCases.
02091   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
02092     if (BitTestCases[i].Parent == First)
02093       BitTestCases[i].Parent = Last;
02094 }
02095 
02096 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
02097   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
02098 
02099   // Update machine-CFG edges with unique successors.
02100   SmallSet<BasicBlock*, 32> Done;
02101   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
02102     BasicBlock *BB = I.getSuccessor(i);
02103     bool Inserted = Done.insert(BB).second;
02104     if (!Inserted)
02105         continue;
02106 
02107     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
02108     addSuccessorWithWeight(IndirectBrMBB, Succ);
02109   }
02110 
02111   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
02112                           MVT::Other, getControlRoot(),
02113                           getValue(I.getAddress())));
02114 }
02115 
02116 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
02117   if (DAG.getTarget().Options.TrapUnreachable)
02118     DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
02119 }
02120 
02121 void SelectionDAGBuilder::visitFSub(const User &I) {
02122   // -0.0 - X --> fneg
02123   Type *Ty = I.getType();
02124   if (isa<Constant>(I.getOperand(0)) &&
02125       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
02126     SDValue Op2 = getValue(I.getOperand(1));
02127     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
02128                              Op2.getValueType(), Op2));
02129     return;
02130   }
02131 
02132   visitBinary(I, ISD::FSUB);
02133 }
02134 
02135 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
02136   SDValue Op1 = getValue(I.getOperand(0));
02137   SDValue Op2 = getValue(I.getOperand(1));
02138 
02139   bool nuw = false;
02140   bool nsw = false;
02141   bool exact = false;
02142   if (const OverflowingBinaryOperator *OFBinOp =
02143           dyn_cast<const OverflowingBinaryOperator>(&I)) {
02144     nuw = OFBinOp->hasNoUnsignedWrap();
02145     nsw = OFBinOp->hasNoSignedWrap();
02146   }
02147   if (const PossiblyExactOperator *ExactOp =
02148           dyn_cast<const PossiblyExactOperator>(&I))
02149     exact = ExactOp->isExact();
02150 
02151   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
02152                                      Op1, Op2, nuw, nsw, exact);
02153   setValue(&I, BinNodeValue);
02154 }
02155 
02156 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
02157   SDValue Op1 = getValue(I.getOperand(0));
02158   SDValue Op2 = getValue(I.getOperand(1));
02159 
02160   EVT ShiftTy =
02161       DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
02162 
02163   // Coerce the shift amount to the right type if we can.
02164   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
02165     unsigned ShiftSize = ShiftTy.getSizeInBits();
02166     unsigned Op2Size = Op2.getValueType().getSizeInBits();
02167     SDLoc DL = getCurSDLoc();
02168 
02169     // If the operand is smaller than the shift count type, promote it.
02170     if (ShiftSize > Op2Size)
02171       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
02172 
02173     // If the operand is larger than the shift count type but the shift
02174     // count type has enough bits to represent any shift value, truncate
02175     // it now. This is a common case and it exposes the truncate to
02176     // optimization early.
02177     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
02178       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
02179     // Otherwise we'll need to temporarily settle for some other convenient
02180     // type.  Type legalization will make adjustments once the shiftee is split.
02181     else
02182       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
02183   }
02184 
02185   bool nuw = false;
02186   bool nsw = false;
02187   bool exact = false;
02188 
02189   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
02190 
02191     if (const OverflowingBinaryOperator *OFBinOp =
02192             dyn_cast<const OverflowingBinaryOperator>(&I)) {
02193       nuw = OFBinOp->hasNoUnsignedWrap();
02194       nsw = OFBinOp->hasNoSignedWrap();
02195     }
02196     if (const PossiblyExactOperator *ExactOp =
02197             dyn_cast<const PossiblyExactOperator>(&I))
02198       exact = ExactOp->isExact();
02199   }
02200 
02201   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
02202                             nuw, nsw, exact);
02203   setValue(&I, Res);
02204 }
02205 
02206 void SelectionDAGBuilder::visitSDiv(const User &I) {
02207   SDValue Op1 = getValue(I.getOperand(0));
02208   SDValue Op2 = getValue(I.getOperand(1));
02209 
02210   // Turn exact SDivs into multiplications.
02211   // FIXME: This should be in DAGCombiner, but it doesn't have access to the
02212   // exact bit.
02213   if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
02214       !isa<ConstantSDNode>(Op1) &&
02215       isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
02216     setValue(&I, DAG.getTargetLoweringInfo()
02217                      .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
02218   else
02219     setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
02220                              Op1, Op2));
02221 }
02222 
02223 void SelectionDAGBuilder::visitICmp(const User &I) {
02224   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
02225   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
02226     predicate = IC->getPredicate();
02227   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
02228     predicate = ICmpInst::Predicate(IC->getPredicate());
02229   SDValue Op1 = getValue(I.getOperand(0));
02230   SDValue Op2 = getValue(I.getOperand(1));
02231   ISD::CondCode Opcode = getICmpCondCode(predicate);
02232 
02233   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02234   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
02235 }
02236 
02237 void SelectionDAGBuilder::visitFCmp(const User &I) {
02238   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
02239   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
02240     predicate = FC->getPredicate();
02241   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
02242     predicate = FCmpInst::Predicate(FC->getPredicate());
02243   SDValue Op1 = getValue(I.getOperand(0));
02244   SDValue Op2 = getValue(I.getOperand(1));
02245   ISD::CondCode Condition = getFCmpCondCode(predicate);
02246   if (TM.Options.NoNaNsFPMath)
02247     Condition = getFCmpCodeWithoutNaN(Condition);
02248   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02249   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
02250 }
02251 
02252 void SelectionDAGBuilder::visitSelect(const User &I) {
02253   SmallVector<EVT, 4> ValueVTs;
02254   ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
02255   unsigned NumValues = ValueVTs.size();
02256   if (NumValues == 0) return;
02257 
02258   SmallVector<SDValue, 4> Values(NumValues);
02259   SDValue Cond     = getValue(I.getOperand(0));
02260   SDValue LHSVal   = getValue(I.getOperand(1));
02261   SDValue RHSVal   = getValue(I.getOperand(2));
02262   auto BaseOps = {Cond};
02263   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
02264     ISD::VSELECT : ISD::SELECT;
02265 
02266   // Min/max matching is only viable if all output VTs are the same.
02267   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
02268     Value *LHS, *RHS;
02269     SelectPatternFlavor SPF = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
02270     ISD::NodeType Opc = ISD::DELETED_NODE;
02271     switch (SPF) {
02272     case SPF_UMAX: Opc = ISD::UMAX; break;
02273     case SPF_UMIN: Opc = ISD::UMIN; break;
02274     case SPF_SMAX: Opc = ISD::SMAX; break;
02275     case SPF_SMIN: Opc = ISD::SMIN; break;
02276     default: break;
02277     }
02278 
02279     EVT VT = ValueVTs[0];
02280     LLVMContext &Ctx = *DAG.getContext();
02281     auto &TLI = DAG.getTargetLoweringInfo();
02282     while (TLI.getTypeAction(Ctx, VT) == TargetLoweringBase::TypeSplitVector)
02283       VT = TLI.getTypeToTransformTo(Ctx, VT);
02284 
02285     if (Opc != ISD::DELETED_NODE && TLI.isOperationLegalOrCustom(Opc, VT)) {
02286       OpCode = Opc;
02287       LHSVal = getValue(LHS);
02288       RHSVal = getValue(RHS);
02289       BaseOps = {};
02290     }
02291   }
02292 
02293   for (unsigned i = 0; i != NumValues; ++i) {
02294     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
02295     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
02296     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
02297     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
02298                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
02299                             Ops);
02300   }
02301 
02302   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
02303                            DAG.getVTList(ValueVTs), Values));
02304 }
02305 
02306 void SelectionDAGBuilder::visitTrunc(const User &I) {
02307   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
02308   SDValue N = getValue(I.getOperand(0));
02309   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02310   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
02311 }
02312 
02313 void SelectionDAGBuilder::visitZExt(const User &I) {
02314   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
02315   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
02316   SDValue N = getValue(I.getOperand(0));
02317   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02318   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
02319 }
02320 
02321 void SelectionDAGBuilder::visitSExt(const User &I) {
02322   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
02323   // SExt also can't be a cast to bool for same reason. So, nothing much to do
02324   SDValue N = getValue(I.getOperand(0));
02325   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02326   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
02327 }
02328 
02329 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
02330   // FPTrunc is never a no-op cast, no need to check
02331   SDValue N = getValue(I.getOperand(0));
02332   SDLoc dl = getCurSDLoc();
02333   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02334   EVT DestVT = TLI.getValueType(I.getType());
02335   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
02336                            DAG.getTargetConstant(0, dl, TLI.getPointerTy())));
02337 }
02338 
02339 void SelectionDAGBuilder::visitFPExt(const User &I) {
02340   // FPExt is never a no-op cast, no need to check
02341   SDValue N = getValue(I.getOperand(0));
02342   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02343   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
02344 }
02345 
02346 void SelectionDAGBuilder::visitFPToUI(const User &I) {
02347   // FPToUI is never a no-op cast, no need to check
02348   SDValue N = getValue(I.getOperand(0));
02349   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02350   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
02351 }
02352 
02353 void SelectionDAGBuilder::visitFPToSI(const User &I) {
02354   // FPToSI is never a no-op cast, no need to check
02355   SDValue N = getValue(I.getOperand(0));
02356   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02357   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
02358 }
02359 
02360 void SelectionDAGBuilder::visitUIToFP(const User &I) {
02361   // UIToFP is never a no-op cast, no need to check
02362   SDValue N = getValue(I.getOperand(0));
02363   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02364   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
02365 }
02366 
02367 void SelectionDAGBuilder::visitSIToFP(const User &I) {
02368   // SIToFP is never a no-op cast, no need to check
02369   SDValue N = getValue(I.getOperand(0));
02370   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02371   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
02372 }
02373 
02374 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
02375   // What to do depends on the size of the integer and the size of the pointer.
02376   // We can either truncate, zero extend, or no-op, accordingly.
02377   SDValue N = getValue(I.getOperand(0));
02378   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02379   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
02380 }
02381 
02382 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
02383   // What to do depends on the size of the integer and the size of the pointer.
02384   // We can either truncate, zero extend, or no-op, accordingly.
02385   SDValue N = getValue(I.getOperand(0));
02386   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02387   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
02388 }
02389 
02390 void SelectionDAGBuilder::visitBitCast(const User &I) {
02391   SDValue N = getValue(I.getOperand(0));
02392   SDLoc dl = getCurSDLoc();
02393   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
02394 
02395   // BitCast assures us that source and destination are the same size so this is
02396   // either a BITCAST or a no-op.
02397   if (DestVT != N.getValueType())
02398     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
02399                              DestVT, N)); // convert types.
02400   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
02401   // might fold any kind of constant expression to an integer constant and that
02402   // is not what we are looking for. Only regcognize a bitcast of a genuine
02403   // constant integer as an opaque constant.
02404   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
02405     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
02406                                  /*isOpaque*/true));
02407   else
02408     setValue(&I, N);            // noop cast.
02409 }
02410 
02411 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
02412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02413   const Value *SV = I.getOperand(0);
02414   SDValue N = getValue(SV);
02415   EVT DestVT = TLI.getValueType(I.getType());
02416 
02417   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
02418   unsigned DestAS = I.getType()->getPointerAddressSpace();
02419 
02420   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
02421     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
02422 
02423   setValue(&I, N);
02424 }
02425 
02426 void SelectionDAGBuilder::visitInsertElement(const User &I) {
02427   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02428   SDValue InVec = getValue(I.getOperand(0));
02429   SDValue InVal = getValue(I.getOperand(1));
02430   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
02431                                      getCurSDLoc(), TLI.getVectorIdxTy());
02432   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
02433                            TLI.getValueType(I.getType()), InVec, InVal, InIdx));
02434 }
02435 
02436 void SelectionDAGBuilder::visitExtractElement(const User &I) {
02437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02438   SDValue InVec = getValue(I.getOperand(0));
02439   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
02440                                      getCurSDLoc(), TLI.getVectorIdxTy());
02441   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
02442                            TLI.getValueType(I.getType()), InVec, InIdx));
02443 }
02444 
02445 // Utility for visitShuffleVector - Return true if every element in Mask,
02446 // beginning from position Pos and ending in Pos+Size, falls within the
02447 // specified sequential range [L, L+Pos). or is undef.
02448 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
02449                                 unsigned Pos, unsigned Size, int Low) {
02450   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
02451     if (Mask[i] >= 0 && Mask[i] != Low)
02452       return false;
02453   return true;
02454 }
02455 
02456 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
02457   SDValue Src1 = getValue(I.getOperand(0));
02458   SDValue Src2 = getValue(I.getOperand(1));
02459 
02460   SmallVector<int, 8> Mask;
02461   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
02462   unsigned MaskNumElts = Mask.size();
02463 
02464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02465   EVT VT = TLI.getValueType(I.getType());
02466   EVT SrcVT = Src1.getValueType();
02467   unsigned SrcNumElts = SrcVT.getVectorNumElements();
02468 
02469   if (SrcNumElts == MaskNumElts) {
02470     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
02471                                       &Mask[0]));
02472     return;
02473   }
02474 
02475   // Normalize the shuffle vector since mask and vector length don't match.
02476   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
02477     // Mask is longer than the source vectors and is a multiple of the source
02478     // vectors.  We can use concatenate vector to make the mask and vectors
02479     // lengths match.
02480     if (SrcNumElts*2 == MaskNumElts) {
02481       // First check for Src1 in low and Src2 in high
02482       if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
02483           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
02484         // The shuffle is concatenating two vectors together.
02485         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
02486                                  VT, Src1, Src2));
02487         return;
02488       }
02489       // Then check for Src2 in low and Src1 in high
02490       if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
02491           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
02492         // The shuffle is concatenating two vectors together.
02493         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
02494                                  VT, Src2, Src1));
02495         return;
02496       }
02497     }
02498 
02499     // Pad both vectors with undefs to make them the same length as the mask.
02500     unsigned NumConcat = MaskNumElts / SrcNumElts;
02501     bool Src1U = Src1.getOpcode() == ISD::UNDEF;
02502     bool Src2U = Src2.getOpcode() == ISD::UNDEF;
02503     SDValue UndefVal = DAG.getUNDEF(SrcVT);
02504 
02505     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
02506     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
02507     MOps1[0] = Src1;
02508     MOps2[0] = Src2;
02509 
02510     Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
02511                                                   getCurSDLoc(), VT, MOps1);
02512     Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
02513                                                   getCurSDLoc(), VT, MOps2);
02514 
02515     // Readjust mask for new input vector length.
02516     SmallVector<int, 8> MappedOps;
02517     for (unsigned i = 0; i != MaskNumElts; ++i) {
02518       int Idx = Mask[i];
02519       if (Idx >= (int)SrcNumElts)
02520         Idx -= SrcNumElts - MaskNumElts;
02521       MappedOps.push_back(Idx);
02522     }
02523 
02524     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
02525                                       &MappedOps[0]));
02526     return;
02527   }
02528 
02529   if (SrcNumElts > MaskNumElts) {
02530     // Analyze the access pattern of the vector to see if we can extract
02531     // two subvectors and do the shuffle. The analysis is done by calculating
02532     // the range of elements the mask access on both vectors.
02533     int MinRange[2] = { static_cast<int>(SrcNumElts),
02534                         static_cast<int>(SrcNumElts)};
02535     int MaxRange[2] = {-1, -1};
02536 
02537     for (unsigned i = 0; i != MaskNumElts; ++i) {
02538       int Idx = Mask[i];
02539       unsigned Input = 0;
02540       if (Idx < 0)
02541         continue;
02542 
02543       if (Idx >= (int)SrcNumElts) {
02544         Input = 1;
02545         Idx -= SrcNumElts;
02546       }
02547       if (Idx > MaxRange[Input])
02548         MaxRange[Input] = Idx;
02549       if (Idx < MinRange[Input])
02550         MinRange[Input] = Idx;
02551     }
02552 
02553     // Check if the access is smaller than the vector size and can we find
02554     // a reasonable extract index.
02555     int RangeUse[2] = { -1, -1 };  // 0 = Unused, 1 = Extract, -1 = Can not
02556                                    // Extract.
02557     int StartIdx[2];  // StartIdx to extract from
02558     for (unsigned Input = 0; Input < 2; ++Input) {
02559       if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
02560         RangeUse[Input] = 0; // Unused
02561         StartIdx[Input] = 0;
02562         continue;
02563       }
02564 
02565       // Find a good start index that is a multiple of the mask length. Then
02566       // see if the rest of the elements are in range.
02567       StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
02568       if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
02569           StartIdx[Input] + MaskNumElts <= SrcNumElts)
02570         RangeUse[Input] = 1; // Extract from a multiple of the mask length.
02571     }
02572 
02573     if (RangeUse[0] == 0 && RangeUse[1] == 0) {
02574       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
02575       return;
02576     }
02577     if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
02578       // Extract appropriate subvector and generate a vector shuffle
02579       for (unsigned Input = 0; Input < 2; ++Input) {
02580         SDValue &Src = Input == 0 ? Src1 : Src2;
02581         if (RangeUse[Input] == 0)
02582           Src = DAG.getUNDEF(VT);
02583         else {
02584           SDLoc dl = getCurSDLoc();
02585           Src = DAG.getNode(
02586               ISD::EXTRACT_SUBVECTOR, dl, VT, Src,
02587               DAG.getConstant(StartIdx[Input], dl, TLI.getVectorIdxTy()));
02588         }
02589       }
02590 
02591       // Calculate new mask.
02592       SmallVector<int, 8> MappedOps;
02593       for (unsigned i = 0; i != MaskNumElts; ++i) {
02594         int Idx = Mask[i];
02595         if (Idx >= 0) {
02596           if (Idx < (int)SrcNumElts)
02597             Idx -= StartIdx[0];
02598           else
02599             Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
02600         }
02601         MappedOps.push_back(Idx);
02602       }
02603 
02604       setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
02605                                         &MappedOps[0]));
02606       return;
02607     }
02608   }
02609 
02610   // We can't use either concat vectors or extract subvectors so fall back to
02611   // replacing the shuffle with extract and build vector.
02612   // to insert and build vector.
02613   EVT EltVT = VT.getVectorElementType();
02614   EVT IdxVT = TLI.getVectorIdxTy();
02615   SDLoc dl = getCurSDLoc();
02616   SmallVector<SDValue,8> Ops;
02617   for (unsigned i = 0; i != MaskNumElts; ++i) {
02618     int Idx = Mask[i];
02619     SDValue Res;
02620 
02621     if (Idx < 0) {
02622       Res = DAG.getUNDEF(EltVT);
02623     } else {
02624       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
02625       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
02626 
02627       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
02628                         EltVT, Src, DAG.getConstant(Idx, dl, IdxVT));
02629     }
02630 
02631     Ops.push_back(Res);
02632   }
02633 
02634   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops));
02635 }
02636 
02637 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
02638   const Value *Op0 = I.getOperand(0);
02639   const Value *Op1 = I.getOperand(1);
02640   Type *AggTy = I.getType();
02641   Type *ValTy = Op1->getType();
02642   bool IntoUndef = isa<UndefValue>(Op0);
02643   bool FromUndef = isa<UndefValue>(Op1);
02644 
02645   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
02646 
02647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02648   SmallVector<EVT, 4> AggValueVTs;
02649   ComputeValueVTs(TLI, AggTy, AggValueVTs);
02650   SmallVector<EVT, 4> ValValueVTs;
02651   ComputeValueVTs(TLI, ValTy, ValValueVTs);
02652 
02653   unsigned NumAggValues = AggValueVTs.size();
02654   unsigned NumValValues = ValValueVTs.size();
02655   SmallVector<SDValue, 4> Values(NumAggValues);
02656 
02657   // Ignore an insertvalue that produces an empty object
02658   if (!NumAggValues) {
02659     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
02660     return;
02661   }
02662 
02663   SDValue Agg = getValue(Op0);
02664   unsigned i = 0;
02665   // Copy the beginning value(s) from the original aggregate.
02666   for (; i != LinearIndex; ++i)
02667     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
02668                 SDValue(Agg.getNode(), Agg.getResNo() + i);
02669   // Copy values from the inserted value(s).
02670   if (NumValValues) {
02671     SDValue Val = getValue(Op1);
02672     for (; i != LinearIndex + NumValValues; ++i)
02673       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
02674                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
02675   }
02676   // Copy remaining value(s) from the original aggregate.
02677   for (; i != NumAggValues; ++i)
02678     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
02679                 SDValue(Agg.getNode(), Agg.getResNo() + i);
02680 
02681   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
02682                            DAG.getVTList(AggValueVTs), Values));
02683 }
02684 
02685 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
02686   const Value *Op0 = I.getOperand(0);
02687   Type *AggTy = Op0->getType();
02688   Type *ValTy = I.getType();
02689   bool OutOfUndef = isa<UndefValue>(Op0);
02690 
02691   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
02692 
02693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02694   SmallVector<EVT, 4> ValValueVTs;
02695   ComputeValueVTs(TLI, ValTy, ValValueVTs);
02696 
02697   unsigned NumValValues = ValValueVTs.size();
02698 
02699   // Ignore a extractvalue that produces an empty object
02700   if (!NumValValues) {
02701     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
02702     return;
02703   }
02704 
02705   SmallVector<SDValue, 4> Values(NumValValues);
02706 
02707   SDValue Agg = getValue(Op0);
02708   // Copy out the selected value(s).
02709   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
02710     Values[i - LinearIndex] =
02711       OutOfUndef ?
02712         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
02713         SDValue(Agg.getNode(), Agg.getResNo() + i);
02714 
02715   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
02716                            DAG.getVTList(ValValueVTs), Values));
02717 }
02718 
02719 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
02720   Value *Op0 = I.getOperand(0);
02721   // Note that the pointer operand may be a vector of pointers. Take the scalar
02722   // element which holds a pointer.
02723   Type *Ty = Op0->getType()->getScalarType();
02724   unsigned AS = Ty->getPointerAddressSpace();
02725   SDValue N = getValue(Op0);
02726   SDLoc dl = getCurSDLoc();
02727 
02728   for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
02729        OI != E; ++OI) {
02730     const Value *Idx = *OI;
02731     if (StructType *StTy = dyn_cast<StructType>(Ty)) {
02732       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
02733       if (Field) {
02734         // N = N + Offset
02735         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
02736         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
02737                         DAG.getConstant(Offset, dl, N.getValueType()));
02738       }
02739 
02740       Ty = StTy->getElementType(Field);
02741     } else {
02742       Ty = cast<SequentialType>(Ty)->getElementType();
02743       MVT PtrTy = DAG.getTargetLoweringInfo().getPointerTy(AS);
02744       unsigned PtrSize = PtrTy.getSizeInBits();
02745       APInt ElementSize(PtrSize, DL->getTypeAllocSize(Ty));
02746 
02747       // If this is a constant subscript, handle it quickly.
02748       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
02749         if (CI->isZero())
02750           continue;
02751         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
02752         SDValue OffsVal = DAG.getConstant(Offs, dl, PtrTy);
02753         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal);
02754         continue;
02755       }
02756 
02757       // N = N + Idx * ElementSize;
02758       SDValue IdxN = getValue(Idx);
02759 
02760       // If the index is smaller or larger than intptr_t, truncate or extend
02761       // it.
02762       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
02763 
02764       // If this is a multiply by a power of two, turn it into a shl
02765       // immediately.  This is a very common case.
02766       if (ElementSize != 1) {
02767         if (ElementSize.isPowerOf2()) {
02768           unsigned Amt = ElementSize.logBase2();
02769           IdxN = DAG.getNode(ISD::SHL, dl,
02770                              N.getValueType(), IdxN,
02771                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
02772         } else {
02773           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
02774           IdxN = DAG.getNode(ISD::MUL, dl,
02775                              N.getValueType(), IdxN, Scale);
02776         }
02777       }
02778 
02779       N = DAG.getNode(ISD::ADD, dl,
02780                       N.getValueType(), N, IdxN);
02781     }
02782   }
02783 
02784   setValue(&I, N);
02785 }
02786 
02787 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
02788   // If this is a fixed sized alloca in the entry block of the function,
02789   // allocate it statically on the stack.
02790   if (FuncInfo.StaticAllocaMap.count(&I))
02791     return;   // getValue will auto-populate this.
02792 
02793   SDLoc dl = getCurSDLoc();
02794   Type *Ty = I.getAllocatedType();
02795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02796   uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
02797   unsigned Align =
02798       std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
02799                I.getAlignment());
02800 
02801   SDValue AllocSize = getValue(I.getArraySize());
02802 
02803   EVT IntPtr = TLI.getPointerTy();
02804   if (AllocSize.getValueType() != IntPtr)
02805     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
02806 
02807   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
02808                           AllocSize,
02809                           DAG.getConstant(TySize, dl, IntPtr));
02810 
02811   // Handle alignment.  If the requested alignment is less than or equal to
02812   // the stack alignment, ignore it.  If the size is greater than or equal to
02813   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
02814   unsigned StackAlign =
02815       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
02816   if (Align <= StackAlign)
02817     Align = 0;
02818 
02819   // Round the size of the allocation up to the stack alignment size
02820   // by add SA-1 to the size.
02821   AllocSize = DAG.getNode(ISD::ADD, dl,
02822                           AllocSize.getValueType(), AllocSize,
02823                           DAG.getIntPtrConstant(StackAlign - 1, dl));
02824 
02825   // Mask out the low bits for alignment purposes.
02826   AllocSize = DAG.getNode(ISD::AND, dl,
02827                           AllocSize.getValueType(), AllocSize,
02828                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
02829                                                 dl));
02830 
02831   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
02832   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
02833   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
02834   setValue(&I, DSA);
02835   DAG.setRoot(DSA.getValue(1));
02836 
02837   assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
02838 }
02839 
02840 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
02841   if (I.isAtomic())
02842     return visitAtomicLoad(I);
02843 
02844   const Value *SV = I.getOperand(0);
02845   SDValue Ptr = getValue(SV);
02846 
02847   Type *Ty = I.getType();
02848 
02849   bool isVolatile = I.isVolatile();
02850   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
02851   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
02852   unsigned Alignment = I.getAlignment();
02853 
02854   AAMDNodes AAInfo;
02855   I.getAAMetadata(AAInfo);
02856   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
02857 
02858   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02859   SmallVector<EVT, 4> ValueVTs;
02860   SmallVector<uint64_t, 4> Offsets;
02861   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
02862   unsigned NumValues = ValueVTs.size();
02863   if (NumValues == 0)
02864     return;
02865 
02866   SDValue Root;
02867   bool ConstantMemory = false;
02868   if (isVolatile || NumValues > MaxParallelChains)
02869     // Serialize volatile loads with other side effects.
02870     Root = getRoot();
02871   else if (AA->pointsToConstantMemory(
02872              AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
02873     // Do not serialize (non-volatile) loads of constant memory with anything.
02874     Root = DAG.getEntryNode();
02875     ConstantMemory = true;
02876   } else {
02877     // Do not serialize non-volatile loads against each other.
02878     Root = DAG.getRoot();
02879   }
02880 
02881   SDLoc dl = getCurSDLoc();
02882 
02883   if (isVolatile)
02884     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
02885 
02886   SmallVector<SDValue, 4> Values(NumValues);
02887   SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
02888                                           NumValues));
02889   EVT PtrVT = Ptr.getValueType();
02890   unsigned ChainI = 0;
02891   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
02892     // Serializing loads here may result in excessive register pressure, and
02893     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
02894     // could recover a bit by hoisting nodes upward in the chain by recognizing
02895     // they are side-effect free or do not alias. The optimizer should really
02896     // avoid this case by converting large object/array copies to llvm.memcpy
02897     // (MaxParallelChains should always remain as failsafe).
02898     if (ChainI == MaxParallelChains) {
02899       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
02900       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
02901                                   makeArrayRef(Chains.data(), ChainI));
02902       Root = Chain;
02903       ChainI = 0;
02904     }
02905     SDValue A = DAG.getNode(ISD::ADD, dl,
02906                             PtrVT, Ptr,
02907                             DAG.getConstant(Offsets[i], dl, PtrVT));
02908     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root,
02909                             A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
02910                             isNonTemporal, isInvariant, Alignment, AAInfo,
02911                             Ranges);
02912 
02913     Values[i] = L;
02914     Chains[ChainI] = L.getValue(1);
02915   }
02916 
02917   if (!ConstantMemory) {
02918     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
02919                                 makeArrayRef(Chains.data(), ChainI));
02920     if (isVolatile)
02921       DAG.setRoot(Chain);
02922     else
02923       PendingLoads.push_back(Chain);
02924   }
02925 
02926   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
02927                            DAG.getVTList(ValueVTs), Values));
02928 }
02929 
02930 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
02931   if (I.isAtomic())
02932     return visitAtomicStore(I);
02933 
02934   const Value *SrcV = I.getOperand(0);
02935   const Value *PtrV = I.getOperand(1);
02936 
02937   SmallVector<EVT, 4> ValueVTs;
02938   SmallVector<uint64_t, 4> Offsets;
02939   ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
02940                   ValueVTs, &Offsets);
02941   unsigned NumValues = ValueVTs.size();
02942   if (NumValues == 0)
02943     return;
02944 
02945   // Get the lowered operands. Note that we do this after
02946   // checking if NumResults is zero, because with zero results
02947   // the operands won't have values in the map.
02948   SDValue Src = getValue(SrcV);
02949   SDValue Ptr = getValue(PtrV);
02950 
02951   SDValue Root = getRoot();
02952   SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
02953                                           NumValues));
02954   EVT PtrVT = Ptr.getValueType();
02955   bool isVolatile = I.isVolatile();
02956   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
02957   unsigned Alignment = I.getAlignment();
02958   SDLoc dl = getCurSDLoc();
02959 
02960   AAMDNodes AAInfo;
02961   I.getAAMetadata(AAInfo);
02962 
02963   unsigned ChainI = 0;
02964   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
02965     // See visitLoad comments.
02966     if (ChainI == MaxParallelChains) {
02967       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
02968                                   makeArrayRef(Chains.data(), ChainI));
02969       Root = Chain;
02970       ChainI = 0;
02971     }
02972     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
02973                               DAG.getConstant(Offsets[i], dl, PtrVT));
02974     SDValue St = DAG.getStore(Root, dl,
02975                               SDValue(Src.getNode(), Src.getResNo() + i),
02976                               Add, MachinePointerInfo(PtrV, Offsets[i]),
02977                               isVolatile, isNonTemporal, Alignment, AAInfo);
02978     Chains[ChainI] = St;
02979   }
02980 
02981   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
02982                                   makeArrayRef(Chains.data(), ChainI));
02983   DAG.setRoot(StoreNode);
02984 }
02985 
02986 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
02987   SDLoc sdl = getCurSDLoc();
02988 
02989   // llvm.masked.store.*(Src0, Ptr, alignemt, Mask)
02990   Value  *PtrOperand = I.getArgOperand(1);
02991   SDValue Ptr = getValue(PtrOperand);
02992   SDValue Src0 = getValue(I.getArgOperand(0));
02993   SDValue Mask = getValue(I.getArgOperand(3));
02994   EVT VT = Src0.getValueType();
02995   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
02996   if (!Alignment)
02997     Alignment = DAG.getEVTAlignment(VT);
02998 
02999   AAMDNodes AAInfo;
03000   I.getAAMetadata(AAInfo);
03001 
03002   MachineMemOperand *MMO =
03003     DAG.getMachineFunction().
03004     getMachineMemOperand(MachinePointerInfo(PtrOperand),
03005                           MachineMemOperand::MOStore,  VT.getStoreSize(),
03006                           Alignment, AAInfo);
03007   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
03008                                          MMO, false);
03009   DAG.setRoot(StoreNode);
03010   setValue(&I, StoreNode);
03011 }
03012 
03013 // Gather/scatter receive a vector of pointers.
03014 // This vector of pointers may be represented as a base pointer + vector of 
03015 // indices, it depends on GEP and instruction preceeding GEP
03016 // that calculates indices
03017 static bool getUniformBase(Value *& Ptr, SDValue& Base, SDValue& Index,
03018                            SelectionDAGBuilder* SDB) {
03019 
03020   assert (Ptr->getType()->isVectorTy() && "Uexpected pointer type");
03021   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
03022   if (!Gep || Gep->getNumOperands() > 2)
03023     return false;
03024   ShuffleVectorInst *ShuffleInst = 
03025     dyn_cast<ShuffleVectorInst>(Gep->getPointerOperand());
03026   if (!ShuffleInst || !ShuffleInst->getMask()->isNullValue() ||
03027       cast<Instruction>(ShuffleInst->getOperand(0))->getOpcode() !=
03028       Instruction::InsertElement)
03029     return false;
03030 
03031   Ptr = cast<InsertElementInst>(ShuffleInst->getOperand(0))->getOperand(1);
03032 
03033   SelectionDAG& DAG = SDB->DAG;
03034   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03035   // Check is the Ptr is inside current basic block
03036   // If not, look for the shuffle instruction
03037   if (SDB->findValue(Ptr))
03038     Base = SDB->getValue(Ptr);
03039   else if (SDB->findValue(ShuffleInst)) {
03040     SDValue ShuffleNode = SDB->getValue(ShuffleInst);
03041     SDLoc sdl = ShuffleNode;
03042     Base = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl,
03043                        ShuffleNode.getValueType().getScalarType(), ShuffleNode,
03044                        DAG.getConstant(0, sdl, TLI.getVectorIdxTy()));
03045     SDB->setValue(Ptr, Base);
03046   }
03047   else
03048     return false;
03049 
03050   Value *IndexVal = Gep->getOperand(1);
03051   if (SDB->findValue(IndexVal)) {
03052     Index = SDB->getValue(IndexVal);
03053 
03054     if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) {
03055       IndexVal = Sext->getOperand(0);
03056       if (SDB->findValue(IndexVal))
03057         Index = SDB->getValue(IndexVal);
03058     }
03059     return true;
03060   }
03061   return false;
03062 }
03063 
03064 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
03065   SDLoc sdl = getCurSDLoc();
03066 
03067   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
03068   Value  *Ptr = I.getArgOperand(1);
03069   SDValue Src0 = getValue(I.getArgOperand(0));
03070   SDValue Mask = getValue(I.getArgOperand(3));
03071   EVT VT = Src0.getValueType();
03072   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
03073   if (!Alignment)
03074     Alignment = DAG.getEVTAlignment(VT);
03075   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03076 
03077   AAMDNodes AAInfo;
03078   I.getAAMetadata(AAInfo);
03079 
03080   SDValue Base;
03081   SDValue Index;
03082   Value *BasePtr = Ptr;
03083   bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
03084 
03085   Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
03086   MachineMemOperand *MMO = DAG.getMachineFunction().
03087     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
03088                          MachineMemOperand::MOStore,  VT.getStoreSize(),
03089                          Alignment, AAInfo);
03090   if (!UniformBase) {
03091     Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy());
03092     Index = getValue(Ptr);
03093   }
03094   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
03095   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
03096                                          Ops, MMO);
03097   DAG.setRoot(Scatter);
03098   setValue(&I, Scatter);
03099 }
03100 
03101 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
03102   SDLoc sdl = getCurSDLoc();
03103 
03104   // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
03105   Value  *PtrOperand = I.getArgOperand(0);
03106   SDValue Ptr = getValue(PtrOperand);
03107   SDValue Src0 = getValue(I.getArgOperand(3));
03108   SDValue Mask = getValue(I.getArgOperand(2));
03109 
03110   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03111   EVT VT = TLI.getValueType(I.getType());
03112   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
03113   if (!Alignment)
03114     Alignment = DAG.getEVTAlignment(VT);
03115 
03116   AAMDNodes AAInfo;
03117   I.getAAMetadata(AAInfo);
03118   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
03119 
03120   SDValue InChain = DAG.getRoot();
03121   if (AA->pointsToConstantMemory(
03122       AliasAnalysis::Location(PtrOperand,
03123                               AA->getTypeStoreSize(I.getType()),
03124                               AAInfo))) {
03125     // Do not serialize (non-volatile) loads of constant memory with anything.
03126     InChain = DAG.getEntryNode();
03127   }
03128 
03129   MachineMemOperand *MMO =
03130     DAG.getMachineFunction().
03131     getMachineMemOperand(MachinePointerInfo(PtrOperand),
03132                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
03133                           Alignment, AAInfo, Ranges);
03134 
03135   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
03136                                    ISD::NON_EXTLOAD);
03137   SDValue OutChain = Load.getValue(1);
03138   DAG.setRoot(OutChain);
03139   setValue(&I, Load);
03140 }
03141 
03142 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
03143   SDLoc sdl = getCurSDLoc();
03144 
03145   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
03146   Value  *Ptr = I.getArgOperand(0);
03147   SDValue Src0 = getValue(I.getArgOperand(3));
03148   SDValue Mask = getValue(I.getArgOperand(2));
03149 
03150   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03151   EVT VT = TLI.getValueType(I.getType());
03152   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
03153   if (!Alignment)
03154     Alignment = DAG.getEVTAlignment(VT);
03155 
03156   AAMDNodes AAInfo;
03157   I.getAAMetadata(AAInfo);
03158   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
03159 
03160   SDValue Root = DAG.getRoot();
03161   SDValue Base;
03162   SDValue Index;
03163   Value *BasePtr = Ptr;
03164   bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
03165   bool ConstantMemory = false;
03166   if (UniformBase && AA->pointsToConstantMemory(
03167       AliasAnalysis::Location(BasePtr,
03168                               AA->getTypeStoreSize(I.getType()),
03169                               AAInfo))) {
03170     // Do not serialize (non-volatile) loads of constant memory with anything.
03171     Root = DAG.getEntryNode();
03172     ConstantMemory = true;
03173   }
03174 
03175   MachineMemOperand *MMO =
03176     DAG.getMachineFunction().
03177     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
03178                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
03179                          Alignment, AAInfo, Ranges);
03180 
03181   if (!UniformBase) {
03182     Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy());
03183     Index = getValue(Ptr);
03184   }
03185   SDValue Ops[] = { Root, Src0, Mask, Base, Index };
03186   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
03187                                        Ops, MMO);
03188 
03189   SDValue OutChain = Gather.getValue(1);
03190   if (!ConstantMemory)
03191     PendingLoads.push_back(OutChain);
03192   setValue(&I, Gather);
03193 }
03194 
03195 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
03196   SDLoc dl = getCurSDLoc();
03197   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
03198   AtomicOrdering FailureOrder = I.getFailureOrdering();
03199   SynchronizationScope Scope = I.getSynchScope();
03200 
03201   SDValue InChain = getRoot();
03202 
03203   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
03204   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
03205   SDValue L = DAG.getAtomicCmpSwap(
03206       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
03207       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
03208       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
03209       /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
03210 
03211   SDValue OutChain = L.getValue(2);
03212 
03213   setValue(&I, L);
03214   DAG.setRoot(OutChain);
03215 }
03216 
03217 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
03218   SDLoc dl = getCurSDLoc();
03219   ISD::NodeType NT;
03220   switch (I.getOperation()) {
03221   default: llvm_unreachable("Unknown atomicrmw operation");
03222   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
03223   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
03224   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
03225   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
03226   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
03227   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
03228   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
03229   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
03230   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
03231   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
03232   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
03233   }
03234   AtomicOrdering Order = I.getOrdering();
03235   SynchronizationScope Scope = I.getSynchScope();
03236 
03237   SDValue InChain = getRoot();
03238 
03239   SDValue L =
03240     DAG.getAtomic(NT, dl,
03241                   getValue(I.getValOperand()).getSimpleValueType(),
03242                   InChain,
03243                   getValue(I.getPointerOperand()),
03244                   getValue(I.getValOperand()),
03245                   I.getPointerOperand(),
03246                   /* Alignment=*/ 0, Order, Scope);
03247 
03248   SDValue OutChain = L.getValue(1);
03249 
03250   setValue(&I, L);
03251   DAG.setRoot(OutChain);
03252 }
03253 
03254 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
03255   SDLoc dl = getCurSDLoc();
03256   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03257   SDValue Ops[3];
03258   Ops[0] = getRoot();
03259   Ops[1] = DAG.getConstant(I.getOrdering(), dl, TLI.getPointerTy());
03260   Ops[2] = DAG.getConstant(I.getSynchScope(), dl, TLI.getPointerTy());
03261   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
03262 }
03263 
03264 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
03265   SDLoc dl = getCurSDLoc();
03266   AtomicOrdering Order = I.getOrdering();
03267   SynchronizationScope Scope = I.getSynchScope();
03268 
03269   SDValue InChain = getRoot();
03270 
03271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03272   EVT VT = TLI.getValueType(I.getType());
03273 
03274   if (I.getAlignment() < VT.getSizeInBits() / 8)
03275     report_fatal_error("Cannot generate unaligned atomic load");
03276 
03277   MachineMemOperand *MMO =
03278       DAG.getMachineFunction().
03279       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
03280                            MachineMemOperand::MOVolatile |
03281                            MachineMemOperand::MOLoad,
03282                            VT.getStoreSize(),
03283                            I.getAlignment() ? I.getAlignment() :
03284                                               DAG.getEVTAlignment(VT));
03285 
03286   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
03287   SDValue L =
03288       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
03289                     getValue(I.getPointerOperand()), MMO,
03290                     Order, Scope);
03291 
03292   SDValue OutChain = L.getValue(1);
03293 
03294   setValue(&I, L);
03295   DAG.setRoot(OutChain);
03296 }
03297 
03298 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
03299   SDLoc dl = getCurSDLoc();
03300 
03301   AtomicOrdering Order = I.getOrdering();
03302   SynchronizationScope Scope = I.getSynchScope();
03303 
03304   SDValue InChain = getRoot();
03305 
03306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03307   EVT VT = TLI.getValueType(I.getValueOperand()->getType());
03308 
03309   if (I.getAlignment() < VT.getSizeInBits() / 8)
03310     report_fatal_error("Cannot generate unaligned atomic store");
03311 
03312   SDValue OutChain =
03313     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
03314                   InChain,
03315                   getValue(I.getPointerOperand()),
03316                   getValue(I.getValueOperand()),
03317                   I.getPointerOperand(), I.getAlignment(),
03318                   Order, Scope);
03319 
03320   DAG.setRoot(OutChain);
03321 }
03322 
03323 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
03324 /// node.
03325 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
03326                                                unsigned Intrinsic) {
03327   bool HasChain = !I.doesNotAccessMemory();
03328   bool OnlyLoad = HasChain && I.onlyReadsMemory();
03329 
03330   // Build the operand list.
03331   SmallVector<SDValue, 8> Ops;
03332   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
03333     if (OnlyLoad) {
03334       // We don't need to serialize loads against other loads.
03335       Ops.push_back(DAG.getRoot());
03336     } else {
03337       Ops.push_back(getRoot());
03338     }
03339   }
03340 
03341   // Info is set by getTgtMemInstrinsic
03342   TargetLowering::IntrinsicInfo Info;
03343   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03344   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
03345 
03346   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
03347   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
03348       Info.opc == ISD::INTRINSIC_W_CHAIN)
03349     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
03350                                         TLI.getPointerTy()));
03351 
03352   // Add all operands of the call to the operand list.
03353   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
03354     SDValue Op = getValue(I.getArgOperand(i));
03355     Ops.push_back(Op);
03356   }
03357 
03358   SmallVector<EVT, 4> ValueVTs;
03359   ComputeValueVTs(TLI, I.getType(), ValueVTs);
03360 
03361   if (HasChain)
03362     ValueVTs.push_back(MVT::Other);
03363 
03364   SDVTList VTs = DAG.getVTList(ValueVTs);
03365 
03366   // Create the node.
03367   SDValue Result;
03368   if (IsTgtIntrinsic) {
03369     // This is target intrinsic that touches memory
03370     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
03371                                      VTs, Ops, Info.memVT,
03372                                    MachinePointerInfo(Info.ptrVal, Info.offset),
03373                                      Info.align, Info.vol,
03374                                      Info.readMem, Info.writeMem, Info.size);
03375   } else if (!HasChain) {
03376     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
03377   } else if (!I.getType()->isVoidTy()) {
03378     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
03379   } else {
03380     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
03381   }
03382 
03383   if (HasChain) {
03384     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
03385     if (OnlyLoad)
03386       PendingLoads.push_back(Chain);
03387     else
03388       DAG.setRoot(Chain);
03389   }
03390 
03391   if (!I.getType()->isVoidTy()) {
03392     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
03393       EVT VT = TLI.getValueType(PTy);
03394       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
03395     }
03396 
03397     setValue(&I, Result);
03398   }
03399 }
03400 
03401 /// GetSignificand - Get the significand and build it into a floating-point
03402 /// number with exponent of 1:
03403 ///
03404 ///   Op = (Op & 0x007fffff) | 0x3f800000;
03405 ///
03406 /// where Op is the hexadecimal representation of floating point value.
03407 static SDValue
03408 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
03409   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
03410                            DAG.getConstant(0x007fffff, dl, MVT::i32));
03411   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
03412                            DAG.getConstant(0x3f800000, dl, MVT::i32));
03413   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
03414 }
03415 
03416 /// GetExponent - Get the exponent:
03417 ///
03418 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
03419 ///
03420 /// where Op is the hexadecimal representation of floating point value.
03421 static SDValue
03422 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
03423             SDLoc dl) {
03424   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
03425                            DAG.getConstant(0x7f800000, dl, MVT::i32));
03426   SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
03427                            DAG.getConstant(23, dl, TLI.getPointerTy()));
03428   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
03429                            DAG.getConstant(127, dl, MVT::i32));
03430   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
03431 }
03432 
03433 /// getF32Constant - Get 32-bit floating point constant.
03434 static SDValue
03435 getF32Constant(SelectionDAG &DAG, unsigned Flt, SDLoc dl) {
03436   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl,
03437                            MVT::f32);
03438 }
03439 
03440 static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl,
03441                                        SelectionDAG &DAG) {
03442   //   IntegerPartOfX = ((int32_t)(t0);
03443   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
03444 
03445   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
03446   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
03447   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
03448 
03449   //   IntegerPartOfX <<= 23;
03450   IntegerPartOfX = DAG.getNode(
03451       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
03452       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy()));
03453 
03454   SDValue TwoToFractionalPartOfX;
03455   if (LimitFloatPrecision <= 6) {
03456     // For floating-point precision of 6:
03457     //
03458     //   TwoToFractionalPartOfX =
03459     //     0.997535578f +
03460     //       (0.735607626f + 0.252464424f * x) * x;
03461     //
03462     // error 0.0144103317, which is 6 bits
03463     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03464                              getF32Constant(DAG, 0x3e814304, dl));
03465     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03466                              getF32Constant(DAG, 0x3f3c50c8, dl));
03467     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03468     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03469                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
03470   } else if (LimitFloatPrecision <= 12) {
03471     // For floating-point precision of 12:
03472     //
03473     //   TwoToFractionalPartOfX =
03474     //     0.999892986f +
03475     //       (0.696457318f +
03476     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
03477     //
03478     // error 0.000107046256, which is 13 to 14 bits
03479     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03480                              getF32Constant(DAG, 0x3da235e3, dl));
03481     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03482                              getF32Constant(DAG, 0x3e65b8f3, dl));
03483     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03484     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03485                              getF32Constant(DAG, 0x3f324b07, dl));
03486     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03487     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03488                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
03489   } else { // LimitFloatPrecision <= 18
03490     // For floating-point precision of 18:
03491     //
03492     //   TwoToFractionalPartOfX =
03493     //     0.999999982f +
03494     //       (0.693148872f +
03495     //         (0.240227044f +
03496     //           (0.554906021e-1f +
03497     //             (0.961591928e-2f +
03498     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
03499     // error 2.47208000*10^(-7), which is better than 18 bits
03500     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03501                              getF32Constant(DAG, 0x3924b03e, dl));
03502     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03503                              getF32Constant(DAG, 0x3ab24b87, dl));
03504     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03505     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03506                              getF32Constant(DAG, 0x3c1d8c17, dl));
03507     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03508     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03509                              getF32Constant(DAG, 0x3d634a1d, dl));
03510     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03511     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
03512                              getF32Constant(DAG, 0x3e75fe14, dl));
03513     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
03514     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
03515                               getF32Constant(DAG, 0x3f317234, dl));
03516     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
03517     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
03518                                          getF32Constant(DAG, 0x3f800000, dl));
03519   }
03520 
03521   // Add the exponent into the result in integer domain.
03522   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
03523   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
03524                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
03525 }
03526 
03527 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
03528 /// limited-precision mode.
03529 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
03530                          const TargetLowering &TLI) {
03531   if (Op.getValueType() == MVT::f32 &&
03532       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03533 
03534     // Put the exponent in the right bit position for later addition to the
03535     // final result:
03536     //
03537     //   #define LOG2OFe 1.4426950f
03538     //   t0 = Op * LOG2OFe
03539     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
03540                              getF32Constant(DAG, 0x3fb8aa3b, dl));
03541     return getLimitedPrecisionExp2(t0, dl, DAG);
03542   }
03543 
03544   // No special expansion.
03545   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
03546 }
03547 
03548 /// expandLog - Lower a log intrinsic. Handles the special sequences for
03549 /// limited-precision mode.
03550 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
03551                          const TargetLowering &TLI) {
03552   if (Op.getValueType() == MVT::f32 &&
03553       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03554     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
03555 
03556     // Scale the exponent by log(2) [0.69314718f].
03557     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
03558     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
03559                                         getF32Constant(DAG, 0x3f317218, dl));
03560 
03561     // Get the significand and build it into a floating-point number with
03562     // exponent of 1.
03563     SDValue X = GetSignificand(DAG, Op1, dl);
03564 
03565     SDValue LogOfMantissa;
03566     if (LimitFloatPrecision <= 6) {
03567       // For floating-point precision of 6:
03568       //
03569       //   LogofMantissa =
03570       //     -1.1609546f +
03571       //       (1.4034025f - 0.23903021f * x) * x;
03572       //
03573       // error 0.0034276066, which is better than 8 bits
03574       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03575                                getF32Constant(DAG, 0xbe74c456, dl));
03576       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03577                                getF32Constant(DAG, 0x3fb3a2b1, dl));
03578       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03579       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03580                                   getF32Constant(DAG, 0x3f949a29, dl));
03581     } else if (LimitFloatPrecision <= 12) {
03582       // For floating-point precision of 12:
03583       //
03584       //   LogOfMantissa =
03585       //     -1.7417939f +
03586       //       (2.8212026f +
03587       //         (-1.4699568f +
03588       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
03589       //
03590       // error 0.000061011436, which is 14 bits
03591       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03592                                getF32Constant(DAG, 0xbd67b6d6, dl));
03593       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03594                                getF32Constant(DAG, 0x3ee4f4b8, dl));
03595       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03596       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03597                                getF32Constant(DAG, 0x3fbc278b, dl));
03598       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03599       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03600                                getF32Constant(DAG, 0x40348e95, dl));
03601       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03602       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
03603                                   getF32Constant(DAG, 0x3fdef31a, dl));
03604     } else { // LimitFloatPrecision <= 18
03605       // For floating-point precision of 18:
03606       //
03607       //   LogOfMantissa =
03608       //     -2.1072184f +
03609       //       (4.2372794f +
03610       //         (-3.7029485f +
03611       //           (2.2781945f +
03612       //             (-0.87823314f +
03613       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
03614       //
03615       // error 0.0000023660568, which is better than 18 bits
03616       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03617                                getF32Constant(DAG, 0xbc91e5ac, dl));
03618       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03619                                getF32Constant(DAG, 0x3e4350aa, dl));
03620       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03621       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03622                                getF32Constant(DAG, 0x3f60d3e3, dl));
03623       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03624       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03625                                getF32Constant(DAG, 0x4011cdf0, dl));
03626       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03627       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
03628                                getF32Constant(DAG, 0x406cfd1c, dl));
03629       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03630       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
03631                                getF32Constant(DAG, 0x408797cb, dl));
03632       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
03633       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
03634                                   getF32Constant(DAG, 0x4006dcab, dl));
03635     }
03636 
03637     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
03638   }
03639 
03640   // No special expansion.
03641   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
03642 }
03643 
03644 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
03645 /// limited-precision mode.
03646 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
03647                           const TargetLowering &TLI) {
03648   if (Op.getValueType() == MVT::f32 &&
03649       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03650     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
03651 
03652     // Get the exponent.
03653     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
03654 
03655     // Get the significand and build it into a floating-point number with
03656     // exponent of 1.
03657     SDValue X = GetSignificand(DAG, Op1, dl);
03658 
03659     // Different possible minimax approximations of significand in
03660     // floating-point for various degrees of accuracy over [1,2].
03661     SDValue Log2ofMantissa;
03662     if (LimitFloatPrecision <= 6) {
03663       // For floating-point precision of 6:
03664       //
03665       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
03666       //
03667       // error 0.0049451742, which is more than 7 bits
03668       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03669                                getF32Constant(DAG, 0xbeb08fe0, dl));
03670       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03671                                getF32Constant(DAG, 0x40019463, dl));
03672       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03673       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03674                                    getF32Constant(DAG, 0x3fd6633d, dl));
03675     } else if (LimitFloatPrecision <= 12) {
03676       // For floating-point precision of 12:
03677       //
03678       //   Log2ofMantissa =
03679       //     -2.51285454f +
03680       //       (4.07009056f +
03681       //         (-2.12067489f +
03682       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
03683       //
03684       // error 0.0000876136000, which is better than 13 bits
03685       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03686                                getF32Constant(DAG, 0xbda7262e, dl));
03687       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03688                                getF32Constant(DAG, 0x3f25280b, dl));
03689       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03690       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03691                                getF32Constant(DAG, 0x4007b923, dl));
03692       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03693       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03694                                getF32Constant(DAG, 0x40823e2f, dl));
03695       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03696       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
03697                                    getF32Constant(DAG, 0x4020d29c, dl));
03698     } else { // LimitFloatPrecision <= 18
03699       // For floating-point precision of 18:
03700       //
03701       //   Log2ofMantissa =
03702       //     -3.0400495f +
03703       //       (6.1129976f +
03704       //         (-5.3420409f +
03705       //           (3.2865683f +
03706       //             (-1.2669343f +
03707       //               (0.27515199f -
03708       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
03709       //
03710       // error 0.0000018516, which is better than 18 bits
03711       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03712                                getF32Constant(DAG, 0xbcd2769e, dl));
03713       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03714                                getF32Constant(DAG, 0x3e8ce0b9, dl));
03715       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03716       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03717                                getF32Constant(DAG, 0x3fa22ae7, dl));
03718       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03719       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03720                                getF32Constant(DAG, 0x40525723, dl));
03721       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03722       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
03723                                getF32Constant(DAG, 0x40aaf200, dl));
03724       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03725       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
03726                                getF32Constant(DAG, 0x40c39dad, dl));
03727       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
03728       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
03729                                    getF32Constant(DAG, 0x4042902c, dl));
03730     }
03731 
03732     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
03733   }
03734 
03735   // No special expansion.
03736   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
03737 }
03738 
03739 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
03740 /// limited-precision mode.
03741 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
03742                            const TargetLowering &TLI) {
03743   if (Op.getValueType() == MVT::f32 &&
03744       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03745     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
03746 
03747     // Scale the exponent by log10(2) [0.30102999f].
03748     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
03749     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
03750                                         getF32Constant(DAG, 0x3e9a209a, dl));
03751 
03752     // Get the significand and build it into a floating-point number with
03753     // exponent of 1.
03754     SDValue X = GetSignificand(DAG, Op1, dl);
03755 
03756     SDValue Log10ofMantissa;
03757     if (LimitFloatPrecision <= 6) {
03758       // For floating-point precision of 6:
03759       //
03760       //   Log10ofMantissa =
03761       //     -0.50419619f +
03762       //       (0.60948995f - 0.10380950f * x) * x;
03763       //
03764       // error 0.0014886165, which is 6 bits
03765       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03766                                getF32Constant(DAG, 0xbdd49a13, dl));
03767       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
03768                                getF32Constant(DAG, 0x3f1c0789, dl));
03769       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03770       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
03771                                     getF32Constant(DAG, 0x3f011300, dl));
03772     } else if (LimitFloatPrecision <= 12) {
03773       // For floating-point precision of 12:
03774       //
03775       //   Log10ofMantissa =
03776       //     -0.64831180f +
03777       //       (0.91751397f +
03778       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
03779       //
03780       // error 0.00019228036, which is better than 12 bits
03781       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03782                                getF32Constant(DAG, 0x3d431f31, dl));
03783       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
03784                                getF32Constant(DAG, 0x3ea21fb2, dl));
03785       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03786       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03787                                getF32Constant(DAG, 0x3f6ae232, dl));
03788       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03789       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
03790                                     getF32Constant(DAG, 0x3f25f7c3, dl));
03791     } else { // LimitFloatPrecision <= 18
03792       // For floating-point precision of 18:
03793       //
03794       //   Log10ofMantissa =
03795       //     -0.84299375f +
03796       //       (1.5327582f +
03797       //         (-1.0688956f +
03798       //           (0.49102474f +
03799       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
03800       //
03801       // error 0.0000037995730, which is better than 18 bits
03802       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03803                                getF32Constant(DAG, 0x3c5d51ce, dl));
03804       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
03805                                getF32Constant(DAG, 0x3e00685a, dl));
03806       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
03807       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03808                                getF32Constant(DAG, 0x3efb6798, dl));
03809       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03810       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
03811                                getF32Constant(DAG, 0x3f88d192, dl));
03812       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03813       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03814                                getF32Constant(DAG, 0x3fc4316c, dl));
03815       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03816       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
03817                                     getF32Constant(DAG, 0x3f57ce70, dl));
03818     }
03819 
03820     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
03821   }
03822 
03823   // No special expansion.
03824   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
03825 }
03826 
03827 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
03828 /// limited-precision mode.
03829 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
03830                           const TargetLowering &TLI) {
03831   if (Op.getValueType() == MVT::f32 &&
03832       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
03833     return getLimitedPrecisionExp2(Op, dl, DAG);
03834 
03835   // No special expansion.
03836   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
03837 }
03838 
03839 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
03840 /// limited-precision mode with x == 10.0f.
03841 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
03842                          SelectionDAG &DAG, const TargetLowering &TLI) {
03843   bool IsExp10 = false;
03844   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
03845       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03846     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
03847       APFloat Ten(10.0f);
03848       IsExp10 = LHSC->isExactlyValue(Ten);
03849     }
03850   }
03851 
03852   if (IsExp10) {
03853     // Put the exponent in the right bit position for later addition to the
03854     // final result:
03855     //
03856     //   #define LOG2OF10 3.3219281f
03857     //   t0 = Op * LOG2OF10;
03858     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
03859                              getF32Constant(DAG, 0x40549a78, dl));
03860     return getLimitedPrecisionExp2(t0, dl, DAG);
03861   }
03862 
03863   // No special expansion.
03864   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
03865 }
03866 
03867 
03868 /// ExpandPowI - Expand a llvm.powi intrinsic.
03869 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
03870                           SelectionDAG &DAG) {
03871   // If RHS is a constant, we can expand this out to a multiplication tree,
03872   // otherwise we end up lowering to a call to __powidf2 (for example).  When
03873   // optimizing for size, we only want to do this if the expansion would produce
03874   // a small number of multiplies, otherwise we do the full expansion.
03875   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
03876     // Get the exponent as a positive value.
03877     unsigned Val = RHSC->getSExtValue();
03878     if ((int)Val < 0) Val = -Val;
03879 
03880     // powi(x, 0) -> 1.0
03881     if (Val == 0)
03882       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
03883 
03884     const Function *F = DAG.getMachineFunction().getFunction();
03885     if (!F->hasFnAttribute(Attribute::OptimizeForSize) ||
03886         // If optimizing for size, don't insert too many multiplies.  This
03887         // inserts up to 5 multiplies.
03888         countPopulation(Val) + Log2_32(Val) < 7) {
03889       // We use the simple binary decomposition method to generate the multiply
03890       // sequence.  There are more optimal ways to do this (for example,
03891       // powi(x,15) generates one more multiply than it should), but this has
03892       // the benefit of being both really simple and much better than a libcall.
03893       SDValue Res;  // Logically starts equal to 1.0
03894       SDValue CurSquare = LHS;
03895       while (Val) {
03896         if (Val & 1) {
03897           if (Res.getNode())
03898             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
03899           else
03900             Res = CurSquare;  // 1.0*CurSquare.
03901         }
03902 
03903         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
03904                                 CurSquare, CurSquare);
03905         Val >>= 1;
03906       }
03907 
03908       // If the original was negative, invert the result, producing 1/(x*x*x).
03909       if (RHSC->getSExtValue() < 0)
03910         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
03911                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
03912       return Res;
03913     }
03914   }
03915 
03916   // Otherwise, expand to a libcall.
03917   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
03918 }
03919 
03920 // getTruncatedArgReg - Find underlying register used for an truncated
03921 // argument.
03922 static unsigned getTruncatedArgReg(const SDValue &N) {
03923   if (N.getOpcode() != ISD::TRUNCATE)
03924     return 0;
03925 
03926   const SDValue &Ext = N.getOperand(0);
03927   if (Ext.getOpcode() == ISD::AssertZext ||
03928       Ext.getOpcode() == ISD::AssertSext) {
03929     const SDValue &CFR = Ext.getOperand(0);
03930     if (CFR.getOpcode() == ISD::CopyFromReg)
03931       return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
03932     if (CFR.getOpcode() == ISD::TRUNCATE)
03933       return getTruncatedArgReg(CFR);
03934   }
03935   return 0;
03936 }
03937 
03938 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
03939 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
03940 /// At the end of instruction selection, they will be inserted to the entry BB.
03941 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
03942     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
03943     DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
03944   const Argument *Arg = dyn_cast<Argument>(V);
03945   if (!Arg)
03946     return false;
03947 
03948   MachineFunction &MF = DAG.getMachineFunction();
03949   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
03950 
03951   // Ignore inlined function arguments here.
03952   //
03953   // FIXME: Should we be checking DL->inlinedAt() to determine this?
03954   if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
03955     return false;
03956 
03957   Optional<MachineOperand> Op;
03958   // Some arguments' frame index is recorded during argument lowering.
03959   if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
03960     Op = MachineOperand::CreateFI(FI);
03961 
03962   if (!Op && N.getNode()) {
03963     unsigned Reg;
03964     if (N.getOpcode() == ISD::CopyFromReg)
03965       Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
03966     else
03967       Reg = getTruncatedArgReg(N);
03968     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
03969       MachineRegisterInfo &RegInfo = MF.getRegInfo();
03970       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
03971       if (PR)
03972         Reg = PR;
03973     }
03974     if (Reg)
03975       Op = MachineOperand::CreateReg(Reg, false);
03976   }
03977 
03978   if (!Op) {
03979     // Check if ValueMap has reg number.
03980     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
03981     if (VMI != FuncInfo.ValueMap.end())
03982       Op = MachineOperand::CreateReg(VMI->second, false);
03983   }
03984 
03985   if (!Op && N.getNode())
03986     // Check if frame index is available.
03987     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
03988       if (FrameIndexSDNode *FINode =
03989           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
03990         Op = MachineOperand::CreateFI(FINode->getIndex());
03991 
03992   if (!Op)
03993     return false;
03994 
03995   assert(Variable->isValidLocationForIntrinsic(DL) &&
03996          "Expected inlined-at fields to agree");
03997   if (Op->isReg())
03998     FuncInfo.ArgDbgValues.push_back(
03999         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
04000                 Op->getReg(), Offset, Variable, Expr));
04001   else
04002     FuncInfo.ArgDbgValues.push_back(
04003         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
04004             .addOperand(*Op)
04005             .addImm(Offset)
04006             .addMetadata(Variable)
04007             .addMetadata(Expr));
04008 
04009   return true;
04010 }
04011 
04012 // VisualStudio defines setjmp as _setjmp
04013 #if defined(_MSC_VER) && defined(setjmp) && \
04014                          !defined(setjmp_undefined_for_msvc)
04015 #  pragma push_macro("setjmp")
04016 #  undef setjmp
04017 #  define setjmp_undefined_for_msvc
04018 #endif
04019 
04020 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
04021 /// we want to emit this as a call to a named external function, return the name
04022 /// otherwise lower it and return null.
04023 const char *
04024 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
04025   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
04026   SDLoc sdl = getCurSDLoc();
04027   DebugLoc dl = getCurDebugLoc();
04028   SDValue Res;
04029 
04030   switch (Intrinsic) {
04031   default:
04032     // By default, turn this into a target intrinsic node.
04033     visitTargetIntrinsic(I, Intrinsic);
04034     return nullptr;
04035   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
04036   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
04037   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
04038   case Intrinsic::returnaddress:
04039     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI.getPointerTy(),
04040                              getValue(I.getArgOperand(0))));
04041     return nullptr;
04042   case Intrinsic::frameaddress:
04043     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
04044                              getValue(I.getArgOperand(0))));
04045     return nullptr;
04046   case Intrinsic::read_register: {
04047     Value *Reg = I.getArgOperand(0);
04048     SDValue Chain = getRoot();
04049     SDValue RegName =
04050         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
04051     EVT VT = TLI.getValueType(I.getType());
04052     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
04053       DAG.getVTList(VT, MVT::Other), Chain, RegName);
04054     setValue(&I, Res);
04055     DAG.setRoot(Res.getValue(1));
04056     return nullptr;
04057   }
04058   case Intrinsic::write_register: {
04059     Value *Reg = I.getArgOperand(0);
04060     Value *RegValue = I.getArgOperand(1);
04061     SDValue Chain = getRoot();
04062     SDValue RegName =
04063         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
04064     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
04065                             RegName, getValue(RegValue)));
04066     return nullptr;
04067   }
04068   case Intrinsic::setjmp:
04069     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
04070   case Intrinsic::longjmp:
04071     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
04072   case Intrinsic::memcpy: {
04073     // FIXME: this definition of "user defined address space" is x86-specific
04074     // Assert for address < 256 since we support only user defined address
04075     // spaces.
04076     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
04077            < 256 &&
04078            cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
04079            < 256 &&
04080            "Unknown address space");
04081     SDValue Op1 = getValue(I.getArgOperand(0));
04082     SDValue Op2 = getValue(I.getArgOperand(1));
04083     SDValue Op3 = getValue(I.getArgOperand(2));
04084     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
04085     if (!Align)
04086       Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
04087     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
04088     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
04089     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
04090                                false, isTC,
04091                                MachinePointerInfo(I.getArgOperand(0)),
04092                                MachinePointerInfo(I.getArgOperand(1)));
04093     updateDAGForMaybeTailCall(MC);
04094     return nullptr;
04095   }
04096   case Intrinsic::memset: {
04097     // FIXME: this definition of "user defined address space" is x86-specific
04098     // Assert for address < 256 since we support only user defined address
04099     // spaces.
04100     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
04101            < 256 &&
04102            "Unknown address space");
04103     SDValue Op1 = getValue(I.getArgOperand(0));
04104     SDValue Op2 = getValue(I.getArgOperand(1));
04105     SDValue Op3 = getValue(I.getArgOperand(2));
04106     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
04107     if (!Align)
04108       Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
04109     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
04110     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
04111     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
04112                                isTC, MachinePointerInfo(I.getArgOperand(0)));
04113     updateDAGForMaybeTailCall(MS);
04114     return nullptr;
04115   }
04116   case Intrinsic::memmove: {
04117     // FIXME: this definition of "user defined address space" is x86-specific
04118     // Assert for address < 256 since we support only user defined address
04119     // spaces.
04120     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
04121            < 256 &&
04122            cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
04123            < 256 &&
04124            "Unknown address space");
04125     SDValue Op1 = getValue(I.getArgOperand(0));
04126     SDValue Op2 = getValue(I.getArgOperand(1));
04127     SDValue Op3 = getValue(I.getArgOperand(2));
04128     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
04129     if (!Align)
04130       Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
04131     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
04132     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
04133     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
04134                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
04135                                 MachinePointerInfo(I.getArgOperand(1)));
04136     updateDAGForMaybeTailCall(MM);
04137     return nullptr;
04138   }
04139   case Intrinsic::dbg_declare: {
04140     const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
04141     DILocalVariable *Variable = DI.getVariable();
04142     DIExpression *Expression = DI.getExpression();
04143     const Value *Address = DI.getAddress();
04144     assert(Variable && "Missing variable");
04145     if (!Address) {
04146       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04147       return nullptr;
04148     }
04149 
04150     // Check if address has undef value.
04151     if (isa<UndefValue>(Address) ||
04152         (Address->use_empty() && !isa<Argument>(Address))) {
04153       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04154       return nullptr;
04155     }
04156 
04157     SDValue &N = NodeMap[Address];
04158     if (!N.getNode() && isa<Argument>(Address))
04159       // Check unused arguments map.
04160       N = UnusedArgNodeMap[Address];
04161     SDDbgValue *SDV;
04162     if (N.getNode()) {
04163       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
04164         Address = BCI->getOperand(0);
04165       // Parameters are handled specially.
04166       bool isParameter = Variable->getTag() == dwarf::DW_TAG_arg_variable ||
04167                          isa<Argument>(Address);
04168 
04169       const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
04170 
04171       if (isParameter && !AI) {
04172         FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
04173         if (FINode)
04174           // Byval parameter.  We have a frame index at this point.
04175           SDV = DAG.getFrameIndexDbgValue(
04176               Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
04177         else {
04178           // Address is an argument, so try to emit its dbg value using
04179           // virtual register info from the FuncInfo.ValueMap.
04180           EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
04181                                    N);
04182           return nullptr;
04183         }
04184       } else if (AI)
04185         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
04186                               true, 0, dl, SDNodeOrder);
04187       else {
04188         // Can't do anything with other non-AI cases yet.
04189         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04190         DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
04191         DEBUG(Address->dump());
04192         return nullptr;
04193       }
04194       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
04195     } else {
04196       // If Address is an argument then try to emit its dbg value using
04197       // virtual register info from the FuncInfo.ValueMap.
04198       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
04199                                     N)) {
04200         // If variable is pinned by a alloca in dominating bb then
04201         // use StaticAllocaMap.
04202         if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
04203           if (AI->getParent() != DI.getParent()) {
04204             DenseMap<const AllocaInst*, int>::iterator SI =
04205               FuncInfo.StaticAllocaMap.find(AI);
04206             if (SI != FuncInfo.StaticAllocaMap.end()) {
04207               SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
04208                                               0, dl, SDNodeOrder);
04209               DAG.AddDbgValue(SDV, nullptr, false);
04210               return nullptr;
04211             }
04212           }
04213         }
04214         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04215       }
04216     }
04217     return nullptr;
04218   }
04219   case Intrinsic::dbg_value: {
04220     const DbgValueInst &DI = cast<DbgValueInst>(I);
04221     assert(DI.getVariable() && "Missing variable");
04222 
04223     DILocalVariable *Variable = DI.getVariable();
04224     DIExpression *Expression = DI.getExpression();
04225     uint64_t Offset = DI.getOffset();
04226     const Value *V = DI.getValue();
04227     if (!V)
04228       return nullptr;
04229 
04230     SDDbgValue *SDV;
04231     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
04232       SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
04233                                     SDNodeOrder);
04234       DAG.AddDbgValue(SDV, nullptr, false);
04235     } else {
04236       // Do not use getValue() in here; we don't want to generate code at
04237       // this point if it hasn't been done yet.
04238       SDValue N = NodeMap[V];
04239       if (!N.getNode() && isa<Argument>(V))
04240         // Check unused arguments map.
04241         N = UnusedArgNodeMap[V];
04242       if (N.getNode()) {
04243         // A dbg.value for an alloca is always indirect.
04244         bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
04245         if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
04246                                       IsIndirect, N)) {
04247           SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
04248                                 IsIndirect, Offset, dl, SDNodeOrder);
04249           DAG.AddDbgValue(SDV, N.getNode(), false);
04250         }
04251       } else if (!V->use_empty() ) {
04252         // Do not call getValue(V) yet, as we don't want to generate code.
04253         // Remember it for later.
04254         DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
04255         DanglingDebugInfoMap[V] = DDI;
04256       } else {
04257         // We may expand this to cover more cases.  One case where we have no
04258         // data available is an unreferenced parameter.
04259         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04260       }
04261     }
04262 
04263     // Build a debug info table entry.
04264     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
04265       V = BCI->getOperand(0);
04266     const AllocaInst *AI = dyn_cast<AllocaInst>(V);
04267     // Don't handle byval struct arguments or VLAs, for example.
04268     if (!AI) {
04269       DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
04270       DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
04271       return nullptr;
04272     }
04273     DenseMap<const AllocaInst*, int>::iterator SI =
04274       FuncInfo.StaticAllocaMap.find(AI);
04275     if (SI == FuncInfo.StaticAllocaMap.end())
04276       return nullptr; // VLAs.
04277     return nullptr;
04278   }
04279 
04280   case Intrinsic::eh_typeid_for: {
04281     // Find the type id for the given typeinfo.
04282     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
04283     unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
04284     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
04285     setValue(&I, Res);
04286     return nullptr;
04287   }
04288 
04289   case Intrinsic::eh_return_i32:
04290   case Intrinsic::eh_return_i64:
04291     DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
04292     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
04293                             MVT::Other,
04294                             getControlRoot(),
04295                             getValue(I.getArgOperand(0)),
04296                             getValue(I.getArgOperand(1))));
04297     return nullptr;
04298   case Intrinsic::eh_unwind_init:
04299     DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
04300     return nullptr;
04301   case Intrinsic::eh_dwarf_cfa: {
04302     SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
04303                                         TLI.getPointerTy());
04304     SDValue Offset = DAG.getNode(ISD::ADD, sdl,
04305                                  CfaArg.getValueType(),
04306                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
04307                                              CfaArg.getValueType()),
04308                                  CfaArg);
04309     SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
04310                              DAG.getConstant(0, sdl, TLI.getPointerTy()));
04311     setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
04312                              FA, Offset));
04313     return nullptr;
04314   }
04315   case Intrinsic::eh_sjlj_callsite: {
04316     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
04317     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
04318     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
04319     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
04320 
04321     MMI.setCurrentCallSite(CI->getZExtValue());
04322     return nullptr;
04323   }
04324   case Intrinsic::eh_sjlj_functioncontext: {
04325     // Get and store the index of the function context.
04326     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
04327     AllocaInst *FnCtx =
04328       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
04329     int FI = FuncInfo.StaticAllocaMap[FnCtx];
04330     MFI->setFunctionContextIndex(FI);
04331     return nullptr;
04332   }
04333   case Intrinsic::eh_sjlj_setjmp: {
04334     SDValue Ops[2];
04335     Ops[0] = getRoot();
04336     Ops[1] = getValue(I.getArgOperand(0));
04337     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
04338                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
04339     setValue(&I, Op.getValue(0));
04340     DAG.setRoot(Op.getValue(1));
04341     return nullptr;
04342   }
04343   case Intrinsic::eh_sjlj_longjmp: {
04344     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
04345                             getRoot(), getValue(I.getArgOperand(0))));
04346     return nullptr;
04347   }
04348 
04349   case Intrinsic::masked_gather:
04350     visitMaskedGather(I);
04351     return nullptr;
04352   case Intrinsic::masked_load:
04353     visitMaskedLoad(I);
04354     return nullptr;
04355   case Intrinsic::masked_scatter:
04356     visitMaskedScatter(I);
04357     return nullptr;
04358   case Intrinsic::masked_store:
04359     visitMaskedStore(I);
04360     return nullptr;
04361   case Intrinsic::x86_mmx_pslli_w:
04362   case Intrinsic::x86_mmx_pslli_d:
04363   case Intrinsic::x86_mmx_pslli_q:
04364   case Intrinsic::x86_mmx_psrli_w:
04365   case Intrinsic::x86_mmx_psrli_d:
04366   case Intrinsic::x86_mmx_psrli_q:
04367   case Intrinsic::x86_mmx_psrai_w:
04368   case Intrinsic::x86_mmx_psrai_d: {
04369     SDValue ShAmt = getValue(I.getArgOperand(1));
04370     if (isa<ConstantSDNode>(ShAmt)) {
04371       visitTargetIntrinsic(I, Intrinsic);
04372       return nullptr;
04373     }
04374     unsigned NewIntrinsic = 0;
04375     EVT ShAmtVT = MVT::v2i32;
04376     switch (Intrinsic) {
04377     case Intrinsic::x86_mmx_pslli_w:
04378       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
04379       break;
04380     case Intrinsic::x86_mmx_pslli_d:
04381       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
04382       break;
04383     case Intrinsic::x86_mmx_pslli_q:
04384       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
04385       break;
04386     case Intrinsic::x86_mmx_psrli_w:
04387       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
04388       break;
04389     case Intrinsic::x86_mmx_psrli_d:
04390       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
04391       break;
04392     case Intrinsic::x86_mmx_psrli_q:
04393       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
04394       break;
04395     case Intrinsic::x86_mmx_psrai_w:
04396       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
04397       break;
04398     case Intrinsic::x86_mmx_psrai_d:
04399       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
04400       break;
04401     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
04402     }
04403 
04404     // The vector shift intrinsics with scalars uses 32b shift amounts but
04405     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
04406     // to be zero.
04407     // We must do this early because v2i32 is not a legal type.
04408     SDValue ShOps[2];
04409     ShOps[0] = ShAmt;
04410     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
04411     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
04412     EVT DestVT = TLI.getValueType(I.getType());
04413     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
04414     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
04415                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
04416                        getValue(I.getArgOperand(0)), ShAmt);
04417     setValue(&I, Res);
04418     return nullptr;
04419   }
04420   case Intrinsic::convertff:
04421   case Intrinsic::convertfsi:
04422   case Intrinsic::convertfui:
04423   case Intrinsic::convertsif:
04424   case Intrinsic::convertuif:
04425   case Intrinsic::convertss:
04426   case Intrinsic::convertsu:
04427   case Intrinsic::convertus:
04428   case Intrinsic::convertuu: {
04429     ISD::CvtCode Code = ISD::CVT_INVALID;
04430     switch (Intrinsic) {
04431     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
04432     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
04433     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
04434     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
04435     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
04436     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
04437     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
04438     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
04439     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
04440     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
04441     }
04442     EVT DestVT = TLI.getValueType(I.getType());
04443     const Value *Op1 = I.getArgOperand(0);
04444     Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
04445                                DAG.getValueType(DestVT),
04446                                DAG.getValueType(getValue(Op1).getValueType()),
04447                                getValue(I.getArgOperand(1)),
04448                                getValue(I.getArgOperand(2)),
04449                                Code);
04450     setValue(&I, Res);
04451     return nullptr;
04452   }
04453   case Intrinsic::powi:
04454     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
04455                             getValue(I.getArgOperand(1)), DAG));
04456     return nullptr;
04457   case Intrinsic::log:
04458     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
04459     return nullptr;
04460   case Intrinsic::log2:
04461     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
04462     return nullptr;
04463   case Intrinsic::log10:
04464     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
04465     return nullptr;
04466   case Intrinsic::exp:
04467     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
04468     return nullptr;
04469   case Intrinsic::exp2:
04470     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
04471     return nullptr;
04472   case Intrinsic::pow:
04473     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
04474                            getValue(I.getArgOperand(1)), DAG, TLI));
04475     return nullptr;
04476   case Intrinsic::sqrt:
04477   case Intrinsic::fabs:
04478   case Intrinsic::sin:
04479   case Intrinsic::cos:
04480   case Intrinsic::floor:
04481   case Intrinsic::ceil:
04482   case Intrinsic::trunc:
04483   case Intrinsic::rint:
04484   case Intrinsic::nearbyint:
04485   case Intrinsic::round: {
04486     unsigned Opcode;
04487     switch (Intrinsic) {
04488     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
04489     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
04490     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
04491     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
04492     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
04493     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
04494     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
04495     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
04496     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
04497     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
04498     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
04499     }
04500 
04501     setValue(&I, DAG.getNode(Opcode, sdl,
04502                              getValue(I.getArgOperand(0)).getValueType(),
04503                              getValue(I.getArgOperand(0))));
04504     return nullptr;
04505   }
04506   case Intrinsic::minnum:
04507     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
04508                              getValue(I.getArgOperand(0)).getValueType(),
04509                              getValue(I.getArgOperand(0)),
04510                              getValue(I.getArgOperand(1))));
04511     return nullptr;
04512   case Intrinsic::maxnum:
04513     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
04514                              getValue(I.getArgOperand(0)).getValueType(),
04515                              getValue(I.getArgOperand(0)),
04516                              getValue(I.getArgOperand(1))));
04517     return nullptr;
04518   case Intrinsic::copysign:
04519     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
04520                              getValue(I.getArgOperand(0)).getValueType(),
04521                              getValue(I.getArgOperand(0)),
04522                              getValue(I.getArgOperand(1))));
04523     return nullptr;
04524   case Intrinsic::fma:
04525     setValue(&I, DAG.getNode(ISD::FMA, sdl,
04526                              getValue(I.getArgOperand(0)).getValueType(),
04527                              getValue(I.getArgOperand(0)),
04528                              getValue(I.getArgOperand(1)),
04529                              getValue(I.getArgOperand(2))));
04530     return nullptr;
04531   case Intrinsic::fmuladd: {
04532     EVT VT = TLI.getValueType(I.getType());
04533     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
04534         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
04535       setValue(&I, DAG.getNode(ISD::FMA, sdl,
04536                                getValue(I.getArgOperand(0)).getValueType(),
04537                                getValue(I.getArgOperand(0)),
04538                                getValue(I.getArgOperand(1)),
04539                                getValue(I.getArgOperand(2))));
04540     } else {
04541       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
04542                                 getValue(I.getArgOperand(0)).getValueType(),
04543                                 getValue(I.getArgOperand(0)),
04544                                 getValue(I.getArgOperand(1)));
04545       SDValue Add = DAG.getNode(ISD::FADD, sdl,
04546                                 getValue(I.getArgOperand(0)).getValueType(),
04547                                 Mul,
04548                                 getValue(I.getArgOperand(2)));
04549       setValue(&I, Add);
04550     }
04551     return nullptr;
04552   }
04553   case Intrinsic::convert_to_fp16:
04554     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
04555                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
04556                                          getValue(I.getArgOperand(0)),
04557                                          DAG.getTargetConstant(0, sdl,
04558                                                                MVT::i32))));
04559     return nullptr;
04560   case Intrinsic::convert_from_fp16:
04561     setValue(&I,
04562              DAG.getNode(ISD::FP_EXTEND, sdl, TLI.getValueType(I.getType()),
04563                          DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
04564                                      getValue(I.getArgOperand(0)))));
04565     return nullptr;
04566   case Intrinsic::pcmarker: {
04567     SDValue Tmp = getValue(I.getArgOperand(0));
04568     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
04569     return nullptr;
04570   }
04571   case Intrinsic::readcyclecounter: {
04572     SDValue Op = getRoot();
04573     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
04574                       DAG.getVTList(MVT::i64, MVT::Other), Op);
04575     setValue(&I, Res);
04576     DAG.setRoot(Res.getValue(1));
04577     return nullptr;
04578   }
04579   case Intrinsic::bswap:
04580     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
04581                              getValue(I.getArgOperand(0)).getValueType(),
04582                              getValue(I.getArgOperand(0))));
04583     return nullptr;
04584   case Intrinsic::cttz: {
04585     SDValue Arg = getValue(I.getArgOperand(0));
04586     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
04587     EVT Ty = Arg.getValueType();
04588     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
04589                              sdl, Ty, Arg));
04590     return nullptr;
04591   }
04592   case Intrinsic::ctlz: {
04593     SDValue Arg = getValue(I.getArgOperand(0));
04594     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
04595     EVT Ty = Arg.getValueType();
04596     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
04597                              sdl, Ty, Arg));
04598     return nullptr;
04599   }
04600   case Intrinsic::ctpop: {
04601     SDValue Arg = getValue(I.getArgOperand(0));
04602     EVT Ty = Arg.getValueType();
04603     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
04604     return nullptr;
04605   }
04606   case Intrinsic::stacksave: {
04607     SDValue Op = getRoot();
04608     Res = DAG.getNode(ISD::STACKSAVE, sdl,
04609                       DAG.getVTList(TLI.getPointerTy(), MVT::Other), Op);
04610     setValue(&I, Res);
04611     DAG.setRoot(Res.getValue(1));
04612     return nullptr;
04613   }
04614   case Intrinsic::stackrestore: {
04615     Res = getValue(I.getArgOperand(0));
04616     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
04617     return nullptr;
04618   }
04619   case Intrinsic::stackprotector: {
04620     // Emit code into the DAG to store the stack guard onto the stack.
04621     MachineFunction &MF = DAG.getMachineFunction();
04622     MachineFrameInfo *MFI = MF.getFrameInfo();
04623     EVT PtrTy = TLI.getPointerTy();
04624     SDValue Src, Chain = getRoot();
04625     const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
04626     const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
04627 
04628     // See if Ptr is a bitcast. If it is, look through it and see if we can get
04629     // global variable __stack_chk_guard.
04630     if (!GV)
04631       if (const Operator *BC = dyn_cast<Operator>(Ptr))
04632         if (BC->getOpcode() == Instruction::BitCast)
04633           GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
04634 
04635     if (GV && TLI.useLoadStackGuardNode()) {
04636       // Emit a LOAD_STACK_GUARD node.
04637       MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
04638                                                sdl, PtrTy, Chain);
04639       MachinePointerInfo MPInfo(GV);
04640       MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
04641       unsigned Flags = MachineMemOperand::MOLoad |
04642                        MachineMemOperand::MOInvariant;
04643       *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
04644                                          PtrTy.getSizeInBits() / 8,
04645                                          DAG.getEVTAlignment(PtrTy));
04646       Node->setMemRefs(MemRefs, MemRefs + 1);
04647 
04648       // Copy the guard value to a virtual register so that it can be
04649       // retrieved in the epilogue.
04650       Src = SDValue(Node, 0);
04651       const TargetRegisterClass *RC =
04652           TLI.getRegClassFor(Src.getSimpleValueType());
04653       unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
04654 
04655       SPDescriptor.setGuardReg(Reg);
04656       Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
04657     } else {
04658       Src = getValue(I.getArgOperand(0));   // The guard's value.
04659     }
04660 
04661     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
04662 
04663     int FI = FuncInfo.StaticAllocaMap[Slot];
04664     MFI->setStackProtectorIndex(FI);
04665 
04666     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
04667 
04668     // Store the stack protector onto the stack.
04669     Res = DAG.getStore(Chain, sdl, Src, FIN,
04670                        MachinePointerInfo::getFixedStack(FI),
04671                        true, false, 0);
04672     setValue(&I, Res);
04673     DAG.setRoot(Res);
04674     return nullptr;
04675   }
04676   case Intrinsic::objectsize: {
04677     // If we don't know by now, we're never going to know.
04678     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
04679 
04680     assert(CI && "Non-constant type in __builtin_object_size?");
04681 
04682     SDValue Arg = getValue(I.getCalledValue());
04683     EVT Ty = Arg.getValueType();
04684 
04685     if (CI->isZero())
04686       Res = DAG.getConstant(-1ULL, sdl, Ty);
04687     else
04688       Res = DAG.getConstant(0, sdl, Ty);
04689 
04690     setValue(&I, Res);
04691     return nullptr;
04692   }
04693   case Intrinsic::annotation:
04694   case Intrinsic::ptr_annotation:
04695     // Drop the intrinsic, but forward the value
04696     setValue(&I, getValue(I.getOperand(0)));
04697     return nullptr;
04698   case Intrinsic::assume:
04699   case Intrinsic::var_annotation:
04700     // Discard annotate attributes and assumptions
04701     return nullptr;
04702 
04703   case Intrinsic::init_trampoline: {
04704     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
04705 
04706     SDValue Ops[6];
04707     Ops[0] = getRoot();
04708     Ops[1] = getValue(I.getArgOperand(0));
04709     Ops[2] = getValue(I.getArgOperand(1));
04710     Ops[3] = getValue(I.getArgOperand(2));
04711     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
04712     Ops[5] = DAG.getSrcValue(F);
04713 
04714     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
04715 
04716     DAG.setRoot(Res);
04717     return nullptr;
04718   }
04719   case Intrinsic::adjust_trampoline: {
04720     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
04721                              TLI.getPointerTy(),
04722                              getValue(I.getArgOperand(0))));
04723     return nullptr;
04724   }
04725   case Intrinsic::gcroot:
04726     if (GFI) {
04727       const Value *Alloca = I.getArgOperand(0)->stripPointer