LLVM API Documentation

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 #define DEBUG_TYPE "isel"
00015 #include "SelectionDAGBuilder.h"
00016 #include "SDNodeDbgValue.h"
00017 #include "llvm/ADT/BitVector.h"
00018 #include "llvm/ADT/Optional.h"
00019 #include "llvm/ADT/SmallSet.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/Analysis/BranchProbabilityInfo.h"
00022 #include "llvm/Analysis/ConstantFolding.h"
00023 #include "llvm/Analysis/ValueTracking.h"
00024 #include "llvm/CodeGen/Analysis.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/IR/CallingConv.h"
00038 #include "llvm/IR/Constants.h"
00039 #include "llvm/IR/DataLayout.h"
00040 #include "llvm/IR/DebugInfo.h"
00041 #include "llvm/IR/DerivedTypes.h"
00042 #include "llvm/IR/Function.h"
00043 #include "llvm/IR/GlobalVariable.h"
00044 #include "llvm/IR/InlineAsm.h"
00045 #include "llvm/IR/Instructions.h"
00046 #include "llvm/IR/IntrinsicInst.h"
00047 #include "llvm/IR/Intrinsics.h"
00048 #include "llvm/IR/LLVMContext.h"
00049 #include "llvm/IR/Module.h"
00050 #include "llvm/Support/CommandLine.h"
00051 #include "llvm/Support/Debug.h"
00052 #include "llvm/Support/ErrorHandling.h"
00053 #include "llvm/Support/MathExtras.h"
00054 #include "llvm/Support/raw_ostream.h"
00055 #include "llvm/Target/TargetFrameLowering.h"
00056 #include "llvm/Target/TargetInstrInfo.h"
00057 #include "llvm/Target/TargetIntrinsicInfo.h"
00058 #include "llvm/Target/TargetLibraryInfo.h"
00059 #include "llvm/Target/TargetLowering.h"
00060 #include "llvm/Target/TargetOptions.h"
00061 #include "llvm/Target/TargetSelectionDAGInfo.h"
00062 #include <algorithm>
00063 using namespace llvm;
00064 
00065 /// LimitFloatPrecision - Generate low-precision inline sequences for
00066 /// some float libcalls (6, 8 or 12 bits).
00067 static unsigned LimitFloatPrecision;
00068 
00069 static cl::opt<unsigned, true>
00070 LimitFPPrecision("limit-float-precision",
00071                  cl::desc("Generate low-precision inline sequences "
00072                           "for some float libcalls"),
00073                  cl::location(LimitFloatPrecision),
00074                  cl::init(0));
00075 
00076 // Limit the width of DAG chains. This is important in general to prevent
00077 // prevent DAG-based analysis from blowing up. For example, alias analysis and
00078 // load clustering may not complete in reasonable time. It is difficult to
00079 // recognize and avoid this situation within each individual analysis, and
00080 // future analyses are likely to have the same behavior. Limiting DAG width is
00081 // the safe approach, and will be especially important with global DAGs.
00082 //
00083 // MaxParallelChains default is arbitrarily high to avoid affecting
00084 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
00085 // sequence over this should have been converted to llvm.memcpy by the
00086 // frontend. It easy to induce this behavior with .ll code such as:
00087 // %buffer = alloca [4096 x i8]
00088 // %data = load [4096 x i8]* %argPtr
00089 // store [4096 x i8] %data, [4096 x i8]* %buffer
00090 static const unsigned MaxParallelChains = 64;
00091 
00092 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
00093                                       const SDValue *Parts, unsigned NumParts,
00094                                       MVT PartVT, EVT ValueVT, const Value *V);
00095 
00096 /// getCopyFromParts - Create a value that contains the specified legal parts
00097 /// combined into the value they represent.  If the parts combine to a type
00098 /// larger then ValueVT then AssertOp can be used to specify whether the extra
00099 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
00100 /// (ISD::AssertSext).
00101 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
00102                                 const SDValue *Parts,
00103                                 unsigned NumParts, MVT PartVT, EVT ValueVT,
00104                                 const Value *V,
00105                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
00106   if (ValueVT.isVector())
00107     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
00108                                   PartVT, ValueVT, V);
00109 
00110   assert(NumParts > 0 && "No parts to assemble!");
00111   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00112   SDValue Val = Parts[0];
00113 
00114   if (NumParts > 1) {
00115     // Assemble the value from multiple parts.
00116     if (ValueVT.isInteger()) {
00117       unsigned PartBits = PartVT.getSizeInBits();
00118       unsigned ValueBits = ValueVT.getSizeInBits();
00119 
00120       // Assemble the power of 2 part.
00121       unsigned RoundParts = NumParts & (NumParts - 1) ?
00122         1 << Log2_32(NumParts) : NumParts;
00123       unsigned RoundBits = PartBits * RoundParts;
00124       EVT RoundVT = RoundBits == ValueBits ?
00125         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
00126       SDValue Lo, Hi;
00127 
00128       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
00129 
00130       if (RoundParts > 2) {
00131         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
00132                               PartVT, HalfVT, V);
00133         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
00134                               RoundParts / 2, PartVT, HalfVT, V);
00135       } else {
00136         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
00137         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
00138       }
00139 
00140       if (TLI.isBigEndian())
00141         std::swap(Lo, Hi);
00142 
00143       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
00144 
00145       if (RoundParts < NumParts) {
00146         // Assemble the trailing non-power-of-2 part.
00147         unsigned OddParts = NumParts - RoundParts;
00148         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
00149         Hi = getCopyFromParts(DAG, DL,
00150                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
00151 
00152         // Combine the round and odd parts.
00153         Lo = Val;
00154         if (TLI.isBigEndian())
00155           std::swap(Lo, Hi);
00156         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00157         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
00158         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
00159                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
00160                                          TLI.getPointerTy()));
00161         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
00162         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
00163       }
00164     } else if (PartVT.isFloatingPoint()) {
00165       // FP split into multiple FP parts (for ppcf128)
00166       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
00167              "Unexpected split");
00168       SDValue Lo, Hi;
00169       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
00170       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
00171       if (TLI.isBigEndian())
00172         std::swap(Lo, Hi);
00173       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
00174     } else {
00175       // FP split into integer parts (soft fp)
00176       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
00177              !PartVT.isVector() && "Unexpected split");
00178       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
00179       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
00180     }
00181   }
00182 
00183   // There is now one part, held in Val.  Correct it to match ValueVT.
00184   EVT PartEVT = Val.getValueType();
00185 
00186   if (PartEVT == ValueVT)
00187     return Val;
00188 
00189   if (PartEVT.isInteger() && ValueVT.isInteger()) {
00190     if (ValueVT.bitsLT(PartEVT)) {
00191       // For a truncate, see if we have any information to
00192       // indicate whether the truncated bits will always be
00193       // zero or sign-extension.
00194       if (AssertOp != ISD::DELETED_NODE)
00195         Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
00196                           DAG.getValueType(ValueVT));
00197       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
00198     }
00199     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
00200   }
00201 
00202   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
00203     // FP_ROUND's are always exact here.
00204     if (ValueVT.bitsLT(Val.getValueType()))
00205       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
00206                          DAG.getTargetConstant(1, TLI.getPointerTy()));
00207 
00208     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
00209   }
00210 
00211   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
00212     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
00213 
00214   llvm_unreachable("Unknown mismatch!");
00215 }
00216 
00217 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
00218                                               const Twine &ErrMsg) {
00219   const Instruction *I = dyn_cast_or_null<Instruction>(V);
00220   if (!V)
00221     return Ctx.emitError(ErrMsg);
00222 
00223   const char *AsmError = ", possible invalid constraint for vector type";
00224   if (const CallInst *CI = dyn_cast<CallInst>(I))
00225     if (isa<InlineAsm>(CI->getCalledValue()))
00226       return Ctx.emitError(I, ErrMsg + AsmError);
00227 
00228   return Ctx.emitError(I, ErrMsg);
00229 }
00230 
00231 /// getCopyFromPartsVector - Create a value that contains the specified legal
00232 /// parts combined into the value they represent.  If the parts combine to a
00233 /// type larger then ValueVT then AssertOp can be used to specify whether the
00234 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
00235 /// ValueVT (ISD::AssertSext).
00236 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
00237                                       const SDValue *Parts, unsigned NumParts,
00238                                       MVT PartVT, EVT ValueVT, const Value *V) {
00239   assert(ValueVT.isVector() && "Not a vector value");
00240   assert(NumParts > 0 && "No parts to assemble!");
00241   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00242   SDValue Val = Parts[0];
00243 
00244   // Handle a multi-element vector.
00245   if (NumParts > 1) {
00246     EVT IntermediateVT;
00247     MVT RegisterVT;
00248     unsigned NumIntermediates;
00249     unsigned NumRegs =
00250     TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
00251                                NumIntermediates, RegisterVT);
00252     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
00253     NumParts = NumRegs; // Silence a compiler warning.
00254     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
00255     assert(RegisterVT == Parts[0].getSimpleValueType() &&
00256            "Part type doesn't match part!");
00257 
00258     // Assemble the parts into intermediate operands.
00259     SmallVector<SDValue, 8> Ops(NumIntermediates);
00260     if (NumIntermediates == NumParts) {
00261       // If the register was not expanded, truncate or copy the value,
00262       // as appropriate.
00263       for (unsigned i = 0; i != NumParts; ++i)
00264         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
00265                                   PartVT, IntermediateVT, V);
00266     } else if (NumParts > 0) {
00267       // If the intermediate type was expanded, build the intermediate
00268       // operands from the parts.
00269       assert(NumParts % NumIntermediates == 0 &&
00270              "Must expand into a divisible number of parts!");
00271       unsigned Factor = NumParts / NumIntermediates;
00272       for (unsigned i = 0; i != NumIntermediates; ++i)
00273         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
00274                                   PartVT, IntermediateVT, V);
00275     }
00276 
00277     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
00278     // intermediate operands.
00279     Val = DAG.getNode(IntermediateVT.isVector() ?
00280                       ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
00281                       ValueVT, &Ops[0], NumIntermediates);
00282   }
00283 
00284   // There is now one part, held in Val.  Correct it to match ValueVT.
00285   EVT PartEVT = Val.getValueType();
00286 
00287   if (PartEVT == ValueVT)
00288     return Val;
00289 
00290   if (PartEVT.isVector()) {
00291     // If the element type of the source/dest vectors are the same, but the
00292     // parts vector has more elements than the value vector, then we have a
00293     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
00294     // elements we want.
00295     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
00296       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
00297              "Cannot narrow, it would be a lossy transformation");
00298       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
00299                          DAG.getConstant(0, TLI.getVectorIdxTy()));
00300     }
00301 
00302     // Vector/Vector bitcast.
00303     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
00304       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
00305 
00306     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
00307       "Cannot handle this kind of promotion");
00308     // Promoted vector extract
00309     bool Smaller = ValueVT.bitsLE(PartEVT);
00310     return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00311                        DL, ValueVT, Val);
00312 
00313   }
00314 
00315   // Trivial bitcast if the types are the same size and the destination
00316   // vector type is legal.
00317   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
00318       TLI.isTypeLegal(ValueVT))
00319     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
00320 
00321   // Handle cases such as i8 -> <1 x i1>
00322   if (ValueVT.getVectorNumElements() != 1) {
00323     diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
00324                                       "non-trivial scalar-to-vector conversion");
00325     return DAG.getUNDEF(ValueVT);
00326   }
00327 
00328   if (ValueVT.getVectorNumElements() == 1 &&
00329       ValueVT.getVectorElementType() != PartEVT) {
00330     bool Smaller = ValueVT.bitsLE(PartEVT);
00331     Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00332                        DL, ValueVT.getScalarType(), Val);
00333   }
00334 
00335   return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
00336 }
00337 
00338 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
00339                                  SDValue Val, SDValue *Parts, unsigned NumParts,
00340                                  MVT PartVT, const Value *V);
00341 
00342 /// getCopyToParts - Create a series of nodes that contain the specified value
00343 /// split into legal parts.  If the parts contain more bits than Val, then, for
00344 /// integers, ExtendKind can be used to specify how to generate the extra bits.
00345 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
00346                            SDValue Val, SDValue *Parts, unsigned NumParts,
00347                            MVT PartVT, const Value *V,
00348                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
00349   EVT ValueVT = Val.getValueType();
00350 
00351   // Handle the vector case separately.
00352   if (ValueVT.isVector())
00353     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
00354 
00355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00356   unsigned PartBits = PartVT.getSizeInBits();
00357   unsigned OrigNumParts = NumParts;
00358   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
00359 
00360   if (NumParts == 0)
00361     return;
00362 
00363   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
00364   EVT PartEVT = PartVT;
00365   if (PartEVT == ValueVT) {
00366     assert(NumParts == 1 && "No-op copy with multiple parts!");
00367     Parts[0] = Val;
00368     return;
00369   }
00370 
00371   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
00372     // If the parts cover more bits than the value has, promote the value.
00373     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
00374       assert(NumParts == 1 && "Do not know what to promote to!");
00375       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
00376     } else {
00377       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
00378              ValueVT.isInteger() &&
00379              "Unknown mismatch!");
00380       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00381       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
00382       if (PartVT == MVT::x86mmx)
00383         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00384     }
00385   } else if (PartBits == ValueVT.getSizeInBits()) {
00386     // Different types of the same size.
00387     assert(NumParts == 1 && PartEVT != ValueVT);
00388     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00389   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
00390     // If the parts cover less bits than value has, truncate the value.
00391     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
00392            ValueVT.isInteger() &&
00393            "Unknown mismatch!");
00394     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00395     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
00396     if (PartVT == MVT::x86mmx)
00397       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00398   }
00399 
00400   // The value may have changed - recompute ValueVT.
00401   ValueVT = Val.getValueType();
00402   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
00403          "Failed to tile the value with PartVT!");
00404 
00405   if (NumParts == 1) {
00406     if (PartEVT != ValueVT)
00407       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
00408                                         "scalar-to-vector conversion failed");
00409 
00410     Parts[0] = Val;
00411     return;
00412   }
00413 
00414   // Expand the value into multiple parts.
00415   if (NumParts & (NumParts - 1)) {
00416     // The number of parts is not a power of 2.  Split off and copy the tail.
00417     assert(PartVT.isInteger() && ValueVT.isInteger() &&
00418            "Do not know what to expand to!");
00419     unsigned RoundParts = 1 << Log2_32(NumParts);
00420     unsigned RoundBits = RoundParts * PartBits;
00421     unsigned OddParts = NumParts - RoundParts;
00422     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
00423                                  DAG.getIntPtrConstant(RoundBits));
00424     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
00425 
00426     if (TLI.isBigEndian())
00427       // The odd parts were reversed by getCopyToParts - unreverse them.
00428       std::reverse(Parts + RoundParts, Parts + NumParts);
00429 
00430     NumParts = RoundParts;
00431     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
00432     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
00433   }
00434 
00435   // The number of parts is a power of 2.  Repeatedly bisect the value using
00436   // EXTRACT_ELEMENT.
00437   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
00438                          EVT::getIntegerVT(*DAG.getContext(),
00439                                            ValueVT.getSizeInBits()),
00440                          Val);
00441 
00442   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
00443     for (unsigned i = 0; i < NumParts; i += StepSize) {
00444       unsigned ThisBits = StepSize * PartBits / 2;
00445       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
00446       SDValue &Part0 = Parts[i];
00447       SDValue &Part1 = Parts[i+StepSize/2];
00448 
00449       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
00450                           ThisVT, Part0, DAG.getIntPtrConstant(1));
00451       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
00452                           ThisVT, Part0, DAG.getIntPtrConstant(0));
00453 
00454       if (ThisBits == PartBits && ThisVT != PartVT) {
00455         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
00456         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
00457       }
00458     }
00459   }
00460 
00461   if (TLI.isBigEndian())
00462     std::reverse(Parts, Parts + OrigNumParts);
00463 }
00464 
00465 
00466 /// getCopyToPartsVector - Create a series of nodes that contain the specified
00467 /// value split into legal parts.
00468 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
00469                                  SDValue Val, SDValue *Parts, unsigned NumParts,
00470                                  MVT PartVT, const Value *V) {
00471   EVT ValueVT = Val.getValueType();
00472   assert(ValueVT.isVector() && "Not a vector");
00473   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00474 
00475   if (NumParts == 1) {
00476     EVT PartEVT = PartVT;
00477     if (PartEVT == ValueVT) {
00478       // Nothing to do.
00479     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
00480       // Bitconvert vector->vector case.
00481       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
00482     } else if (PartVT.isVector() &&
00483                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
00484                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
00485       EVT ElementVT = PartVT.getVectorElementType();
00486       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
00487       // undef elements.
00488       SmallVector<SDValue, 16> Ops;
00489       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
00490         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
00491                                   ElementVT, Val, DAG.getConstant(i,
00492                                                   TLI.getVectorIdxTy())));
00493 
00494       for (unsigned i = ValueVT.getVectorNumElements(),
00495            e = PartVT.getVectorNumElements(); i != e; ++i)
00496         Ops.push_back(DAG.getUNDEF(ElementVT));
00497 
00498       Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
00499 
00500       // FIXME: Use CONCAT for 2x -> 4x.
00501 
00502       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
00503       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
00504     } else if (PartVT.isVector() &&
00505                PartEVT.getVectorElementType().bitsGE(
00506                  ValueVT.getVectorElementType()) &&
00507                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
00508 
00509       // Promoted vector extract
00510       bool Smaller = PartEVT.bitsLE(ValueVT);
00511       Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00512                         DL, PartVT, Val);
00513     } else{
00514       // Vector -> scalar conversion.
00515       assert(ValueVT.getVectorNumElements() == 1 &&
00516              "Only trivial vector-to-scalar conversions should get here!");
00517       Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
00518                         PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
00519 
00520       bool Smaller = ValueVT.bitsLE(PartVT);
00521       Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
00522                          DL, PartVT, Val);
00523     }
00524 
00525     Parts[0] = Val;
00526     return;
00527   }
00528 
00529   // Handle a multi-element vector.
00530   EVT IntermediateVT;
00531   MVT RegisterVT;
00532   unsigned NumIntermediates;
00533   unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
00534                                                 IntermediateVT,
00535                                                 NumIntermediates, RegisterVT);
00536   unsigned NumElements = ValueVT.getVectorNumElements();
00537 
00538   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
00539   NumParts = NumRegs; // Silence a compiler warning.
00540   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
00541 
00542   // Split the vector into intermediate operands.
00543   SmallVector<SDValue, 8> Ops(NumIntermediates);
00544   for (unsigned i = 0; i != NumIntermediates; ++i) {
00545     if (IntermediateVT.isVector())
00546       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
00547                            IntermediateVT, Val,
00548                    DAG.getConstant(i * (NumElements / NumIntermediates),
00549                                    TLI.getVectorIdxTy()));
00550     else
00551       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
00552                            IntermediateVT, Val,
00553                            DAG.getConstant(i, TLI.getVectorIdxTy()));
00554   }
00555 
00556   // Split the intermediate operands into legal parts.
00557   if (NumParts == NumIntermediates) {
00558     // If the register was not expanded, promote or copy the value,
00559     // as appropriate.
00560     for (unsigned i = 0; i != NumParts; ++i)
00561       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
00562   } else if (NumParts > 0) {
00563     // If the intermediate type was expanded, split each the value into
00564     // legal parts.
00565     assert(NumParts % NumIntermediates == 0 &&
00566            "Must expand into a divisible number of parts!");
00567     unsigned Factor = NumParts / NumIntermediates;
00568     for (unsigned i = 0; i != NumIntermediates; ++i)
00569       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
00570   }
00571 }
00572 
00573 namespace {
00574   /// RegsForValue - This struct represents the registers (physical or virtual)
00575   /// that a particular set of values is assigned, and the type information
00576   /// about the value. The most common situation is to represent one value at a
00577   /// time, but struct or array values are handled element-wise as multiple
00578   /// values.  The splitting of aggregates is performed recursively, so that we
00579   /// never have aggregate-typed registers. The values at this point do not
00580   /// necessarily have legal types, so each value may require one or more
00581   /// registers of some legal type.
00582   ///
00583   struct RegsForValue {
00584     /// ValueVTs - The value types of the values, which may not be legal, and
00585     /// may need be promoted or synthesized from one or more registers.
00586     ///
00587     SmallVector<EVT, 4> ValueVTs;
00588 
00589     /// RegVTs - The value types of the registers. This is the same size as
00590     /// ValueVTs and it records, for each value, what the type of the assigned
00591     /// register or registers are. (Individual values are never synthesized
00592     /// from more than one type of register.)
00593     ///
00594     /// With virtual registers, the contents of RegVTs is redundant with TLI's
00595     /// getRegisterType member function, however when with physical registers
00596     /// it is necessary to have a separate record of the types.
00597     ///
00598     SmallVector<MVT, 4> RegVTs;
00599 
00600     /// Regs - This list holds the registers assigned to the values.
00601     /// Each legal or promoted value requires one register, and each
00602     /// expanded value requires multiple registers.
00603     ///
00604     SmallVector<unsigned, 4> Regs;
00605 
00606     RegsForValue() {}
00607 
00608     RegsForValue(const SmallVector<unsigned, 4> &regs,
00609                  MVT regvt, EVT valuevt)
00610       : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
00611 
00612     RegsForValue(LLVMContext &Context, const TargetLowering &tli,
00613                  unsigned Reg, Type *Ty) {
00614       ComputeValueVTs(tli, Ty, ValueVTs);
00615 
00616       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
00617         EVT ValueVT = ValueVTs[Value];
00618         unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
00619         MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
00620         for (unsigned i = 0; i != NumRegs; ++i)
00621           Regs.push_back(Reg + i);
00622         RegVTs.push_back(RegisterVT);
00623         Reg += NumRegs;
00624       }
00625     }
00626 
00627     /// append - Add the specified values to this one.
00628     void append(const RegsForValue &RHS) {
00629       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
00630       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
00631       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
00632     }
00633 
00634     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
00635     /// this value and returns the result as a ValueVTs value.  This uses
00636     /// Chain/Flag as the input and updates them for the output Chain/Flag.
00637     /// If the Flag pointer is NULL, no flag is used.
00638     SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
00639                             SDLoc dl,
00640                             SDValue &Chain, SDValue *Flag,
00641                             const Value *V = nullptr) const;
00642 
00643     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
00644     /// specified value into the registers specified by this object.  This uses
00645     /// Chain/Flag as the input and updates them for the output Chain/Flag.
00646     /// If the Flag pointer is NULL, no flag is used.
00647     void getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
00648                        SDValue &Chain, SDValue *Flag, const Value *V) const;
00649 
00650     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
00651     /// operand list.  This adds the code marker, matching input operand index
00652     /// (if applicable), and includes the number of values added into it.
00653     void AddInlineAsmOperands(unsigned Kind,
00654                               bool HasMatching, unsigned MatchingIdx,
00655                               SelectionDAG &DAG,
00656                               std::vector<SDValue> &Ops) const;
00657   };
00658 }
00659 
00660 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
00661 /// this value and returns the result as a ValueVT value.  This uses
00662 /// Chain/Flag as the input and updates them for the output Chain/Flag.
00663 /// If the Flag pointer is NULL, no flag is used.
00664 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
00665                                       FunctionLoweringInfo &FuncInfo,
00666                                       SDLoc dl,
00667                                       SDValue &Chain, SDValue *Flag,
00668                                       const Value *V) const {
00669   // A Value with type {} or [0 x %t] needs no registers.
00670   if (ValueVTs.empty())
00671     return SDValue();
00672 
00673   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00674 
00675   // Assemble the legal parts into the final values.
00676   SmallVector<SDValue, 4> Values(ValueVTs.size());
00677   SmallVector<SDValue, 8> Parts;
00678   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
00679     // Copy the legal parts from the registers.
00680     EVT ValueVT = ValueVTs[Value];
00681     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
00682     MVT RegisterVT = RegVTs[Value];
00683 
00684     Parts.resize(NumRegs);
00685     for (unsigned i = 0; i != NumRegs; ++i) {
00686       SDValue P;
00687       if (!Flag) {
00688         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
00689       } else {
00690         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
00691         *Flag = P.getValue(2);
00692       }
00693 
00694       Chain = P.getValue(1);
00695       Parts[i] = P;
00696 
00697       // If the source register was virtual and if we know something about it,
00698       // add an assert node.
00699       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
00700           !RegisterVT.isInteger() || RegisterVT.isVector())
00701         continue;
00702 
00703       const FunctionLoweringInfo::LiveOutInfo *LOI =
00704         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
00705       if (!LOI)
00706         continue;
00707 
00708       unsigned RegSize = RegisterVT.getSizeInBits();
00709       unsigned NumSignBits = LOI->NumSignBits;
00710       unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
00711 
00712       if (NumZeroBits == RegSize) {
00713         // The current value is a zero.
00714         // Explicitly express that as it would be easier for
00715         // optimizations to kick in.
00716         Parts[i] = DAG.getConstant(0, RegisterVT);
00717         continue;
00718       }
00719 
00720       // FIXME: We capture more information than the dag can represent.  For
00721       // now, just use the tightest assertzext/assertsext possible.
00722       bool isSExt = true;
00723       EVT FromVT(MVT::Other);
00724       if (NumSignBits == RegSize)
00725         isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
00726       else if (NumZeroBits >= RegSize-1)
00727         isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
00728       else if (NumSignBits > RegSize-8)
00729         isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
00730       else if (NumZeroBits >= RegSize-8)
00731         isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
00732       else if (NumSignBits > RegSize-16)
00733         isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
00734       else if (NumZeroBits >= RegSize-16)
00735         isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
00736       else if (NumSignBits > RegSize-32)
00737         isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
00738       else if (NumZeroBits >= RegSize-32)
00739         isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
00740       else
00741         continue;
00742 
00743       // Add an assertion node.
00744       assert(FromVT != MVT::Other);
00745       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
00746                              RegisterVT, P, DAG.getValueType(FromVT));
00747     }
00748 
00749     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
00750                                      NumRegs, RegisterVT, ValueVT, V);
00751     Part += NumRegs;
00752     Parts.clear();
00753   }
00754 
00755   return DAG.getNode(ISD::MERGE_VALUES, dl,
00756                      DAG.getVTList(ValueVTs),
00757                      &Values[0], ValueVTs.size());
00758 }
00759 
00760 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
00761 /// specified value into the registers specified by this object.  This uses
00762 /// Chain/Flag as the input and updates them for the output Chain/Flag.
00763 /// If the Flag pointer is NULL, no flag is used.
00764 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
00765                                  SDValue &Chain, SDValue *Flag,
00766                                  const Value *V) const {
00767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00768 
00769   // Get the list of the values's legal parts.
00770   unsigned NumRegs = Regs.size();
00771   SmallVector<SDValue, 8> Parts(NumRegs);
00772   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
00773     EVT ValueVT = ValueVTs[Value];
00774     unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
00775     MVT RegisterVT = RegVTs[Value];
00776     ISD::NodeType ExtendKind =
00777       TLI.isZExtFree(Val, RegisterVT)? ISD::ZERO_EXTEND: ISD::ANY_EXTEND;
00778 
00779     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
00780                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
00781     Part += NumParts;
00782   }
00783 
00784   // Copy the parts into the registers.
00785   SmallVector<SDValue, 8> Chains(NumRegs);
00786   for (unsigned i = 0; i != NumRegs; ++i) {
00787     SDValue Part;
00788     if (!Flag) {
00789       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
00790     } else {
00791       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
00792       *Flag = Part.getValue(1);
00793     }
00794 
00795     Chains[i] = Part.getValue(0);
00796   }
00797 
00798   if (NumRegs == 1 || Flag)
00799     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
00800     // flagged to it. That is the CopyToReg nodes and the user are considered
00801     // a single scheduling unit. If we create a TokenFactor and return it as
00802     // chain, then the TokenFactor is both a predecessor (operand) of the
00803     // user as well as a successor (the TF operands are flagged to the user).
00804     // c1, f1 = CopyToReg
00805     // c2, f2 = CopyToReg
00806     // c3     = TokenFactor c1, c2
00807     // ...
00808     //        = op c3, ..., f2
00809     Chain = Chains[NumRegs-1];
00810   else
00811     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
00812 }
00813 
00814 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
00815 /// operand list.  This adds the code marker and includes the number of
00816 /// values added into it.
00817 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
00818                                         unsigned MatchingIdx,
00819                                         SelectionDAG &DAG,
00820                                         std::vector<SDValue> &Ops) const {
00821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
00822 
00823   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
00824   if (HasMatching)
00825     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
00826   else if (!Regs.empty() &&
00827            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
00828     // Put the register class of the virtual registers in the flag word.  That
00829     // way, later passes can recompute register class constraints for inline
00830     // assembly as well as normal instructions.
00831     // Don't do this for tied operands that can use the regclass information
00832     // from the def.
00833     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
00834     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
00835     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
00836   }
00837 
00838   SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
00839   Ops.push_back(Res);
00840 
00841   unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
00842   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
00843     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
00844     MVT RegisterVT = RegVTs[Value];
00845     for (unsigned i = 0; i != NumRegs; ++i) {
00846       assert(Reg < Regs.size() && "Mismatch in # registers expected");
00847       unsigned TheReg = Regs[Reg++];
00848       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
00849 
00850       if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
00851         // If we clobbered the stack pointer, MFI should know about it.
00852         assert(DAG.getMachineFunction().getFrameInfo()->
00853             hasInlineAsmWithSPAdjust());
00854       }
00855     }
00856   }
00857 }
00858 
00859 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
00860                                const TargetLibraryInfo *li) {
00861   AA = &aa;
00862   GFI = gfi;
00863   LibInfo = li;
00864   DL = DAG.getTarget().getDataLayout();
00865   Context = DAG.getContext();
00866   LPadToCallSiteMap.clear();
00867 }
00868 
00869 /// clear - Clear out the current SelectionDAG and the associated
00870 /// state and prepare this SelectionDAGBuilder object to be used
00871 /// for a new block. This doesn't clear out information about
00872 /// additional blocks that are needed to complete switch lowering
00873 /// or PHI node updating; that information is cleared out as it is
00874 /// consumed.
00875 void SelectionDAGBuilder::clear() {
00876   NodeMap.clear();
00877   UnusedArgNodeMap.clear();
00878   PendingLoads.clear();
00879   PendingExports.clear();
00880   CurInst = nullptr;
00881   HasTailCall = false;
00882   SDNodeOrder = LowestSDNodeOrder;
00883 }
00884 
00885 /// clearDanglingDebugInfo - Clear the dangling debug information
00886 /// map. This function is separated from the clear so that debug
00887 /// information that is dangling in a basic block can be properly
00888 /// resolved in a different basic block. This allows the
00889 /// SelectionDAG to resolve dangling debug information attached
00890 /// to PHI nodes.
00891 void SelectionDAGBuilder::clearDanglingDebugInfo() {
00892   DanglingDebugInfoMap.clear();
00893 }
00894 
00895 /// getRoot - Return the current virtual root of the Selection DAG,
00896 /// flushing any PendingLoad items. This must be done before emitting
00897 /// a store or any other node that may need to be ordered after any
00898 /// prior load instructions.
00899 ///
00900 SDValue SelectionDAGBuilder::getRoot() {
00901   if (PendingLoads.empty())
00902     return DAG.getRoot();
00903 
00904   if (PendingLoads.size() == 1) {
00905     SDValue Root = PendingLoads[0];
00906     DAG.setRoot(Root);
00907     PendingLoads.clear();
00908     return Root;
00909   }
00910 
00911   // Otherwise, we have to make a token factor node.
00912   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
00913                                &PendingLoads[0], PendingLoads.size());
00914   PendingLoads.clear();
00915   DAG.setRoot(Root);
00916   return Root;
00917 }
00918 
00919 /// getControlRoot - Similar to getRoot, but instead of flushing all the
00920 /// PendingLoad items, flush all the PendingExports items. It is necessary
00921 /// to do this before emitting a terminator instruction.
00922 ///
00923 SDValue SelectionDAGBuilder::getControlRoot() {
00924   SDValue Root = DAG.getRoot();
00925 
00926   if (PendingExports.empty())
00927     return Root;
00928 
00929   // Turn all of the CopyToReg chains into one factored node.
00930   if (Root.getOpcode() != ISD::EntryToken) {
00931     unsigned i = 0, e = PendingExports.size();
00932     for (; i != e; ++i) {
00933       assert(PendingExports[i].getNode()->getNumOperands() > 1);
00934       if (PendingExports[i].getNode()->getOperand(0) == Root)
00935         break;  // Don't add the root if we already indirectly depend on it.
00936     }
00937 
00938     if (i == e)
00939       PendingExports.push_back(Root);
00940   }
00941 
00942   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
00943                      &PendingExports[0],
00944                      PendingExports.size());
00945   PendingExports.clear();
00946   DAG.setRoot(Root);
00947   return Root;
00948 }
00949 
00950 void SelectionDAGBuilder::visit(const Instruction &I) {
00951   // Set up outgoing PHI node register values before emitting the terminator.
00952   if (isa<TerminatorInst>(&I))
00953     HandlePHINodesInSuccessorBlocks(I.getParent());
00954 
00955   ++SDNodeOrder;
00956 
00957   CurInst = &I;
00958 
00959   visit(I.getOpcode(), I);
00960 
00961   if (!isa<TerminatorInst>(&I) && !HasTailCall)
00962     CopyToExportRegsIfNeeded(&I);
00963 
00964   CurInst = nullptr;
00965 }
00966 
00967 void SelectionDAGBuilder::visitPHI(const PHINode &) {
00968   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
00969 }
00970 
00971 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
00972   // Note: this doesn't use InstVisitor, because it has to work with
00973   // ConstantExpr's in addition to instructions.
00974   switch (Opcode) {
00975   default: llvm_unreachable("Unknown instruction type encountered!");
00976     // Build the switch statement using the Instruction.def file.
00977 #define HANDLE_INST(NUM, OPCODE, CLASS) \
00978     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
00979 #include "llvm/IR/Instruction.def"
00980   }
00981 }
00982 
00983 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
00984 // generate the debug data structures now that we've seen its definition.
00985 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
00986                                                    SDValue Val) {
00987   DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
00988   if (DDI.getDI()) {
00989     const DbgValueInst *DI = DDI.getDI();
00990     DebugLoc dl = DDI.getdl();
00991     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
00992     MDNode *Variable = DI->getVariable();
00993     uint64_t Offset = DI->getOffset();
00994     SDDbgValue *SDV;
00995     if (Val.getNode()) {
00996       if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
00997         SDV = DAG.getDbgValue(Variable, Val.getNode(),
00998                               Val.getResNo(), Offset, dl, DbgSDNodeOrder);
00999         DAG.AddDbgValue(SDV, Val.getNode(), false);
01000       }
01001     } else
01002       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
01003     DanglingDebugInfoMap[V] = DanglingDebugInfo();
01004   }
01005 }
01006 
01007 /// getValue - Return an SDValue for the given Value.
01008 SDValue SelectionDAGBuilder::getValue(const Value *V) {
01009   // If we already have an SDValue for this value, use it. It's important
01010   // to do this first, so that we don't create a CopyFromReg if we already
01011   // have a regular SDValue.
01012   SDValue &N = NodeMap[V];
01013   if (N.getNode()) return N;
01014 
01015   // If there's a virtual register allocated and initialized for this
01016   // value, use it.
01017   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
01018   if (It != FuncInfo.ValueMap.end()) {
01019     unsigned InReg = It->second;
01020     RegsForValue RFV(*DAG.getContext(), *TM.getTargetLowering(),
01021                      InReg, V->getType());
01022     SDValue Chain = DAG.getEntryNode();
01023     N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
01024     resolveDanglingDebugInfo(V, N);
01025     return N;
01026   }
01027 
01028   // Otherwise create a new SDValue and remember it.
01029   SDValue Val = getValueImpl(V);
01030   NodeMap[V] = Val;
01031   resolveDanglingDebugInfo(V, Val);
01032   return Val;
01033 }
01034 
01035 /// getNonRegisterValue - Return an SDValue for the given Value, but
01036 /// don't look in FuncInfo.ValueMap for a virtual register.
01037 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
01038   // If we already have an SDValue for this value, use it.
01039   SDValue &N = NodeMap[V];
01040   if (N.getNode()) return N;
01041 
01042   // Otherwise create a new SDValue and remember it.
01043   SDValue Val = getValueImpl(V);
01044   NodeMap[V] = Val;
01045   resolveDanglingDebugInfo(V, Val);
01046   return Val;
01047 }
01048 
01049 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
01050 /// Create an SDValue for the given value.
01051 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
01052   const TargetLowering *TLI = TM.getTargetLowering();
01053 
01054   if (const Constant *C = dyn_cast<Constant>(V)) {
01055     EVT VT = TLI->getValueType(V->getType(), true);
01056 
01057     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
01058       return DAG.getConstant(*CI, VT);
01059 
01060     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
01061       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
01062 
01063     if (isa<ConstantPointerNull>(C)) {
01064       unsigned AS = V->getType()->getPointerAddressSpace();
01065       return DAG.getConstant(0, TLI->getPointerTy(AS));
01066     }
01067 
01068     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
01069       return DAG.getConstantFP(*CFP, VT);
01070 
01071     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
01072       return DAG.getUNDEF(VT);
01073 
01074     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
01075       visit(CE->getOpcode(), *CE);
01076       SDValue N1 = NodeMap[V];
01077       assert(N1.getNode() && "visit didn't populate the NodeMap!");
01078       return N1;
01079     }
01080 
01081     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
01082       SmallVector<SDValue, 4> Constants;
01083       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
01084            OI != OE; ++OI) {
01085         SDNode *Val = getValue(*OI).getNode();
01086         // If the operand is an empty aggregate, there are no values.
01087         if (!Val) continue;
01088         // Add each leaf value from the operand to the Constants list
01089         // to form a flattened list of all the values.
01090         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
01091           Constants.push_back(SDValue(Val, i));
01092       }
01093 
01094       return DAG.getMergeValues(&Constants[0], Constants.size(),
01095                                 getCurSDLoc());
01096     }
01097 
01098     if (const ConstantDataSequential *CDS =
01099           dyn_cast<ConstantDataSequential>(C)) {
01100       SmallVector<SDValue, 4> Ops;
01101       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01102         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
01103         // Add each leaf value from the operand to the Constants list
01104         // to form a flattened list of all the values.
01105         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
01106           Ops.push_back(SDValue(Val, i));
01107       }
01108 
01109       if (isa<ArrayType>(CDS->getType()))
01110         return DAG.getMergeValues(&Ops[0], Ops.size(), getCurSDLoc());
01111       return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
01112                                       VT, &Ops[0], Ops.size());
01113     }
01114 
01115     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
01116       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
01117              "Unknown struct or array constant!");
01118 
01119       SmallVector<EVT, 4> ValueVTs;
01120       ComputeValueVTs(*TLI, C->getType(), ValueVTs);
01121       unsigned NumElts = ValueVTs.size();
01122       if (NumElts == 0)
01123         return SDValue(); // empty struct
01124       SmallVector<SDValue, 4> Constants(NumElts);
01125       for (unsigned i = 0; i != NumElts; ++i) {
01126         EVT EltVT = ValueVTs[i];
01127         if (isa<UndefValue>(C))
01128           Constants[i] = DAG.getUNDEF(EltVT);
01129         else if (EltVT.isFloatingPoint())
01130           Constants[i] = DAG.getConstantFP(0, EltVT);
01131         else
01132           Constants[i] = DAG.getConstant(0, EltVT);
01133       }
01134 
01135       return DAG.getMergeValues(&Constants[0], NumElts,
01136                                 getCurSDLoc());
01137     }
01138 
01139     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
01140       return DAG.getBlockAddress(BA, VT);
01141 
01142     VectorType *VecTy = cast<VectorType>(V->getType());
01143     unsigned NumElements = VecTy->getNumElements();
01144 
01145     // Now that we know the number and type of the elements, get that number of
01146     // elements into the Ops array based on what kind of constant it is.
01147     SmallVector<SDValue, 16> Ops;
01148     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
01149       for (unsigned i = 0; i != NumElements; ++i)
01150         Ops.push_back(getValue(CV->getOperand(i)));
01151     } else {
01152       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
01153       EVT EltVT = TLI->getValueType(VecTy->getElementType());
01154 
01155       SDValue Op;
01156       if (EltVT.isFloatingPoint())
01157         Op = DAG.getConstantFP(0, EltVT);
01158       else
01159         Op = DAG.getConstant(0, EltVT);
01160       Ops.assign(NumElements, Op);
01161     }
01162 
01163     // Create a BUILD_VECTOR node.
01164     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
01165                                     VT, &Ops[0], Ops.size());
01166   }
01167 
01168   // If this is a static alloca, generate it as the frameindex instead of
01169   // computation.
01170   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
01171     DenseMap<const AllocaInst*, int>::iterator SI =
01172       FuncInfo.StaticAllocaMap.find(AI);
01173     if (SI != FuncInfo.StaticAllocaMap.end())
01174       return DAG.getFrameIndex(SI->second, TLI->getPointerTy());
01175   }
01176 
01177   // If this is an instruction which fast-isel has deferred, select it now.
01178   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
01179     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
01180     RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType());
01181     SDValue Chain = DAG.getEntryNode();
01182     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
01183   }
01184 
01185   llvm_unreachable("Can't get register for value!");
01186 }
01187 
01188 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
01189   const TargetLowering *TLI = TM.getTargetLowering();
01190   SDValue Chain = getControlRoot();
01191   SmallVector<ISD::OutputArg, 8> Outs;
01192   SmallVector<SDValue, 8> OutVals;
01193 
01194   if (!FuncInfo.CanLowerReturn) {
01195     unsigned DemoteReg = FuncInfo.DemoteRegister;
01196     const Function *F = I.getParent()->getParent();
01197 
01198     // Emit a store of the return value through the virtual register.
01199     // Leave Outs empty so that LowerReturn won't try to load return
01200     // registers the usual way.
01201     SmallVector<EVT, 1> PtrValueVTs;
01202     ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()),
01203                     PtrValueVTs);
01204 
01205     SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
01206     SDValue RetOp = getValue(I.getOperand(0));
01207 
01208     SmallVector<EVT, 4> ValueVTs;
01209     SmallVector<uint64_t, 4> Offsets;
01210     ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
01211     unsigned NumValues = ValueVTs.size();
01212 
01213     SmallVector<SDValue, 4> Chains(NumValues);
01214     for (unsigned i = 0; i != NumValues; ++i) {
01215       SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
01216                                 RetPtr.getValueType(), RetPtr,
01217                                 DAG.getIntPtrConstant(Offsets[i]));
01218       Chains[i] =
01219         DAG.getStore(Chain, getCurSDLoc(),
01220                      SDValue(RetOp.getNode(), RetOp.getResNo() + i),
01221                      // FIXME: better loc info would be nice.
01222                      Add, MachinePointerInfo(), false, false, 0);
01223     }
01224 
01225     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
01226                         MVT::Other, &Chains[0], NumValues);
01227   } else if (I.getNumOperands() != 0) {
01228     SmallVector<EVT, 4> ValueVTs;
01229     ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs);
01230     unsigned NumValues = ValueVTs.size();
01231     if (NumValues) {
01232       SDValue RetOp = getValue(I.getOperand(0));
01233       for (unsigned j = 0, f = NumValues; j != f; ++j) {
01234         EVT VT = ValueVTs[j];
01235 
01236         ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
01237 
01238         const Function *F = I.getParent()->getParent();
01239         if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
01240                                             Attribute::SExt))
01241           ExtendKind = ISD::SIGN_EXTEND;
01242         else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
01243                                                  Attribute::ZExt))
01244           ExtendKind = ISD::ZERO_EXTEND;
01245 
01246         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
01247           VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind);
01248 
01249         unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT);
01250         MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT);
01251         SmallVector<SDValue, 4> Parts(NumParts);
01252         getCopyToParts(DAG, getCurSDLoc(),
01253                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
01254                        &Parts[0], NumParts, PartVT, &I, ExtendKind);
01255 
01256         // 'inreg' on function refers to return value
01257         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
01258         if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
01259                                             Attribute::InReg))
01260           Flags.setInReg();
01261 
01262         // Propagate extension type if any
01263         if (ExtendKind == ISD::SIGN_EXTEND)
01264           Flags.setSExt();
01265         else if (ExtendKind == ISD::ZERO_EXTEND)
01266           Flags.setZExt();
01267 
01268         for (unsigned i = 0; i < NumParts; ++i) {
01269           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
01270                                         VT, /*isfixed=*/true, 0, 0));
01271           OutVals.push_back(Parts[i]);
01272         }
01273       }
01274     }
01275   }
01276 
01277   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
01278   CallingConv::ID CallConv =
01279     DAG.getMachineFunction().getFunction()->getCallingConv();
01280   Chain = TM.getTargetLowering()->LowerReturn(Chain, CallConv, isVarArg,
01281                                               Outs, OutVals, getCurSDLoc(),
01282                                               DAG);
01283 
01284   // Verify that the target's LowerReturn behaved as expected.
01285   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
01286          "LowerReturn didn't return a valid chain!");
01287 
01288   // Update the DAG with the new chain value resulting from return lowering.
01289   DAG.setRoot(Chain);
01290 }
01291 
01292 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
01293 /// created for it, emit nodes to copy the value into the virtual
01294 /// registers.
01295 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
01296   // Skip empty types
01297   if (V->getType()->isEmptyTy())
01298     return;
01299 
01300   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
01301   if (VMI != FuncInfo.ValueMap.end()) {
01302     assert(!V->use_empty() && "Unused value assigned virtual registers!");
01303     CopyValueToVirtualRegister(V, VMI->second);
01304   }
01305 }
01306 
01307 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
01308 /// the current basic block, add it to ValueMap now so that we'll get a
01309 /// CopyTo/FromReg.
01310 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
01311   // No need to export constants.
01312   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
01313 
01314   // Already exported?
01315   if (FuncInfo.isExportedInst(V)) return;
01316 
01317   unsigned Reg = FuncInfo.InitializeRegForValue(V);
01318   CopyValueToVirtualRegister(V, Reg);
01319 }
01320 
01321 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
01322                                                      const BasicBlock *FromBB) {
01323   // The operands of the setcc have to be in this block.  We don't know
01324   // how to export them from some other block.
01325   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
01326     // Can export from current BB.
01327     if (VI->getParent() == FromBB)
01328       return true;
01329 
01330     // Is already exported, noop.
01331     return FuncInfo.isExportedInst(V);
01332   }
01333 
01334   // If this is an argument, we can export it if the BB is the entry block or
01335   // if it is already exported.
01336   if (isa<Argument>(V)) {
01337     if (FromBB == &FromBB->getParent()->getEntryBlock())
01338       return true;
01339 
01340     // Otherwise, can only export this if it is already exported.
01341     return FuncInfo.isExportedInst(V);
01342   }
01343 
01344   // Otherwise, constants can always be exported.
01345   return true;
01346 }
01347 
01348 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
01349 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
01350                                             const MachineBasicBlock *Dst) const {
01351   BranchProbabilityInfo *BPI = FuncInfo.BPI;
01352   if (!BPI)
01353     return 0;
01354   const BasicBlock *SrcBB = Src->getBasicBlock();
01355   const BasicBlock *DstBB = Dst->getBasicBlock();
01356   return BPI->getEdgeWeight(SrcBB, DstBB);
01357 }
01358 
01359 void SelectionDAGBuilder::
01360 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
01361                        uint32_t Weight /* = 0 */) {
01362   if (!Weight)
01363     Weight = getEdgeWeight(Src, Dst);
01364   Src->addSuccessor(Dst, Weight);
01365 }
01366 
01367 
01368 static bool InBlock(const Value *V, const BasicBlock *BB) {
01369   if (const Instruction *I = dyn_cast<Instruction>(V))
01370     return I->getParent() == BB;
01371   return true;
01372 }
01373 
01374 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
01375 /// This function emits a branch and is used at the leaves of an OR or an
01376 /// AND operator tree.
01377 ///
01378 void
01379 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
01380                                                   MachineBasicBlock *TBB,
01381                                                   MachineBasicBlock *FBB,
01382                                                   MachineBasicBlock *CurBB,
01383                                                   MachineBasicBlock *SwitchBB,
01384                                                   uint32_t TWeight,
01385                                                   uint32_t FWeight) {
01386   const BasicBlock *BB = CurBB->getBasicBlock();
01387 
01388   // If the leaf of the tree is a comparison, merge the condition into
01389   // the caseblock.
01390   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
01391     // The operands of the cmp have to be in this block.  We don't know
01392     // how to export them from some other block.  If this is the first block
01393     // of the sequence, no exporting is needed.
01394     if (CurBB == SwitchBB ||
01395         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
01396          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
01397       ISD::CondCode Condition;
01398       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
01399         Condition = getICmpCondCode(IC->getPredicate());
01400       } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
01401         Condition = getFCmpCondCode(FC->getPredicate());
01402         if (TM.Options.NoNaNsFPMath)
01403           Condition = getFCmpCodeWithoutNaN(Condition);
01404       } else {
01405         Condition = ISD::SETEQ; // silence warning.
01406         llvm_unreachable("Unknown compare instruction");
01407       }
01408 
01409       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
01410                    TBB, FBB, CurBB, TWeight, FWeight);
01411       SwitchCases.push_back(CB);
01412       return;
01413     }
01414   }
01415 
01416   // Create a CaseBlock record representing this branch.
01417   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
01418                nullptr, TBB, FBB, CurBB, TWeight, FWeight);
01419   SwitchCases.push_back(CB);
01420 }
01421 
01422 /// Scale down both weights to fit into uint32_t.
01423 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
01424   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
01425   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
01426   NewTrue = NewTrue / Scale;
01427   NewFalse = NewFalse / Scale;
01428 }
01429 
01430 /// FindMergedConditions - If Cond is an expression like
01431 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
01432                                                MachineBasicBlock *TBB,
01433                                                MachineBasicBlock *FBB,
01434                                                MachineBasicBlock *CurBB,
01435                                                MachineBasicBlock *SwitchBB,
01436                                                unsigned Opc, uint32_t TWeight,
01437                                                uint32_t FWeight) {
01438   // If this node is not part of the or/and tree, emit it as a branch.
01439   const Instruction *BOp = dyn_cast<Instruction>(Cond);
01440   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
01441       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
01442       BOp->getParent() != CurBB->getBasicBlock() ||
01443       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
01444       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
01445     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
01446                                  TWeight, FWeight);
01447     return;
01448   }
01449 
01450   //  Create TmpBB after CurBB.
01451   MachineFunction::iterator BBI = CurBB;
01452   MachineFunction &MF = DAG.getMachineFunction();
01453   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
01454   CurBB->getParent()->insert(++BBI, TmpBB);
01455 
01456   if (Opc == Instruction::Or) {
01457     // Codegen X | Y as:
01458     // BB1:
01459     //   jmp_if_X TBB
01460     //   jmp TmpBB
01461     // TmpBB:
01462     //   jmp_if_Y TBB
01463     //   jmp FBB
01464     //
01465 
01466     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
01467     // The requirement is that
01468     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
01469     //     = TrueProb for orignal BB.
01470     // Assuming the orignal weights are A and B, one choice is to set BB1's
01471     // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
01472     // assumes that
01473     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
01474     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
01475     // TmpBB, but the math is more complicated.
01476 
01477     uint64_t NewTrueWeight = TWeight;
01478     uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
01479     ScaleWeights(NewTrueWeight, NewFalseWeight);
01480     // Emit the LHS condition.
01481     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
01482                          NewTrueWeight, NewFalseWeight);
01483 
01484     NewTrueWeight = TWeight;
01485     NewFalseWeight = 2 * (uint64_t)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   } else {
01491     assert(Opc == Instruction::And && "Unknown merge op!");
01492     // Codegen X & Y as:
01493     // BB1:
01494     //   jmp_if_X TmpBB
01495     //   jmp FBB
01496     // TmpBB:
01497     //   jmp_if_Y TBB
01498     //   jmp FBB
01499     //
01500     //  This requires creation of TmpBB after CurBB.
01501 
01502     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
01503     // The requirement is that
01504     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
01505     //     = FalseProb for orignal BB.
01506     // Assuming the orignal weights are A and B, one choice is to set BB1's
01507     // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
01508     // assumes that
01509     //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
01510 
01511     uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
01512     uint64_t NewFalseWeight = FWeight;
01513     ScaleWeights(NewTrueWeight, NewFalseWeight);
01514     // Emit the LHS condition.
01515     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
01516                          NewTrueWeight, NewFalseWeight);
01517 
01518     NewTrueWeight = 2 * (uint64_t)TWeight;
01519     NewFalseWeight = FWeight;
01520     ScaleWeights(NewTrueWeight, NewFalseWeight);
01521     // Emit the RHS condition into TmpBB.
01522     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
01523                          NewTrueWeight, NewFalseWeight);
01524   }
01525 }
01526 
01527 /// If the set of cases should be emitted as a series of branches, return true.
01528 /// If we should emit this as a bunch of and/or'd together conditions, return
01529 /// false.
01530 bool
01531 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
01532   if (Cases.size() != 2) return true;
01533 
01534   // If this is two comparisons of the same values or'd or and'd together, they
01535   // will get folded into a single comparison, so don't emit two blocks.
01536   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
01537        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
01538       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
01539        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
01540     return false;
01541   }
01542 
01543   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
01544   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
01545   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
01546       Cases[0].CC == Cases[1].CC &&
01547       isa<Constant>(Cases[0].CmpRHS) &&
01548       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
01549     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
01550       return false;
01551     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
01552       return false;
01553   }
01554 
01555   return true;
01556 }
01557 
01558 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
01559   MachineBasicBlock *BrMBB = FuncInfo.MBB;
01560 
01561   // Update machine-CFG edges.
01562   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
01563 
01564   // Figure out which block is immediately after the current one.
01565   MachineBasicBlock *NextBlock = nullptr;
01566   MachineFunction::iterator BBI = BrMBB;
01567   if (++BBI != FuncInfo.MF->end())
01568     NextBlock = BBI;
01569 
01570   if (I.isUnconditional()) {
01571     // Update machine-CFG edges.
01572     BrMBB->addSuccessor(Succ0MBB);
01573 
01574     // If this is not a fall-through branch or optimizations are switched off,
01575     // emit the branch.
01576     if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
01577       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
01578                               MVT::Other, getControlRoot(),
01579                               DAG.getBasicBlock(Succ0MBB)));
01580 
01581     return;
01582   }
01583 
01584   // If this condition is one of the special cases we handle, do special stuff
01585   // now.
01586   const Value *CondVal = I.getCondition();
01587   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
01588 
01589   // If this is a series of conditions that are or'd or and'd together, emit
01590   // this as a sequence of branches instead of setcc's with and/or operations.
01591   // As long as jumps are not expensive, this should improve performance.
01592   // For example, instead of something like:
01593   //     cmp A, B
01594   //     C = seteq
01595   //     cmp D, E
01596   //     F = setle
01597   //     or C, F
01598   //     jnz foo
01599   // Emit:
01600   //     cmp A, B
01601   //     je foo
01602   //     cmp D, E
01603   //     jle foo
01604   //
01605   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
01606     if (!TM.getTargetLowering()->isJumpExpensive() &&
01607         BOp->hasOneUse() &&
01608         (BOp->getOpcode() == Instruction::And ||
01609          BOp->getOpcode() == Instruction::Or)) {
01610       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
01611                            BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
01612                            getEdgeWeight(BrMBB, Succ1MBB));
01613       // If the compares in later blocks need to use values not currently
01614       // exported from this block, export them now.  This block should always
01615       // be the first entry.
01616       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
01617 
01618       // Allow some cases to be rejected.
01619       if (ShouldEmitAsBranches(SwitchCases)) {
01620         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
01621           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
01622           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
01623         }
01624 
01625         // Emit the branch for this block.
01626         visitSwitchCase(SwitchCases[0], BrMBB);
01627         SwitchCases.erase(SwitchCases.begin());
01628         return;
01629       }
01630 
01631       // Okay, we decided not to do this, remove any inserted MBB's and clear
01632       // SwitchCases.
01633       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
01634         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
01635 
01636       SwitchCases.clear();
01637     }
01638   }
01639 
01640   // Create a CaseBlock record representing this branch.
01641   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
01642                nullptr, Succ0MBB, Succ1MBB, BrMBB);
01643 
01644   // Use visitSwitchCase to actually insert the fast branch sequence for this
01645   // cond branch.
01646   visitSwitchCase(CB, BrMBB);
01647 }
01648 
01649 /// visitSwitchCase - Emits the necessary code to represent a single node in
01650 /// the binary search tree resulting from lowering a switch instruction.
01651 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
01652                                           MachineBasicBlock *SwitchBB) {
01653   SDValue Cond;
01654   SDValue CondLHS = getValue(CB.CmpLHS);
01655   SDLoc dl = getCurSDLoc();
01656 
01657   // Build the setcc now.
01658   if (!CB.CmpMHS) {
01659     // Fold "(X == true)" to X and "(X == false)" to !X to
01660     // handle common cases produced by branch lowering.
01661     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
01662         CB.CC == ISD::SETEQ)
01663       Cond = CondLHS;
01664     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
01665              CB.CC == ISD::SETEQ) {
01666       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
01667       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
01668     } else
01669       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
01670   } else {
01671     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
01672 
01673     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
01674     const APInt& High  = cast<ConstantInt>(CB.CmpRHS)->getValue();
01675 
01676     SDValue CmpOp = getValue(CB.CmpMHS);
01677     EVT VT = CmpOp.getValueType();
01678 
01679     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
01680       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
01681                           ISD::SETLE);
01682     } else {
01683       SDValue SUB = DAG.getNode(ISD::SUB, dl,
01684                                 VT, CmpOp, DAG.getConstant(Low, VT));
01685       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
01686                           DAG.getConstant(High-Low, VT), ISD::SETULE);
01687     }
01688   }
01689 
01690   // Update successor info
01691   addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
01692   // TrueBB and FalseBB are always different unless the incoming IR is
01693   // degenerate. This only happens when running llc on weird IR.
01694   if (CB.TrueBB != CB.FalseBB)
01695     addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
01696 
01697   // Set NextBlock to be the MBB immediately after the current one, if any.
01698   // This is used to avoid emitting unnecessary branches to the next block.
01699   MachineBasicBlock *NextBlock = nullptr;
01700   MachineFunction::iterator BBI = SwitchBB;
01701   if (++BBI != FuncInfo.MF->end())
01702     NextBlock = BBI;
01703 
01704   // If the lhs block is the next block, invert the condition so that we can
01705   // fall through to the lhs instead of the rhs block.
01706   if (CB.TrueBB == NextBlock) {
01707     std::swap(CB.TrueBB, CB.FalseBB);
01708     SDValue True = DAG.getConstant(1, Cond.getValueType());
01709     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
01710   }
01711 
01712   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
01713                                MVT::Other, getControlRoot(), Cond,
01714                                DAG.getBasicBlock(CB.TrueBB));
01715 
01716   // Insert the false branch. Do this even if it's a fall through branch,
01717   // this makes it easier to do DAG optimizations which require inverting
01718   // the branch condition.
01719   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
01720                        DAG.getBasicBlock(CB.FalseBB));
01721 
01722   DAG.setRoot(BrCond);
01723 }
01724 
01725 /// visitJumpTable - Emit JumpTable node in the current MBB
01726 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
01727   // Emit the code for the jump table
01728   assert(JT.Reg != -1U && "Should lower JT Header first!");
01729   EVT PTy = TM.getTargetLowering()->getPointerTy();
01730   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
01731                                      JT.Reg, PTy);
01732   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
01733   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
01734                                     MVT::Other, Index.getValue(1),
01735                                     Table, Index);
01736   DAG.setRoot(BrJumpTable);
01737 }
01738 
01739 /// visitJumpTableHeader - This function emits necessary code to produce index
01740 /// in the JumpTable from switch case.
01741 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
01742                                                JumpTableHeader &JTH,
01743                                                MachineBasicBlock *SwitchBB) {
01744   // Subtract the lowest switch case value from the value being switched on and
01745   // conditional branch to default mbb if the result is greater than the
01746   // difference between smallest and largest cases.
01747   SDValue SwitchOp = getValue(JTH.SValue);
01748   EVT VT = SwitchOp.getValueType();
01749   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
01750                             DAG.getConstant(JTH.First, VT));
01751 
01752   // The SDNode we just created, which holds the value being switched on minus
01753   // the smallest case value, needs to be copied to a virtual register so it
01754   // can be used as an index into the jump table in a subsequent basic block.
01755   // This value may be smaller or larger than the target's pointer type, and
01756   // therefore require extension or truncating.
01757   const TargetLowering *TLI = TM.getTargetLowering();
01758   SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy());
01759 
01760   unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy());
01761   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
01762                                     JumpTableReg, SwitchOp);
01763   JT.Reg = JumpTableReg;
01764 
01765   // Emit the range check for the jump table, and branch to the default block
01766   // for the switch statement if the value being switched on exceeds the largest
01767   // case in the switch.
01768   SDValue CMP = DAG.getSetCC(getCurSDLoc(),
01769                              TLI->getSetCCResultType(*DAG.getContext(),
01770                                                      Sub.getValueType()),
01771                              Sub,
01772                              DAG.getConstant(JTH.Last - JTH.First,VT),
01773                              ISD::SETUGT);
01774 
01775   // Set NextBlock to be the MBB immediately after the current one, if any.
01776   // This is used to avoid emitting unnecessary branches to the next block.
01777   MachineBasicBlock *NextBlock = nullptr;
01778   MachineFunction::iterator BBI = SwitchBB;
01779 
01780   if (++BBI != FuncInfo.MF->end())
01781     NextBlock = BBI;
01782 
01783   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
01784                                MVT::Other, CopyTo, CMP,
01785                                DAG.getBasicBlock(JT.Default));
01786 
01787   if (JT.MBB != NextBlock)
01788     BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
01789                          DAG.getBasicBlock(JT.MBB));
01790 
01791   DAG.setRoot(BrCond);
01792 }
01793 
01794 /// Codegen a new tail for a stack protector check ParentMBB which has had its
01795 /// tail spliced into a stack protector check success bb.
01796 ///
01797 /// For a high level explanation of how this fits into the stack protector
01798 /// generation see the comment on the declaration of class
01799 /// StackProtectorDescriptor.
01800 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
01801                                                   MachineBasicBlock *ParentBB) {
01802 
01803   // First create the loads to the guard/stack slot for the comparison.
01804   const TargetLowering *TLI = TM.getTargetLowering();
01805   EVT PtrTy = TLI->getPointerTy();
01806 
01807   MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
01808   int FI = MFI->getStackProtectorIndex();
01809 
01810   const Value *IRGuard = SPD.getGuard();
01811   SDValue GuardPtr = getValue(IRGuard);
01812   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
01813 
01814   unsigned Align =
01815     TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
01816   SDValue Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
01817                               GuardPtr, MachinePointerInfo(IRGuard, 0),
01818                               true, false, false, Align);
01819 
01820   SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
01821                                   StackSlotPtr,
01822                                   MachinePointerInfo::getFixedStack(FI),
01823                                   true, false, false, Align);
01824 
01825   // Perform the comparison via a subtract/getsetcc.
01826   EVT VT = Guard.getValueType();
01827   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
01828 
01829   SDValue Cmp = DAG.getSetCC(getCurSDLoc(),
01830                              TLI->getSetCCResultType(*DAG.getContext(),
01831                                                      Sub.getValueType()),
01832                              Sub, DAG.getConstant(0, VT),
01833                              ISD::SETNE);
01834 
01835   // If the sub is not 0, then we know the guard/stackslot do not equal, so
01836   // branch to failure MBB.
01837   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
01838                                MVT::Other, StackSlot.getOperand(0),
01839                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
01840   // Otherwise branch to success MBB.
01841   SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
01842                            MVT::Other, BrCond,
01843                            DAG.getBasicBlock(SPD.getSuccessMBB()));
01844 
01845   DAG.setRoot(Br);
01846 }
01847 
01848 /// Codegen the failure basic block for a stack protector check.
01849 ///
01850 /// A failure stack protector machine basic block consists simply of a call to
01851 /// __stack_chk_fail().
01852 ///
01853 /// For a high level explanation of how this fits into the stack protector
01854 /// generation see the comment on the declaration of class
01855 /// StackProtectorDescriptor.
01856 void
01857 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
01858   const TargetLowering *TLI = TM.getTargetLowering();
01859   SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
01860                                    MVT::isVoid, nullptr, 0, false,
01861                                    getCurSDLoc(), false, false).second;
01862   DAG.setRoot(Chain);
01863 }
01864 
01865 /// visitBitTestHeader - This function emits necessary code to produce value
01866 /// suitable for "bit tests"
01867 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
01868                                              MachineBasicBlock *SwitchBB) {
01869   // Subtract the minimum value
01870   SDValue SwitchOp = getValue(B.SValue);
01871   EVT VT = SwitchOp.getValueType();
01872   SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
01873                             DAG.getConstant(B.First, VT));
01874 
01875   // Check range
01876   const TargetLowering *TLI = TM.getTargetLowering();
01877   SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(),
01878                                   TLI->getSetCCResultType(*DAG.getContext(),
01879                                                          Sub.getValueType()),
01880                                   Sub, DAG.getConstant(B.Range, VT),
01881                                   ISD::SETUGT);
01882 
01883   // Determine the type of the test operands.
01884   bool UsePtrType = false;
01885   if (!TLI->isTypeLegal(VT))
01886     UsePtrType = true;
01887   else {
01888     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
01889       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
01890         // Switch table case range are encoded into series of masks.
01891         // Just use pointer type, it's guaranteed to fit.
01892         UsePtrType = true;
01893         break;
01894       }
01895   }
01896   if (UsePtrType) {
01897     VT = TLI->getPointerTy();
01898     Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
01899   }
01900 
01901   B.RegVT = VT.getSimpleVT();
01902   B.Reg = FuncInfo.CreateReg(B.RegVT);
01903   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
01904                                     B.Reg, Sub);
01905 
01906   // Set NextBlock to be the MBB immediately after the current one, if any.
01907   // This is used to avoid emitting unnecessary branches to the next block.
01908   MachineBasicBlock *NextBlock = nullptr;
01909   MachineFunction::iterator BBI = SwitchBB;
01910   if (++BBI != FuncInfo.MF->end())
01911     NextBlock = BBI;
01912 
01913   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
01914 
01915   addSuccessorWithWeight(SwitchBB, B.Default);
01916   addSuccessorWithWeight(SwitchBB, MBB);
01917 
01918   SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
01919                                 MVT::Other, CopyTo, RangeCmp,
01920                                 DAG.getBasicBlock(B.Default));
01921 
01922   if (MBB != NextBlock)
01923     BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
01924                           DAG.getBasicBlock(MBB));
01925 
01926   DAG.setRoot(BrRange);
01927 }
01928 
01929 /// visitBitTestCase - this function produces one "bit test"
01930 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
01931                                            MachineBasicBlock* NextMBB,
01932                                            uint32_t BranchWeightToNext,
01933                                            unsigned Reg,
01934                                            BitTestCase &B,
01935                                            MachineBasicBlock *SwitchBB) {
01936   MVT VT = BB.RegVT;
01937   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
01938                                        Reg, VT);
01939   SDValue Cmp;
01940   unsigned PopCount = CountPopulation_64(B.Mask);
01941   const TargetLowering *TLI = TM.getTargetLowering();
01942   if (PopCount == 1) {
01943     // Testing for a single bit; just compare the shift count with what it
01944     // would need to be to shift a 1 bit in that position.
01945     Cmp = DAG.getSetCC(getCurSDLoc(),
01946                        TLI->getSetCCResultType(*DAG.getContext(), VT),
01947                        ShiftOp,
01948                        DAG.getConstant(countTrailingZeros(B.Mask), VT),
01949                        ISD::SETEQ);
01950   } else if (PopCount == BB.Range) {
01951     // There is only one zero bit in the range, test for it directly.
01952     Cmp = DAG.getSetCC(getCurSDLoc(),
01953                        TLI->getSetCCResultType(*DAG.getContext(), VT),
01954                        ShiftOp,
01955                        DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
01956                        ISD::SETNE);
01957   } else {
01958     // Make desired shift
01959     SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
01960                                     DAG.getConstant(1, VT), ShiftOp);
01961 
01962     // Emit bit tests and jumps
01963     SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
01964                                 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
01965     Cmp = DAG.getSetCC(getCurSDLoc(),
01966                        TLI->getSetCCResultType(*DAG.getContext(), VT),
01967                        AndOp, DAG.getConstant(0, VT),
01968                        ISD::SETNE);
01969   }
01970 
01971   // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
01972   addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
01973   // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
01974   addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
01975 
01976   SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
01977                               MVT::Other, getControlRoot(),
01978                               Cmp, DAG.getBasicBlock(B.TargetBB));
01979 
01980   // Set NextBlock to be the MBB immediately after the current one, if any.
01981   // This is used to avoid emitting unnecessary branches to the next block.
01982   MachineBasicBlock *NextBlock = nullptr;
01983   MachineFunction::iterator BBI = SwitchBB;
01984   if (++BBI != FuncInfo.MF->end())
01985     NextBlock = BBI;
01986 
01987   if (NextMBB != NextBlock)
01988     BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
01989                         DAG.getBasicBlock(NextMBB));
01990 
01991   DAG.setRoot(BrAnd);
01992 }
01993 
01994 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
01995   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
01996 
01997   // Retrieve successors.
01998   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
01999   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
02000 
02001   const Value *Callee(I.getCalledValue());
02002   const Function *Fn = dyn_cast<Function>(Callee);
02003   if (isa<InlineAsm>(Callee))
02004     visitInlineAsm(&I);
02005   else if (Fn && Fn->isIntrinsic()) {
02006     assert(Fn->getIntrinsicID() == Intrinsic::donothing);
02007     // Ignore invokes to @llvm.donothing: jump directly to the next BB.
02008   } else
02009     LowerCallTo(&I, getValue(Callee), false, LandingPad);
02010 
02011   // If the value of the invoke is used outside of its defining block, make it
02012   // available as a virtual register.
02013   CopyToExportRegsIfNeeded(&I);
02014 
02015   // Update successor info
02016   addSuccessorWithWeight(InvokeMBB, Return);
02017   addSuccessorWithWeight(InvokeMBB, LandingPad);
02018 
02019   // Drop into normal successor.
02020   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
02021                           MVT::Other, getControlRoot(),
02022                           DAG.getBasicBlock(Return)));
02023 }
02024 
02025 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
02026   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
02027 }
02028 
02029 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
02030   assert(FuncInfo.MBB->isLandingPad() &&
02031          "Call to landingpad not in landing pad!");
02032 
02033   MachineBasicBlock *MBB = FuncInfo.MBB;
02034   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
02035   AddLandingPadInfo(LP, MMI, MBB);
02036 
02037   // If there aren't registers to copy the values into (e.g., during SjLj
02038   // exceptions), then don't bother to create these DAG nodes.
02039   const TargetLowering *TLI = TM.getTargetLowering();
02040   if (TLI->getExceptionPointerRegister() == 0 &&
02041       TLI->getExceptionSelectorRegister() == 0)
02042     return;
02043 
02044   SmallVector<EVT, 2> ValueVTs;
02045   ComputeValueVTs(*TLI, LP.getType(), ValueVTs);
02046   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
02047 
02048   // Get the two live-in registers as SDValues. The physregs have already been
02049   // copied into virtual registers.
02050   SDValue Ops[2];
02051   Ops[0] = DAG.getZExtOrTrunc(
02052     DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
02053                        FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()),
02054     getCurSDLoc(), ValueVTs[0]);
02055   Ops[1] = DAG.getZExtOrTrunc(
02056     DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
02057                        FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()),
02058     getCurSDLoc(), ValueVTs[1]);
02059 
02060   // Merge into one.
02061   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
02062                             DAG.getVTList(ValueVTs),
02063                             &Ops[0], 2);
02064   setValue(&LP, Res);
02065 }
02066 
02067 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
02068 /// small case ranges).
02069 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
02070                                                  CaseRecVector& WorkList,
02071                                                  const Value* SV,
02072                                                  MachineBasicBlock *Default,
02073                                                  MachineBasicBlock *SwitchBB) {
02074   // Size is the number of Cases represented by this range.
02075   size_t Size = CR.Range.second - CR.Range.first;
02076   if (Size > 3)
02077     return false;
02078 
02079   // Get the MachineFunction which holds the current MBB.  This is used when
02080   // inserting any additional MBBs necessary to represent the switch.
02081   MachineFunction *CurMF = FuncInfo.MF;
02082 
02083   // Figure out which block is immediately after the current one.
02084   MachineBasicBlock *NextBlock = nullptr;
02085   MachineFunction::iterator BBI = CR.CaseBB;
02086 
02087   if (++BBI != FuncInfo.MF->end())
02088     NextBlock = BBI;
02089 
02090   BranchProbabilityInfo *BPI = FuncInfo.BPI;
02091   // If any two of the cases has the same destination, and if one value
02092   // is the same as the other, but has one bit unset that the other has set,
02093   // use bit manipulation to do two compares at once.  For example:
02094   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
02095   // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
02096   // TODO: Handle cases where CR.CaseBB != SwitchBB.
02097   if (Size == 2 && CR.CaseBB == SwitchBB) {
02098     Case &Small = *CR.Range.first;
02099     Case &Big = *(CR.Range.second-1);
02100 
02101     if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
02102       const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
02103       const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
02104 
02105       // Check that there is only one bit different.
02106       if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
02107           (SmallValue | BigValue) == BigValue) {
02108         // Isolate the common bit.
02109         APInt CommonBit = BigValue & ~SmallValue;
02110         assert((SmallValue | CommonBit) == BigValue &&
02111                CommonBit.countPopulation() == 1 && "Not a common bit?");
02112 
02113         SDValue CondLHS = getValue(SV);
02114         EVT VT = CondLHS.getValueType();
02115         SDLoc DL = getCurSDLoc();
02116 
02117         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
02118                                  DAG.getConstant(CommonBit, VT));
02119         SDValue Cond = DAG.getSetCC(DL, MVT::i1,
02120                                     Or, DAG.getConstant(BigValue, VT),
02121                                     ISD::SETEQ);
02122 
02123         // Update successor info.
02124         // Both Small and Big will jump to Small.BB, so we sum up the weights.
02125         addSuccessorWithWeight(SwitchBB, Small.BB,
02126                                Small.ExtraWeight + Big.ExtraWeight);
02127         addSuccessorWithWeight(SwitchBB, Default,
02128           // The default destination is the first successor in IR.
02129           BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
02130 
02131         // Insert the true branch.
02132         SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
02133                                      getControlRoot(), Cond,
02134                                      DAG.getBasicBlock(Small.BB));
02135 
02136         // Insert the false branch.
02137         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
02138                              DAG.getBasicBlock(Default));
02139 
02140         DAG.setRoot(BrCond);
02141         return true;
02142       }
02143     }
02144   }
02145 
02146   // Order cases by weight so the most likely case will be checked first.
02147   uint32_t UnhandledWeights = 0;
02148   if (BPI) {
02149     for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
02150       uint32_t IWeight = I->ExtraWeight;
02151       UnhandledWeights += IWeight;
02152       for (CaseItr J = CR.Range.first; J < I; ++J) {
02153         uint32_t JWeight = J->ExtraWeight;
02154         if (IWeight > JWeight)
02155           std::swap(*I, *J);
02156       }
02157     }
02158   }
02159   // Rearrange the case blocks so that the last one falls through if possible.
02160   Case &BackCase = *(CR.Range.second-1);
02161   if (Size > 1 &&
02162       NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
02163     // The last case block won't fall through into 'NextBlock' if we emit the
02164     // branches in this order.  See if rearranging a case value would help.
02165     // We start at the bottom as it's the case with the least weight.
02166     for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
02167       if (I->BB == NextBlock) {
02168         std::swap(*I, BackCase);
02169         break;
02170       }
02171   }
02172 
02173   // Create a CaseBlock record representing a conditional branch to
02174   // the Case's target mbb if the value being switched on SV is equal
02175   // to C.
02176   MachineBasicBlock *CurBlock = CR.CaseBB;
02177   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
02178     MachineBasicBlock *FallThrough;
02179     if (I != E-1) {
02180       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
02181       CurMF->insert(BBI, FallThrough);
02182 
02183       // Put SV in a virtual register to make it available from the new blocks.
02184       ExportFromCurrentBlock(SV);
02185     } else {
02186       // If the last case doesn't match, go to the default block.
02187       FallThrough = Default;
02188     }
02189 
02190     const Value *RHS, *LHS, *MHS;
02191     ISD::CondCode CC;
02192     if (I->High == I->Low) {
02193       // This is just small small case range :) containing exactly 1 case
02194       CC = ISD::SETEQ;
02195       LHS = SV; RHS = I->High; MHS = nullptr;
02196     } else {
02197       CC = ISD::SETLE;
02198       LHS = I->Low; MHS = SV; RHS = I->High;
02199     }
02200 
02201     // The false weight should be sum of all un-handled cases.
02202     UnhandledWeights -= I->ExtraWeight;
02203     CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
02204                  /* me */ CurBlock,
02205                  /* trueweight */ I->ExtraWeight,
02206                  /* falseweight */ UnhandledWeights);
02207 
02208     // If emitting the first comparison, just call visitSwitchCase to emit the
02209     // code into the current block.  Otherwise, push the CaseBlock onto the
02210     // vector to be later processed by SDISel, and insert the node's MBB
02211     // before the next MBB.
02212     if (CurBlock == SwitchBB)
02213       visitSwitchCase(CB, SwitchBB);
02214     else
02215       SwitchCases.push_back(CB);
02216 
02217     CurBlock = FallThrough;
02218   }
02219 
02220   return true;
02221 }
02222 
02223 static inline bool areJTsAllowed(const TargetLowering &TLI) {
02224   return TLI.supportJumpTables() &&
02225           (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
02226            TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
02227 }
02228 
02229 static APInt ComputeRange(const APInt &First, const APInt &Last) {
02230   uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
02231   APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
02232   return (LastExt - FirstExt + 1ULL);
02233 }
02234 
02235 /// handleJTSwitchCase - Emit jumptable for current switch case range
02236 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
02237                                              CaseRecVector &WorkList,
02238                                              const Value *SV,
02239                                              MachineBasicBlock *Default,
02240                                              MachineBasicBlock *SwitchBB) {
02241   Case& FrontCase = *CR.Range.first;
02242   Case& BackCase  = *(CR.Range.second-1);
02243 
02244   const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
02245   const APInt &Last  = cast<ConstantInt>(BackCase.High)->getValue();
02246 
02247   APInt TSize(First.getBitWidth(), 0);
02248   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
02249     TSize += I->size();
02250 
02251   const TargetLowering *TLI = TM.getTargetLowering();
02252   if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries()))
02253     return false;
02254 
02255   APInt Range = ComputeRange(First, Last);
02256   // The density is TSize / Range. Require at least 40%.
02257   // It should not be possible for IntTSize to saturate for sane code, but make
02258   // sure we handle Range saturation correctly.
02259   uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
02260   uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
02261   if (IntTSize * 10 < IntRange * 4)
02262     return false;
02263 
02264   DEBUG(dbgs() << "Lowering jump table\n"
02265                << "First entry: " << First << ". Last entry: " << Last << '\n'
02266                << "Range: " << Range << ". Size: " << TSize << ".\n\n");
02267 
02268   // Get the MachineFunction which holds the current MBB.  This is used when
02269   // inserting any additional MBBs necessary to represent the switch.
02270   MachineFunction *CurMF = FuncInfo.MF;
02271 
02272   // Figure out which block is immediately after the current one.
02273   MachineFunction::iterator BBI = CR.CaseBB;
02274   ++BBI;
02275 
02276   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
02277 
02278   // Create a new basic block to hold the code for loading the address
02279   // of the jump table, and jumping to it.  Update successor information;
02280   // we will either branch to the default case for the switch, or the jump
02281   // table.
02282   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
02283   CurMF->insert(BBI, JumpTableBB);
02284 
02285   addSuccessorWithWeight(CR.CaseBB, Default);
02286   addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
02287 
02288   // Build a vector of destination BBs, corresponding to each target
02289   // of the jump table. If the value of the jump table slot corresponds to
02290   // a case statement, push the case's BB onto the vector, otherwise, push
02291   // the default BB.
02292   std::vector<MachineBasicBlock*> DestBBs;
02293   APInt TEI = First;
02294   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
02295     const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
02296     const APInt &High = cast<ConstantInt>(I->High)->getValue();
02297 
02298     if (Low.sle(TEI) && TEI.sle(High)) {
02299       DestBBs.push_back(I->BB);
02300       if (TEI==High)
02301         ++I;
02302     } else {
02303       DestBBs.push_back(Default);
02304     }
02305   }
02306 
02307   // Calculate weight for each unique destination in CR.
02308   DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
02309   if (FuncInfo.BPI)
02310     for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
02311       DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
02312           DestWeights.find(I->BB);
02313       if (Itr != DestWeights.end())
02314         Itr->second += I->ExtraWeight;
02315       else
02316         DestWeights[I->BB] = I->ExtraWeight;
02317     }
02318 
02319   // Update successor info. Add one edge to each unique successor.
02320   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
02321   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
02322          E = DestBBs.end(); I != E; ++I) {
02323     if (!SuccsHandled[(*I)->getNumber()]) {
02324       SuccsHandled[(*I)->getNumber()] = true;
02325       DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
02326           DestWeights.find(*I);
02327       addSuccessorWithWeight(JumpTableBB, *I,
02328                              Itr != DestWeights.end() ? Itr->second : 0);
02329     }
02330   }
02331 
02332   // Create a jump table index for this jump table.
02333   unsigned JTEncoding = TLI->getJumpTableEncoding();
02334   unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
02335                        ->createJumpTableIndex(DestBBs);
02336 
02337   // Set the jump table information so that we can codegen it as a second
02338   // MachineBasicBlock
02339   JumpTable JT(-1U, JTI, JumpTableBB, Default);
02340   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
02341   if (CR.CaseBB == SwitchBB)
02342     visitJumpTableHeader(JT, JTH, SwitchBB);
02343 
02344   JTCases.push_back(JumpTableBlock(JTH, JT));
02345   return true;
02346 }
02347 
02348 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
02349 /// 2 subtrees.
02350 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
02351                                                   CaseRecVector& WorkList,
02352                                                   const Value* SV,
02353                                                   MachineBasicBlock* Default,
02354                                                   MachineBasicBlock* SwitchBB) {
02355   // Get the MachineFunction which holds the current MBB.  This is used when
02356   // inserting any additional MBBs necessary to represent the switch.
02357   MachineFunction *CurMF = FuncInfo.MF;
02358 
02359   // Figure out which block is immediately after the current one.
02360   MachineFunction::iterator BBI = CR.CaseBB;
02361   ++BBI;
02362 
02363   Case& FrontCase = *CR.Range.first;
02364   Case& BackCase  = *(CR.Range.second-1);
02365   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
02366 
02367   // Size is the number of Cases represented by this range.
02368   unsigned Size = CR.Range.second - CR.Range.first;
02369 
02370   const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
02371   const APInt &Last  = cast<ConstantInt>(BackCase.High)->getValue();
02372   double FMetric = 0;
02373   CaseItr Pivot = CR.Range.first + Size/2;
02374 
02375   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
02376   // (heuristically) allow us to emit JumpTable's later.
02377   APInt TSize(First.getBitWidth(), 0);
02378   for (CaseItr I = CR.Range.first, E = CR.Range.second;
02379        I!=E; ++I)
02380     TSize += I->size();
02381 
02382   APInt LSize = FrontCase.size();
02383   APInt RSize = TSize-LSize;
02384   DEBUG(dbgs() << "Selecting best pivot: \n"
02385                << "First: " << First << ", Last: " << Last <<'\n'
02386                << "LSize: " << LSize << ", RSize: " << RSize << '\n');
02387   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
02388        J!=E; ++I, ++J) {
02389     const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
02390     const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
02391     APInt Range = ComputeRange(LEnd, RBegin);
02392     assert((Range - 2ULL).isNonNegative() &&
02393            "Invalid case distance");
02394     // Use volatile double here to avoid excess precision issues on some hosts,
02395     // e.g. that use 80-bit X87 registers.
02396     volatile double LDensity =
02397        (double)LSize.roundToDouble() /
02398                            (LEnd - First + 1ULL).roundToDouble();
02399     volatile double RDensity =
02400       (double)RSize.roundToDouble() /
02401                            (Last - RBegin + 1ULL).roundToDouble();
02402     volatile double Metric = Range.logBase2()*(LDensity+RDensity);
02403     // Should always split in some non-trivial place
02404     DEBUG(dbgs() <<"=>Step\n"
02405                  << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
02406                  << "LDensity: " << LDensity
02407                  << ", RDensity: " << RDensity << '\n'
02408                  << "Metric: " << Metric << '\n');
02409     if (FMetric < Metric) {
02410       Pivot = J;
02411       FMetric = Metric;
02412       DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
02413     }
02414 
02415     LSize += J->size();
02416     RSize -= J->size();
02417   }
02418 
02419   const TargetLowering *TLI = TM.getTargetLowering();
02420   if (areJTsAllowed(*TLI)) {
02421     // If our case is dense we *really* should handle it earlier!
02422     assert((FMetric > 0) && "Should handle dense range earlier!");
02423   } else {
02424     Pivot = CR.Range.first + Size/2;
02425   }
02426 
02427   CaseRange LHSR(CR.Range.first, Pivot);
02428   CaseRange RHSR(Pivot, CR.Range.second);
02429   const Constant *C = Pivot->Low;
02430   MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
02431 
02432   // We know that we branch to the LHS if the Value being switched on is
02433   // less than the Pivot value, C.  We use this to optimize our binary
02434   // tree a bit, by recognizing that if SV is greater than or equal to the
02435   // LHS's Case Value, and that Case Value is exactly one less than the
02436   // Pivot's Value, then we can branch directly to the LHS's Target,
02437   // rather than creating a leaf node for it.
02438   if ((LHSR.second - LHSR.first) == 1 &&
02439       LHSR.first->High == CR.GE &&
02440       cast<ConstantInt>(C)->getValue() ==
02441       (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
02442     TrueBB = LHSR.first->BB;
02443   } else {
02444     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
02445     CurMF->insert(BBI, TrueBB);
02446     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
02447 
02448     // Put SV in a virtual register to make it available from the new blocks.
02449     ExportFromCurrentBlock(SV);
02450   }
02451 
02452   // Similar to the optimization above, if the Value being switched on is
02453   // known to be less than the Constant CR.LT, and the current Case Value
02454   // is CR.LT - 1, then we can branch directly to the target block for
02455   // the current Case Value, rather than emitting a RHS leaf node for it.
02456   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
02457       cast<ConstantInt>(RHSR.first->Low)->getValue() ==
02458       (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
02459     FalseBB = RHSR.first->BB;
02460   } else {
02461     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
02462     CurMF->insert(BBI, FalseBB);
02463     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
02464 
02465     // Put SV in a virtual register to make it available from the new blocks.
02466     ExportFromCurrentBlock(SV);
02467   }
02468 
02469   // Create a CaseBlock record representing a conditional branch to
02470   // the LHS node if the value being switched on SV is less than C.
02471   // Otherwise, branch to LHS.
02472   CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
02473 
02474   if (CR.CaseBB == SwitchBB)
02475     visitSwitchCase(CB, SwitchBB);
02476   else
02477     SwitchCases.push_back(CB);
02478 
02479   return true;
02480 }
02481 
02482 /// handleBitTestsSwitchCase - if current case range has few destination and
02483 /// range span less, than machine word bitwidth, encode case range into series
02484 /// of masks and emit bit tests with these masks.
02485 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
02486                                                    CaseRecVector& WorkList,
02487                                                    const Value* SV,
02488                                                    MachineBasicBlock* Default,
02489                                                    MachineBasicBlock* SwitchBB) {
02490   const TargetLowering *TLI = TM.getTargetLowering();
02491   EVT PTy = TLI->getPointerTy();
02492   unsigned IntPtrBits = PTy.getSizeInBits();
02493 
02494   Case& FrontCase = *CR.Range.first;
02495   Case& BackCase  = *(CR.Range.second-1);
02496 
02497   // Get the MachineFunction which holds the current MBB.  This is used when
02498   // inserting any additional MBBs necessary to represent the switch.
02499   MachineFunction *CurMF = FuncInfo.MF;
02500 
02501   // If target does not have legal shift left, do not emit bit tests at all.
02502   if (!TLI->isOperationLegal(ISD::SHL, PTy))
02503     return false;
02504 
02505   size_t numCmps = 0;
02506   for (CaseItr I = CR.Range.first, E = CR.Range.second;
02507        I!=E; ++I) {
02508     // Single case counts one, case range - two.
02509     numCmps += (I->Low == I->High ? 1 : 2);
02510   }
02511 
02512   // Count unique destinations
02513   SmallSet<MachineBasicBlock*, 4> Dests;
02514   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
02515     Dests.insert(I->BB);
02516     if (Dests.size() > 3)
02517       // Don't bother the code below, if there are too much unique destinations
02518       return false;
02519   }
02520   DEBUG(dbgs() << "Total number of unique destinations: "
02521         << Dests.size() << '\n'
02522         << "Total number of comparisons: " << numCmps << '\n');
02523 
02524   // Compute span of values.
02525   const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
02526   const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
02527   APInt cmpRange = maxValue - minValue;
02528 
02529   DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
02530                << "Low bound: " << minValue << '\n'
02531                << "High bound: " << maxValue << '\n');
02532 
02533   if (cmpRange.uge(IntPtrBits) ||
02534       (!(Dests.size() == 1 && numCmps >= 3) &&
02535        !(Dests.size() == 2 && numCmps >= 5) &&
02536        !(Dests.size() >= 3 && numCmps >= 6)))
02537     return false;
02538 
02539   DEBUG(dbgs() << "Emitting bit tests\n");
02540   APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
02541 
02542   // Optimize the case where all the case values fit in a
02543   // word without having to subtract minValue. In this case,
02544   // we can optimize away the subtraction.
02545   if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
02546     cmpRange = maxValue;
02547   } else {
02548     lowBound = minValue;
02549   }
02550 
02551   CaseBitsVector CasesBits;
02552   unsigned i, count = 0;
02553 
02554   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
02555     MachineBasicBlock* Dest = I->BB;
02556     for (i = 0; i < count; ++i)
02557       if (Dest == CasesBits[i].BB)
02558         break;
02559 
02560     if (i == count) {
02561       assert((count < 3) && "Too much destinations to test!");
02562       CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
02563       count++;
02564     }
02565 
02566     const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
02567     const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
02568 
02569     uint64_t lo = (lowValue - lowBound).getZExtValue();
02570     uint64_t hi = (highValue - lowBound).getZExtValue();
02571     CasesBits[i].ExtraWeight += I->ExtraWeight;
02572 
02573     for (uint64_t j = lo; j <= hi; j++) {
02574       CasesBits[i].Mask |=  1ULL << j;
02575       CasesBits[i].Bits++;
02576     }
02577 
02578   }
02579   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
02580 
02581   BitTestInfo BTC;
02582 
02583   // Figure out which block is immediately after the current one.
02584   MachineFunction::iterator BBI = CR.CaseBB;
02585   ++BBI;
02586 
02587   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
02588 
02589   DEBUG(dbgs() << "Cases:\n");
02590   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
02591     DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
02592                  << ", Bits: " << CasesBits[i].Bits
02593                  << ", BB: " << CasesBits[i].BB << '\n');
02594 
02595     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
02596     CurMF->insert(BBI, CaseBB);
02597     BTC.push_back(BitTestCase(CasesBits[i].Mask,
02598                               CaseBB,
02599                               CasesBits[i].BB, CasesBits[i].ExtraWeight));
02600 
02601     // Put SV in a virtual register to make it available from the new blocks.
02602     ExportFromCurrentBlock(SV);
02603   }
02604 
02605   BitTestBlock BTB(lowBound, cmpRange, SV,
02606                    -1U, MVT::Other, (CR.CaseBB == SwitchBB),
02607                    CR.CaseBB, Default, BTC);
02608 
02609   if (CR.CaseBB == SwitchBB)
02610     visitBitTestHeader(BTB, SwitchBB);
02611 
02612   BitTestCases.push_back(BTB);
02613 
02614   return true;
02615 }
02616 
02617 /// Clusterify - Transform simple list of Cases into list of CaseRange's
02618 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
02619                                        const SwitchInst& SI) {
02620   size_t numCmps = 0;
02621 
02622   BranchProbabilityInfo *BPI = FuncInfo.BPI;
02623   // Start with "simple" cases
02624   for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
02625        i != e; ++i) {
02626     const BasicBlock *SuccBB = i.getCaseSuccessor();
02627     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
02628 
02629     uint32_t ExtraWeight =
02630       BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
02631 
02632     Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
02633                          SMBB, ExtraWeight));
02634   }
02635   std::sort(Cases.begin(), Cases.end(), CaseCmp());
02636 
02637   // Merge case into clusters
02638   if (Cases.size() >= 2)
02639     // Must recompute end() each iteration because it may be
02640     // invalidated by erase if we hold on to it
02641     for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
02642          J != Cases.end(); ) {
02643       const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
02644       const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
02645       MachineBasicBlock* nextBB = J->BB;
02646       MachineBasicBlock* currentBB = I->BB;
02647 
02648       // If the two neighboring cases go to the same destination, merge them
02649       // into a single case.
02650       if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
02651         I->High = J->High;
02652         I->ExtraWeight += J->ExtraWeight;
02653         J = Cases.erase(J);
02654       } else {
02655         I = J++;
02656       }
02657     }
02658 
02659   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
02660     if (I->Low != I->High)
02661       // A range counts double, since it requires two compares.
02662       ++numCmps;
02663   }
02664 
02665   return numCmps;
02666 }
02667 
02668 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
02669                                            MachineBasicBlock *Last) {
02670   // Update JTCases.
02671   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
02672     if (JTCases[i].first.HeaderBB == First)
02673       JTCases[i].first.HeaderBB = Last;
02674 
02675   // Update BitTestCases.
02676   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
02677     if (BitTestCases[i].Parent == First)
02678       BitTestCases[i].Parent = Last;
02679 }
02680 
02681 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
02682   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
02683 
02684   // Figure out which block is immediately after the current one.
02685   MachineBasicBlock *NextBlock = nullptr;
02686   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
02687 
02688   // If there is only the default destination, branch to it if it is not the
02689   // next basic block.  Otherwise, just fall through.
02690   if (!SI.getNumCases()) {
02691     // Update machine-CFG edges.
02692 
02693     // If this is not a fall-through branch, emit the branch.
02694     SwitchMBB->addSuccessor(Default);
02695     if (Default != NextBlock)
02696       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
02697                               MVT::Other, getControlRoot(),
02698                               DAG.getBasicBlock(Default)));
02699 
02700     return;
02701   }
02702 
02703   // If there are any non-default case statements, create a vector of Cases
02704   // representing each one, and sort the vector so that we can efficiently
02705   // create a binary search tree from them.
02706   CaseVector Cases;
02707   size_t numCmps = Clusterify(Cases, SI);
02708   DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
02709                << ". Total compares: " << numCmps << '\n');
02710   (void)numCmps;
02711 
02712   // Get the Value to be switched on and default basic blocks, which will be
02713   // inserted into CaseBlock records, representing basic blocks in the binary
02714   // search tree.
02715   const Value *SV = SI.getCondition();
02716 
02717   // Push the initial CaseRec onto the worklist
02718   CaseRecVector WorkList;
02719   WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
02720                              CaseRange(Cases.begin(),Cases.end())));
02721 
02722   while (!WorkList.empty()) {
02723     // Grab a record representing a case range to process off the worklist
02724     CaseRec CR = WorkList.back();
02725     WorkList.pop_back();
02726 
02727     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
02728       continue;
02729 
02730     // If the range has few cases (two or less) emit a series of specific
02731     // tests.
02732     if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
02733       continue;
02734 
02735     // If the switch has more than N blocks, and is at least 40% dense, and the
02736     // target supports indirect branches, then emit a jump table rather than
02737     // lowering the switch to a binary tree of conditional branches.
02738     // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
02739     if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
02740       continue;
02741 
02742     // Emit binary tree. We need to pick a pivot, and push left and right ranges
02743     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
02744     handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
02745   }
02746 }
02747 
02748 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
02749   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
02750 
02751   // Update machine-CFG edges with unique successors.
02752   SmallSet<BasicBlock*, 32> Done;
02753   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
02754     BasicBlock *BB = I.getSuccessor(i);
02755     bool Inserted = Done.insert(BB);
02756     if (!Inserted)
02757         continue;
02758 
02759     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
02760     addSuccessorWithWeight(IndirectBrMBB, Succ);
02761   }
02762 
02763   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
02764                           MVT::Other, getControlRoot(),
02765                           getValue(I.getAddress())));
02766 }
02767 
02768 void SelectionDAGBuilder::visitFSub(const User &I) {
02769   // -0.0 - X --> fneg
02770   Type *Ty = I.getType();
02771   if (isa<Constant>(I.getOperand(0)) &&
02772       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
02773     SDValue Op2 = getValue(I.getOperand(1));
02774     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
02775                              Op2.getValueType(), Op2));
02776     return;
02777   }
02778 
02779   visitBinary(I, ISD::FSUB);
02780 }
02781 
02782 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
02783   SDValue Op1 = getValue(I.getOperand(0));
02784   SDValue Op2 = getValue(I.getOperand(1));
02785   setValue(&I, DAG.getNode(OpCode, getCurSDLoc(),
02786                            Op1.getValueType(), Op1, Op2));
02787 }
02788 
02789 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
02790   SDValue Op1 = getValue(I.getOperand(0));
02791   SDValue Op2 = getValue(I.getOperand(1));
02792 
02793   EVT ShiftTy = TM.getTargetLowering()->getShiftAmountTy(Op2.getValueType());
02794 
02795   // Coerce the shift amount to the right type if we can.
02796   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
02797     unsigned ShiftSize = ShiftTy.getSizeInBits();
02798     unsigned Op2Size = Op2.getValueType().getSizeInBits();
02799     SDLoc DL = getCurSDLoc();
02800 
02801     // If the operand is smaller than the shift count type, promote it.
02802     if (ShiftSize > Op2Size)
02803       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
02804 
02805     // If the operand is larger than the shift count type but the shift
02806     // count type has enough bits to represent any shift value, truncate
02807     // it now. This is a common case and it exposes the truncate to
02808     // optimization early.
02809     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
02810       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
02811     // Otherwise we'll need to temporarily settle for some other convenient
02812     // type.  Type legalization will make adjustments once the shiftee is split.
02813     else
02814       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
02815   }
02816 
02817   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(),
02818                            Op1.getValueType(), Op1, Op2));
02819 }
02820 
02821 void SelectionDAGBuilder::visitSDiv(const User &I) {
02822   SDValue Op1 = getValue(I.getOperand(0));
02823   SDValue Op2 = getValue(I.getOperand(1));
02824 
02825   // Turn exact SDivs into multiplications.
02826   // FIXME: This should be in DAGCombiner, but it doesn't have access to the
02827   // exact bit.
02828   if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
02829       !isa<ConstantSDNode>(Op1) &&
02830       isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
02831     setValue(&I, TM.getTargetLowering()->BuildExactSDIV(Op1, Op2,
02832                                                         getCurSDLoc(), DAG));
02833   else
02834     setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
02835                              Op1, Op2));
02836 }
02837 
02838 void SelectionDAGBuilder::visitICmp(const User &I) {
02839   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
02840   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
02841     predicate = IC->getPredicate();
02842   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
02843     predicate = ICmpInst::Predicate(IC->getPredicate());
02844   SDValue Op1 = getValue(I.getOperand(0));
02845   SDValue Op2 = getValue(I.getOperand(1));
02846   ISD::CondCode Opcode = getICmpCondCode(predicate);
02847 
02848   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02849   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
02850 }
02851 
02852 void SelectionDAGBuilder::visitFCmp(const User &I) {
02853   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
02854   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
02855     predicate = FC->getPredicate();
02856   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
02857     predicate = FCmpInst::Predicate(FC->getPredicate());
02858   SDValue Op1 = getValue(I.getOperand(0));
02859   SDValue Op2 = getValue(I.getOperand(1));
02860   ISD::CondCode Condition = getFCmpCondCode(predicate);
02861   if (TM.Options.NoNaNsFPMath)
02862     Condition = getFCmpCodeWithoutNaN(Condition);
02863   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02864   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
02865 }
02866 
02867 void SelectionDAGBuilder::visitSelect(const User &I) {
02868   SmallVector<EVT, 4> ValueVTs;
02869   ComputeValueVTs(*TM.getTargetLowering(), I.getType(), ValueVTs);
02870   unsigned NumValues = ValueVTs.size();
02871   if (NumValues == 0) return;
02872 
02873   SmallVector<SDValue, 4> Values(NumValues);
02874   SDValue Cond     = getValue(I.getOperand(0));
02875   SDValue TrueVal  = getValue(I.getOperand(1));
02876   SDValue FalseVal = getValue(I.getOperand(2));
02877   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
02878     ISD::VSELECT : ISD::SELECT;
02879 
02880   for (unsigned i = 0; i != NumValues; ++i)
02881     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
02882                             TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
02883                             Cond,
02884                             SDValue(TrueVal.getNode(),
02885                                     TrueVal.getResNo() + i),
02886                             SDValue(FalseVal.getNode(),
02887                                     FalseVal.getResNo() + i));
02888 
02889   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
02890                            DAG.getVTList(ValueVTs),
02891                            &Values[0], NumValues));
02892 }
02893 
02894 void SelectionDAGBuilder::visitTrunc(const User &I) {
02895   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
02896   SDValue N = getValue(I.getOperand(0));
02897   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02898   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
02899 }
02900 
02901 void SelectionDAGBuilder::visitZExt(const User &I) {
02902   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
02903   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
02904   SDValue N = getValue(I.getOperand(0));
02905   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02906   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
02907 }
02908 
02909 void SelectionDAGBuilder::visitSExt(const User &I) {
02910   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
02911   // SExt also can't be a cast to bool for same reason. So, nothing much to do
02912   SDValue N = getValue(I.getOperand(0));
02913   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02914   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
02915 }
02916 
02917 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
02918   // FPTrunc is never a no-op cast, no need to check
02919   SDValue N = getValue(I.getOperand(0));
02920   const TargetLowering *TLI = TM.getTargetLowering();
02921   EVT DestVT = TLI->getValueType(I.getType());
02922   setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(),
02923                            DestVT, N,
02924                            DAG.getTargetConstant(0, TLI->getPointerTy())));
02925 }
02926 
02927 void SelectionDAGBuilder::visitFPExt(const User &I) {
02928   // FPExt is never a no-op cast, no need to check
02929   SDValue N = getValue(I.getOperand(0));
02930   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02931   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
02932 }
02933 
02934 void SelectionDAGBuilder::visitFPToUI(const User &I) {
02935   // FPToUI is never a no-op cast, no need to check
02936   SDValue N = getValue(I.getOperand(0));
02937   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02938   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
02939 }
02940 
02941 void SelectionDAGBuilder::visitFPToSI(const User &I) {
02942   // FPToSI is never a no-op cast, no need to check
02943   SDValue N = getValue(I.getOperand(0));
02944   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02945   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
02946 }
02947 
02948 void SelectionDAGBuilder::visitUIToFP(const User &I) {
02949   // UIToFP is never a no-op cast, no need to check
02950   SDValue N = getValue(I.getOperand(0));
02951   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02952   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
02953 }
02954 
02955 void SelectionDAGBuilder::visitSIToFP(const User &I) {
02956   // SIToFP is never a no-op cast, no need to check
02957   SDValue N = getValue(I.getOperand(0));
02958   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02959   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
02960 }
02961 
02962 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
02963   // What to do depends on the size of the integer and the size of the pointer.
02964   // We can either truncate, zero extend, or no-op, accordingly.
02965   SDValue N = getValue(I.getOperand(0));
02966   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02967   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
02968 }
02969 
02970 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
02971   // What to do depends on the size of the integer and the size of the pointer.
02972   // We can either truncate, zero extend, or no-op, accordingly.
02973   SDValue N = getValue(I.getOperand(0));
02974   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02975   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
02976 }
02977 
02978 void SelectionDAGBuilder::visitBitCast(const User &I) {
02979   SDValue N = getValue(I.getOperand(0));
02980   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
02981 
02982   // BitCast assures us that source and destination are the same size so this is
02983   // either a BITCAST or a no-op.
02984   if (DestVT != N.getValueType())
02985     setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
02986                              DestVT, N)); // convert types.
02987   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
02988   // might fold any kind of constant expression to an integer constant and that
02989   // is not what we are looking for. Only regcognize a bitcast of a genuine
02990   // constant integer as an opaque constant.
02991   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
02992     setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
02993                                  /*isOpaque*/true));
02994   else
02995     setValue(&I, N);            // noop cast.
02996 }
02997 
02998 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
02999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03000   const Value *SV = I.getOperand(0);
03001   SDValue N = getValue(SV);
03002   EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
03003 
03004   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
03005   unsigned DestAS = I.getType()->getPointerAddressSpace();
03006 
03007   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
03008     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
03009 
03010   setValue(&I, N);
03011 }
03012 
03013 void SelectionDAGBuilder::visitInsertElement(const User &I) {
03014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03015   SDValue InVec = getValue(I.getOperand(0));
03016   SDValue InVal = getValue(I.getOperand(1));
03017   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
03018                                      getCurSDLoc(), TLI.getVectorIdxTy());
03019   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
03020                            TM.getTargetLowering()->getValueType(I.getType()),
03021                            InVec, InVal, InIdx));
03022 }
03023 
03024 void SelectionDAGBuilder::visitExtractElement(const User &I) {
03025   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03026   SDValue InVec = getValue(I.getOperand(0));
03027   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
03028                                      getCurSDLoc(), TLI.getVectorIdxTy());
03029   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
03030                            TM.getTargetLowering()->getValueType(I.getType()),
03031                            InVec, InIdx));
03032 }
03033 
03034 // Utility for visitShuffleVector - Return true if every element in Mask,
03035 // beginning from position Pos and ending in Pos+Size, falls within the
03036 // specified sequential range [L, L+Pos). or is undef.
03037 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
03038                                 unsigned Pos, unsigned Size, int Low) {
03039   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
03040     if (Mask[i] >= 0 && Mask[i] != Low)
03041       return false;
03042   return true;
03043 }
03044 
03045 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
03046   SDValue Src1 = getValue(I.getOperand(0));
03047   SDValue Src2 = getValue(I.getOperand(1));
03048 
03049   SmallVector<int, 8> Mask;
03050   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
03051   unsigned MaskNumElts = Mask.size();
03052 
03053   const TargetLowering *TLI = TM.getTargetLowering();
03054   EVT VT = TLI->getValueType(I.getType());
03055   EVT SrcVT = Src1.getValueType();
03056   unsigned SrcNumElts = SrcVT.getVectorNumElements();
03057 
03058   if (SrcNumElts == MaskNumElts) {
03059     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
03060                                       &Mask[0]));
03061     return;
03062   }
03063 
03064   // Normalize the shuffle vector since mask and vector length don't match.
03065   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
03066     // Mask is longer than the source vectors and is a multiple of the source
03067     // vectors.  We can use concatenate vector to make the mask and vectors
03068     // lengths match.
03069     if (SrcNumElts*2 == MaskNumElts) {
03070       // First check for Src1 in low and Src2 in high
03071       if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
03072           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
03073         // The shuffle is concatenating two vectors together.
03074         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
03075                                  VT, Src1, Src2));
03076         return;
03077       }
03078       // Then check for Src2 in low and Src1 in high
03079       if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
03080           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
03081         // The shuffle is concatenating two vectors together.
03082         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
03083                                  VT, Src2, Src1));
03084         return;
03085       }
03086     }
03087 
03088     // Pad both vectors with undefs to make them the same length as the mask.
03089     unsigned NumConcat = MaskNumElts / SrcNumElts;
03090     bool Src1U = Src1.getOpcode() == ISD::UNDEF;
03091     bool Src2U = Src2.getOpcode() == ISD::UNDEF;
03092     SDValue UndefVal = DAG.getUNDEF(SrcVT);
03093 
03094     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
03095     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
03096     MOps1[0] = Src1;
03097     MOps2[0] = Src2;
03098 
03099     Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
03100                                                   getCurSDLoc(), VT,
03101                                                   &MOps1[0], NumConcat);
03102     Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
03103                                                   getCurSDLoc(), VT,
03104                                                   &MOps2[0], NumConcat);
03105 
03106     // Readjust mask for new input vector length.
03107     SmallVector<int, 8> MappedOps;
03108     for (unsigned i = 0; i != MaskNumElts; ++i) {
03109       int Idx = Mask[i];
03110       if (Idx >= (int)SrcNumElts)
03111         Idx -= SrcNumElts - MaskNumElts;
03112       MappedOps.push_back(Idx);
03113     }
03114 
03115     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
03116                                       &MappedOps[0]));
03117     return;
03118   }
03119 
03120   if (SrcNumElts > MaskNumElts) {
03121     // Analyze the access pattern of the vector to see if we can extract
03122     // two subvectors and do the shuffle. The analysis is done by calculating
03123     // the range of elements the mask access on both vectors.
03124     int MinRange[2] = { static_cast<int>(SrcNumElts),
03125                         static_cast<int>(SrcNumElts)};
03126     int MaxRange[2] = {-1, -1};
03127 
03128     for (unsigned i = 0; i != MaskNumElts; ++i) {
03129       int Idx = Mask[i];
03130       unsigned Input = 0;
03131       if (Idx < 0)
03132         continue;
03133 
03134       if (Idx >= (int)SrcNumElts) {
03135         Input = 1;
03136         Idx -= SrcNumElts;
03137       }
03138       if (Idx > MaxRange[Input])
03139         MaxRange[Input] = Idx;
03140       if (Idx < MinRange[Input])
03141         MinRange[Input] = Idx;
03142     }
03143 
03144     // Check if the access is smaller than the vector size and can we find
03145     // a reasonable extract index.
03146     int RangeUse[2] = { -1, -1 };  // 0 = Unused, 1 = Extract, -1 = Can not
03147                                    // Extract.
03148     int StartIdx[2];  // StartIdx to extract from
03149     for (unsigned Input = 0; Input < 2; ++Input) {
03150       if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
03151         RangeUse[Input] = 0; // Unused
03152         StartIdx[Input] = 0;
03153         continue;
03154       }
03155 
03156       // Find a good start index that is a multiple of the mask length. Then
03157       // see if the rest of the elements are in range.
03158       StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
03159       if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
03160           StartIdx[Input] + MaskNumElts <= SrcNumElts)
03161         RangeUse[Input] = 1; // Extract from a multiple of the mask length.
03162     }
03163 
03164     if (RangeUse[0] == 0 && RangeUse[1] == 0) {
03165       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
03166       return;
03167     }
03168     if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
03169       // Extract appropriate subvector and generate a vector shuffle
03170       for (unsigned Input = 0; Input < 2; ++Input) {
03171         SDValue &Src = Input == 0 ? Src1 : Src2;
03172         if (RangeUse[Input] == 0)
03173           Src = DAG.getUNDEF(VT);
03174         else
03175           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT,
03176                             Src, DAG.getConstant(StartIdx[Input],
03177                                                  TLI->getVectorIdxTy()));
03178       }
03179 
03180       // Calculate new mask.
03181       SmallVector<int, 8> MappedOps;
03182       for (unsigned i = 0; i != MaskNumElts; ++i) {
03183         int Idx = Mask[i];
03184         if (Idx >= 0) {
03185           if (Idx < (int)SrcNumElts)
03186             Idx -= StartIdx[0];
03187           else
03188             Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
03189         }
03190         MappedOps.push_back(Idx);
03191       }
03192 
03193       setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
03194                                         &MappedOps[0]));
03195       return;
03196     }
03197   }
03198 
03199   // We can't use either concat vectors or extract subvectors so fall back to
03200   // replacing the shuffle with extract and build vector.
03201   // to insert and build vector.
03202   EVT EltVT = VT.getVectorElementType();
03203   EVT IdxVT = TLI->getVectorIdxTy();
03204   SmallVector<SDValue,8> Ops;
03205   for (unsigned i = 0; i != MaskNumElts; ++i) {
03206     int Idx = Mask[i];
03207     SDValue Res;
03208 
03209     if (Idx < 0) {
03210       Res = DAG.getUNDEF(EltVT);
03211     } else {
03212       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
03213       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
03214 
03215       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
03216                         EltVT, Src, DAG.getConstant(Idx, IdxVT));
03217     }
03218 
03219     Ops.push_back(Res);
03220   }
03221 
03222   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
03223                            VT, &Ops[0], Ops.size()));
03224 }
03225 
03226 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
03227   const Value *Op0 = I.getOperand(0);
03228   const Value *Op1 = I.getOperand(1);
03229   Type *AggTy = I.getType();
03230   Type *ValTy = Op1->getType();
03231   bool IntoUndef = isa<UndefValue>(Op0);
03232   bool FromUndef = isa<UndefValue>(Op1);
03233 
03234   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
03235 
03236   const TargetLowering *TLI = TM.getTargetLowering();
03237   SmallVector<EVT, 4> AggValueVTs;
03238   ComputeValueVTs(*TLI, AggTy, AggValueVTs);
03239   SmallVector<EVT, 4> ValValueVTs;
03240   ComputeValueVTs(*TLI, ValTy, ValValueVTs);
03241 
03242   unsigned NumAggValues = AggValueVTs.size();
03243   unsigned NumValValues = ValValueVTs.size();
03244   SmallVector<SDValue, 4> Values(NumAggValues);
03245 
03246   SDValue Agg = getValue(Op0);
03247   unsigned i = 0;
03248   // Copy the beginning value(s) from the original aggregate.
03249   for (; i != LinearIndex; ++i)
03250     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
03251                 SDValue(Agg.getNode(), Agg.getResNo() + i);
03252   // Copy values from the inserted value(s).
03253   if (NumValValues) {
03254     SDValue Val = getValue(Op1);
03255     for (; i != LinearIndex + NumValValues; ++i)
03256       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
03257                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
03258   }
03259   // Copy remaining value(s) from the original aggregate.
03260   for (; i != NumAggValues; ++i)
03261     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
03262                 SDValue(Agg.getNode(), Agg.getResNo() + i);
03263 
03264   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
03265                            DAG.getVTList(AggValueVTs),
03266                            &Values[0], NumAggValues));
03267 }
03268 
03269 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
03270   const Value *Op0 = I.getOperand(0);
03271   Type *AggTy = Op0->getType();
03272   Type *ValTy = I.getType();
03273   bool OutOfUndef = isa<UndefValue>(Op0);
03274 
03275   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
03276 
03277   const TargetLowering *TLI = TM.getTargetLowering();
03278   SmallVector<EVT, 4> ValValueVTs;
03279   ComputeValueVTs(*TLI, ValTy, ValValueVTs);
03280 
03281   unsigned NumValValues = ValValueVTs.size();
03282 
03283   // Ignore a extractvalue that produces an empty object
03284   if (!NumValValues) {
03285     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
03286     return;
03287   }
03288 
03289   SmallVector<SDValue, 4> Values(NumValValues);
03290 
03291   SDValue Agg = getValue(Op0);
03292   // Copy out the selected value(s).
03293   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
03294     Values[i - LinearIndex] =
03295       OutOfUndef ?
03296         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
03297         SDValue(Agg.getNode(), Agg.getResNo() + i);
03298 
03299   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
03300                            DAG.getVTList(ValValueVTs),
03301                            &Values[0], NumValValues));
03302 }
03303 
03304 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
03305   Value *Op0 = I.getOperand(0);
03306   // Note that the pointer operand may be a vector of pointers. Take the scalar
03307   // element which holds a pointer.
03308   Type *Ty = Op0->getType()->getScalarType();
03309   unsigned AS = Ty->getPointerAddressSpace();
03310   SDValue N = getValue(Op0);
03311 
03312   for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
03313        OI != E; ++OI) {
03314     const Value *Idx = *OI;
03315     if (StructType *StTy = dyn_cast<StructType>(Ty)) {
03316       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
03317       if (Field) {
03318         // N = N + Offset
03319         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
03320         N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
03321                         DAG.getConstant(Offset, N.getValueType()));
03322       }
03323 
03324       Ty = StTy->getElementType(Field);
03325     } else {
03326       Ty = cast<SequentialType>(Ty)->getElementType();
03327 
03328       // If this is a constant subscript, handle it quickly.
03329       const TargetLowering *TLI = TM.getTargetLowering();
03330       if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
03331         if (CI->isZero()) continue;
03332         uint64_t Offs =
03333             DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
03334         SDValue OffsVal;
03335         EVT PTy = TLI->getPointerTy(AS);
03336         unsigned PtrBits = PTy.getSizeInBits();
03337         if (PtrBits < 64)
03338           OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
03339                                 DAG.getConstant(Offs, MVT::i64));
03340         else
03341           OffsVal = DAG.getConstant(Offs, PTy);
03342 
03343         N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
03344                         OffsVal);
03345         continue;
03346       }
03347 
03348       // N = N + Idx * ElementSize;
03349       APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS),
03350                                 DL->getTypeAllocSize(Ty));
03351       SDValue IdxN = getValue(Idx);
03352 
03353       // If the index is smaller or larger than intptr_t, truncate or extend
03354       // it.
03355       IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
03356 
03357       // If this is a multiply by a power of two, turn it into a shl
03358       // immediately.  This is a very common case.
03359       if (ElementSize != 1) {
03360         if (ElementSize.isPowerOf2()) {
03361           unsigned Amt = ElementSize.logBase2();
03362           IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
03363                              N.getValueType(), IdxN,
03364                              DAG.getConstant(Amt, IdxN.getValueType()));
03365         } else {
03366           SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
03367           IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
03368                              N.getValueType(), IdxN, Scale);
03369         }
03370       }
03371 
03372       N = DAG.getNode(ISD::ADD, getCurSDLoc(),
03373                       N.getValueType(), N, IdxN);
03374     }
03375   }
03376 
03377   setValue(&I, N);
03378 }
03379 
03380 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
03381   // If this is a fixed sized alloca in the entry block of the function,
03382   // allocate it statically on the stack.
03383   if (FuncInfo.StaticAllocaMap.count(&I))
03384     return;   // getValue will auto-populate this.
03385 
03386   Type *Ty = I.getAllocatedType();
03387   const TargetLowering *TLI = TM.getTargetLowering();
03388   uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
03389   unsigned Align =
03390     std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
03391              I.getAlignment());
03392 
03393   SDValue AllocSize = getValue(I.getArraySize());
03394 
03395   EVT IntPtr = TLI->getPointerTy();
03396   if (AllocSize.getValueType() != IntPtr)
03397     AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
03398 
03399   AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
03400                           AllocSize,
03401                           DAG.getConstant(TySize, IntPtr));
03402 
03403   // Handle alignment.  If the requested alignment is less than or equal to
03404   // the stack alignment, ignore it.  If the size is greater than or equal to
03405   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
03406   unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
03407   if (Align <= StackAlign)
03408     Align = 0;
03409 
03410   // Round the size of the allocation up to the stack alignment size
03411   // by add SA-1 to the size.
03412   AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
03413                           AllocSize.getValueType(), AllocSize,
03414                           DAG.getIntPtrConstant(StackAlign-1));
03415 
03416   // Mask out the low bits for alignment purposes.
03417   AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
03418                           AllocSize.getValueType(), AllocSize,
03419                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
03420 
03421   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
03422   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
03423   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(),
03424                             VTs, Ops, 3);
03425   setValue(&I, DSA);
03426   DAG.setRoot(DSA.getValue(1));
03427 
03428   assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
03429 }
03430 
03431 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
03432   if (I.isAtomic())
03433     return visitAtomicLoad(I);
03434 
03435   const Value *SV = I.getOperand(0);
03436   SDValue Ptr = getValue(SV);
03437 
03438   Type *Ty = I.getType();
03439 
03440   bool isVolatile = I.isVolatile();
03441   bool isNonTemporal = I.getMetadata("nontemporal") != nullptr;
03442   bool isInvariant = I.getMetadata("invariant.load") != nullptr;
03443   unsigned Alignment = I.getAlignment();
03444   const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
03445   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
03446 
03447   SmallVector<EVT, 4> ValueVTs;
03448   SmallVector<uint64_t, 4> Offsets;
03449   ComputeValueVTs(*TM.getTargetLowering(), Ty, ValueVTs, &Offsets);
03450   unsigned NumValues = ValueVTs.size();
03451   if (NumValues == 0)
03452     return;
03453 
03454   SDValue Root;
03455   bool ConstantMemory = false;
03456   if (isVolatile || NumValues > MaxParallelChains)
03457     // Serialize volatile loads with other side effects.
03458     Root = getRoot();
03459   else if (AA->pointsToConstantMemory(
03460              AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
03461     // Do not serialize (non-volatile) loads of constant memory with anything.
03462     Root = DAG.getEntryNode();
03463     ConstantMemory = true;
03464   } else {
03465     // Do not serialize non-volatile loads against each other.
03466     Root = DAG.getRoot();
03467   }
03468 
03469   const TargetLowering *TLI = TM.getTargetLowering();
03470   if (isVolatile)
03471     Root = TLI->prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
03472 
03473   SmallVector<SDValue, 4> Values(NumValues);
03474   SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
03475                                           NumValues));
03476   EVT PtrVT = Ptr.getValueType();
03477   unsigned ChainI = 0;
03478   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
03479     // Serializing loads here may result in excessive register pressure, and
03480     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
03481     // could recover a bit by hoisting nodes upward in the chain by recognizing
03482     // they are side-effect free or do not alias. The optimizer should really
03483     // avoid this case by converting large object/array copies to llvm.memcpy
03484     // (MaxParallelChains should always remain as failsafe).
03485     if (ChainI == MaxParallelChains) {
03486       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
03487       SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
03488                                   MVT::Other, &Chains[0], ChainI);
03489       Root = Chain;
03490       ChainI = 0;
03491     }
03492     SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
03493                             PtrVT, Ptr,
03494                             DAG.getConstant(Offsets[i], PtrVT));
03495     SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
03496                             A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
03497                             isNonTemporal, isInvariant, Alignment, TBAAInfo,
03498                             Ranges);
03499 
03500     Values[i] = L;
03501     Chains[ChainI] = L.getValue(1);
03502   }
03503 
03504   if (!ConstantMemory) {
03505     SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
03506                                 MVT::Other, &Chains[0], ChainI);
03507     if (isVolatile)
03508       DAG.setRoot(Chain);
03509     else
03510       PendingLoads.push_back(Chain);
03511   }
03512 
03513   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
03514                            DAG.getVTList(ValueVTs),
03515                            &Values[0], NumValues));
03516 }
03517 
03518 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
03519   if (I.isAtomic())
03520     return visitAtomicStore(I);
03521 
03522   const Value *SrcV = I.getOperand(0);
03523   const Value *PtrV = I.getOperand(1);
03524 
03525   SmallVector<EVT, 4> ValueVTs;
03526   SmallVector<uint64_t, 4> Offsets;
03527   ComputeValueVTs(*TM.getTargetLowering(), SrcV->getType(), ValueVTs, &Offsets);
03528   unsigned NumValues = ValueVTs.size();
03529   if (NumValues == 0)
03530     return;
03531 
03532   // Get the lowered operands. Note that we do this after
03533   // checking if NumResults is zero, because with zero results
03534   // the operands won't have values in the map.
03535   SDValue Src = getValue(SrcV);
03536   SDValue Ptr = getValue(PtrV);
03537 
03538   SDValue Root = getRoot();
03539   SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
03540                                           NumValues));
03541   EVT PtrVT = Ptr.getValueType();
03542   bool isVolatile = I.isVolatile();
03543   bool isNonTemporal = I.getMetadata("nontemporal") != nullptr;
03544   unsigned Alignment = I.getAlignment();
03545   const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
03546 
03547   unsigned ChainI = 0;
03548   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
03549     // See visitLoad comments.
03550     if (ChainI == MaxParallelChains) {
03551       SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
03552                                   MVT::Other, &Chains[0], ChainI);
03553       Root = Chain;
03554       ChainI = 0;
03555     }
03556     SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
03557                               DAG.getConstant(Offsets[i], PtrVT));
03558     SDValue St = DAG.getStore(Root, getCurSDLoc(),
03559                               SDValue(Src.getNode(), Src.getResNo() + i),
03560                               Add, MachinePointerInfo(PtrV, Offsets[i]),
03561                               isVolatile, isNonTemporal, Alignment, TBAAInfo);
03562     Chains[ChainI] = St;
03563   }
03564 
03565   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
03566                                   MVT::Other, &Chains[0], ChainI);
03567   DAG.setRoot(StoreNode);
03568 }
03569 
03570 static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
03571                                     SynchronizationScope Scope,
03572                                     bool Before, SDLoc dl,
03573                                     SelectionDAG &DAG,
03574                                     const TargetLowering &TLI) {
03575   // Fence, if necessary
03576   if (Before) {
03577     if (Order == AcquireRelease || Order == SequentiallyConsistent)
03578       Order = Release;
03579     else if (Order == Acquire || Order == Monotonic)
03580       return Chain;
03581   } else {
03582     if (Order == AcquireRelease)
03583       Order = Acquire;
03584     else if (Order == Release || Order == Monotonic)
03585       return Chain;
03586   }
03587   SDValue Ops[3];
03588   Ops[0] = Chain;
03589   Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
03590   Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
03591   return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
03592 }
03593 
03594 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
03595   SDLoc dl = getCurSDLoc();
03596   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
03597   AtomicOrdering FailureOrder = I.getFailureOrdering();
03598   SynchronizationScope Scope = I.getSynchScope();
03599 
03600   SDValue InChain = getRoot();
03601 
03602   const TargetLowering *TLI = TM.getTargetLowering();
03603   if (TLI->getInsertFencesForAtomic())
03604     InChain = InsertFenceForAtomic(InChain, SuccessOrder, Scope, true, dl,
03605                                    DAG, *TLI);
03606 
03607   SDValue L =
03608     DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
03609                   getValue(I.getCompareOperand()).getSimpleValueType(),
03610                   InChain,
03611                   getValue(I.getPointerOperand()),
03612                   getValue(I.getCompareOperand()),
03613                   getValue(I.getNewValOperand()),
03614                   MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
03615                   TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder,
03616                   TLI->getInsertFencesForAtomic() ? Monotonic : FailureOrder,
03617                   Scope);
03618 
03619   SDValue OutChain = L.getValue(1);
03620 
03621   if (TLI->getInsertFencesForAtomic())
03622     OutChain = InsertFenceForAtomic(OutChain, SuccessOrder, Scope, false, dl,
03623                                     DAG, *TLI);
03624 
03625   setValue(&I, L);
03626   DAG.setRoot(OutChain);
03627 }
03628 
03629 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
03630   SDLoc dl = getCurSDLoc();
03631   ISD::NodeType NT;
03632   switch (I.getOperation()) {
03633   default: llvm_unreachable("Unknown atomicrmw operation");
03634   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
03635   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
03636   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
03637   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
03638   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
03639   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
03640   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
03641   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
03642   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
03643   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
03644   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
03645   }
03646   AtomicOrdering Order = I.getOrdering();
03647   SynchronizationScope Scope = I.getSynchScope();
03648 
03649   SDValue InChain = getRoot();
03650 
03651   const TargetLowering *TLI = TM.getTargetLowering();
03652   if (TLI->getInsertFencesForAtomic())
03653     InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
03654                                    DAG, *TLI);
03655 
03656   SDValue L =
03657     DAG.getAtomic(NT, dl,
03658                   getValue(I.getValOperand()).getSimpleValueType(),
03659                   InChain,
03660                   getValue(I.getPointerOperand()),
03661                   getValue(I.getValOperand()),
03662                   I.getPointerOperand(), 0 /* Alignment */,
03663                   TLI->getInsertFencesForAtomic() ? Monotonic : Order,
03664                   Scope);
03665 
03666   SDValue OutChain = L.getValue(1);
03667 
03668   if (TLI->getInsertFencesForAtomic())
03669     OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
03670                                     DAG, *TLI);
03671 
03672   setValue(&I, L);
03673   DAG.setRoot(OutChain);
03674 }
03675 
03676 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
03677   SDLoc dl = getCurSDLoc();
03678   const TargetLowering *TLI = TM.getTargetLowering();
03679   SDValue Ops[3];
03680   Ops[0] = getRoot();
03681   Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy());
03682   Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy());
03683   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
03684 }
03685 
03686 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
03687   SDLoc dl = getCurSDLoc();
03688   AtomicOrdering Order = I.getOrdering();
03689   SynchronizationScope Scope = I.getSynchScope();
03690 
03691   SDValue InChain = getRoot();
03692 
03693   const TargetLowering *TLI = TM.getTargetLowering();
03694   EVT VT = TLI->getValueType(I.getType());
03695 
03696   if (I.getAlignment() < VT.getSizeInBits() / 8)
03697     report_fatal_error("Cannot generate unaligned atomic load");
03698 
03699   MachineMemOperand *MMO =
03700       DAG.getMachineFunction().
03701       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
03702                            MachineMemOperand::MOVolatile |
03703                            MachineMemOperand::MOLoad,
03704                            VT.getStoreSize(),
03705                            I.getAlignment() ? I.getAlignment() :
03706                                               DAG.getEVTAlignment(VT));
03707 
03708   InChain = TLI->prepareVolatileOrAtomicLoad(InChain, dl, DAG);
03709   SDValue L =
03710       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
03711                     getValue(I.getPointerOperand()), MMO,
03712                     TLI->getInsertFencesForAtomic() ? Monotonic : Order,
03713                     Scope);
03714 
03715   SDValue OutChain = L.getValue(1);
03716 
03717   if (TLI->getInsertFencesForAtomic())
03718     OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
03719                                     DAG, *TLI);
03720 
03721   setValue(&I, L);
03722   DAG.setRoot(OutChain);
03723 }
03724 
03725 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
03726   SDLoc dl = getCurSDLoc();
03727 
03728   AtomicOrdering Order = I.getOrdering();
03729   SynchronizationScope Scope = I.getSynchScope();
03730 
03731   SDValue InChain = getRoot();
03732 
03733   const TargetLowering *TLI = TM.getTargetLowering();
03734   EVT VT = TLI->getValueType(I.getValueOperand()->getType());
03735 
03736   if (I.getAlignment() < VT.getSizeInBits() / 8)
03737     report_fatal_error("Cannot generate unaligned atomic store");
03738 
03739   if (TLI->getInsertFencesForAtomic())
03740     InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
03741                                    DAG, *TLI);
03742 
03743   SDValue OutChain =
03744     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
03745                   InChain,
03746                   getValue(I.getPointerOperand()),
03747                   getValue(I.getValueOperand()),
03748                   I.getPointerOperand(), I.getAlignment(),
03749                   TLI->getInsertFencesForAtomic() ? Monotonic : Order,
03750                   Scope);
03751 
03752   if (TLI->getInsertFencesForAtomic())
03753     OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
03754                                     DAG, *TLI);
03755 
03756   DAG.setRoot(OutChain);
03757 }
03758 
03759 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
03760 /// node.
03761 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
03762                                                unsigned Intrinsic) {
03763   bool HasChain = !I.doesNotAccessMemory();
03764   bool OnlyLoad = HasChain && I.onlyReadsMemory();
03765 
03766   // Build the operand list.
03767   SmallVector<SDValue, 8> Ops;
03768   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
03769     if (OnlyLoad) {
03770       // We don't need to serialize loads against other loads.
03771       Ops.push_back(DAG.getRoot());
03772     } else {
03773       Ops.push_back(getRoot());
03774     }
03775   }
03776 
03777   // Info is set by getTgtMemInstrinsic
03778   TargetLowering::IntrinsicInfo Info;
03779   const TargetLowering *TLI = TM.getTargetLowering();
03780   bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic);
03781 
03782   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
03783   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
03784       Info.opc == ISD::INTRINSIC_W_CHAIN)
03785     Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy()));
03786 
03787   // Add all operands of the call to the operand list.
03788   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
03789     SDValue Op = getValue(I.getArgOperand(i));
03790     Ops.push_back(Op);
03791   }
03792 
03793   SmallVector<EVT, 4> ValueVTs;
03794   ComputeValueVTs(*TLI, I.getType(), ValueVTs);
03795 
03796   if (HasChain)
03797     ValueVTs.push_back(MVT::Other);
03798 
03799   SDVTList VTs = DAG.getVTList(ValueVTs);
03800 
03801   // Create the node.
03802   SDValue Result;
03803   if (IsTgtIntrinsic) {
03804     // This is target intrinsic that touches memory
03805     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
03806                                      VTs, &Ops[0], Ops.size(),
03807                                      Info.memVT,
03808                                    MachinePointerInfo(Info.ptrVal, Info.offset),
03809                                      Info.align, Info.vol,
03810                                      Info.readMem, Info.writeMem);
03811   } else if (!HasChain) {
03812     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(),
03813                          VTs, &Ops[0], Ops.size());
03814   } else if (!I.getType()->isVoidTy()) {
03815     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(),
03816                          VTs, &Ops[0], Ops.size());
03817   } else {
03818     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(),
03819                          VTs, &Ops[0], Ops.size());
03820   }
03821 
03822   if (HasChain) {
03823     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
03824     if (OnlyLoad)
03825       PendingLoads.push_back(Chain);
03826     else
03827       DAG.setRoot(Chain);
03828   }
03829 
03830   if (!I.getType()->isVoidTy()) {
03831     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
03832       EVT VT = TLI->getValueType(PTy);
03833       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
03834     }
03835 
03836     setValue(&I, Result);
03837   }
03838 }
03839 
03840 /// GetSignificand - Get the significand and build it into a floating-point
03841 /// number with exponent of 1:
03842 ///
03843 ///   Op = (Op & 0x007fffff) | 0x3f800000;
03844 ///
03845 /// where Op is the hexadecimal representation of floating point value.
03846 static SDValue
03847 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
03848   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
03849                            DAG.getConstant(0x007fffff, MVT::i32));
03850   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
03851                            DAG.getConstant(0x3f800000, MVT::i32));
03852   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
03853 }
03854 
03855 /// GetExponent - Get the exponent:
03856 ///
03857 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
03858 ///
03859 /// where Op is the hexadecimal representation of floating point value.
03860 static SDValue
03861 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
03862             SDLoc dl) {
03863   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
03864                            DAG.getConstant(0x7f800000, MVT::i32));
03865   SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
03866                            DAG.getConstant(23, TLI.getPointerTy()));
03867   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
03868                            DAG.getConstant(127, MVT::i32));
03869   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
03870 }
03871 
03872 /// getF32Constant - Get 32-bit floating point constant.
03873 static SDValue
03874 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
03875   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
03876                            MVT::f32);
03877 }
03878 
03879 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
03880 /// limited-precision mode.
03881 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
03882                          const TargetLowering &TLI) {
03883   if (Op.getValueType() == MVT::f32 &&
03884       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03885 
03886     // Put the exponent in the right bit position for later addition to the
03887     // final result:
03888     //
03889     //   #define LOG2OFe 1.4426950f
03890     //   IntegerPartOfX = ((int32_t)(X * LOG2OFe));
03891     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
03892                              getF32Constant(DAG, 0x3fb8aa3b));
03893     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
03894 
03895     //   FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
03896     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
03897     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
03898 
03899     //   IntegerPartOfX <<= 23;
03900     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
03901                                  DAG.getConstant(23, TLI.getPointerTy()));
03902 
03903     SDValue TwoToFracPartOfX;
03904     if (LimitFloatPrecision <= 6) {
03905       // For floating-point precision of 6:
03906       //
03907       //   TwoToFractionalPartOfX =
03908       //     0.997535578f +
03909       //       (0.735607626f + 0.252464424f * x) * x;
03910       //
03911       // error 0.0144103317, which is 6 bits
03912       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03913                                getF32Constant(DAG, 0x3e814304));
03914       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03915                                getF32Constant(DAG, 0x3f3c50c8));
03916       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03917       TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03918                                      getF32Constant(DAG, 0x3f7f5e7e));
03919     } else if (LimitFloatPrecision <= 12) {
03920       // For floating-point precision of 12:
03921       //
03922       //   TwoToFractionalPartOfX =
03923       //     0.999892986f +
03924       //       (0.696457318f +
03925       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
03926       //
03927       // 0.000107046256 error, which is 13 to 14 bits
03928       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03929                                getF32Constant(DAG, 0x3da235e3));
03930       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03931                                getF32Constant(DAG, 0x3e65b8f3));
03932       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03933       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03934                                getF32Constant(DAG, 0x3f324b07));
03935       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03936       TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03937                                      getF32Constant(DAG, 0x3f7ff8fd));
03938     } else { // LimitFloatPrecision <= 18
03939       // For floating-point precision of 18:
03940       //
03941       //   TwoToFractionalPartOfX =
03942       //     0.999999982f +
03943       //       (0.693148872f +
03944       //         (0.240227044f +
03945       //           (0.554906021e-1f +
03946       //             (0.961591928e-2f +
03947       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
03948       //
03949       // error 2.47208000*10^(-7), which is better than 18 bits
03950       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
03951                                getF32Constant(DAG, 0x3924b03e));
03952       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
03953                                getF32Constant(DAG, 0x3ab24b87));
03954       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
03955       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
03956                                getF32Constant(DAG, 0x3c1d8c17));
03957       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
03958       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
03959                                getF32Constant(DAG, 0x3d634a1d));
03960       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
03961       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
03962                                getF32Constant(DAG, 0x3e75fe14));
03963       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
03964       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
03965                                 getF32Constant(DAG, 0x3f317234));
03966       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
03967       TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
03968                                      getF32Constant(DAG, 0x3f800000));
03969     }
03970 
03971     // Add the exponent into the result in integer domain.
03972     SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
03973     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
03974                        DAG.getNode(ISD::ADD, dl, MVT::i32,
03975                                    t13, IntegerPartOfX));
03976   }
03977 
03978   // No special expansion.
03979   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
03980 }
03981 
03982 /// expandLog - Lower a log intrinsic. Handles the special sequences for
03983 /// limited-precision mode.
03984 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
03985                          const TargetLowering &TLI) {
03986   if (Op.getValueType() == MVT::f32 &&
03987       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
03988     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
03989 
03990     // Scale the exponent by log(2) [0.69314718f].
03991     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
03992     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
03993                                         getF32Constant(DAG, 0x3f317218));
03994 
03995     // Get the significand and build it into a floating-point number with
03996     // exponent of 1.
03997     SDValue X = GetSignificand(DAG, Op1, dl);
03998 
03999     SDValue LogOfMantissa;
04000     if (LimitFloatPrecision <= 6) {
04001       // For floating-point precision of 6:
04002       //
04003       //   LogofMantissa =
04004       //     -1.1609546f +
04005       //       (1.4034025f - 0.23903021f * x) * x;
04006       //
04007       // error 0.0034276066, which is better than 8 bits
04008       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04009                                getF32Constant(DAG, 0xbe74c456));
04010       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04011                                getF32Constant(DAG, 0x3fb3a2b1));
04012       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04013       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04014                                   getF32Constant(DAG, 0x3f949a29));
04015     } else if (LimitFloatPrecision <= 12) {
04016       // For floating-point precision of 12:
04017       //
04018       //   LogOfMantissa =
04019       //     -1.7417939f +
04020       //       (2.8212026f +
04021       //         (-1.4699568f +
04022       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
04023       //
04024       // error 0.000061011436, which is 14 bits
04025       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04026                                getF32Constant(DAG, 0xbd67b6d6));
04027       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04028                                getF32Constant(DAG, 0x3ee4f4b8));
04029       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04030       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04031                                getF32Constant(DAG, 0x3fbc278b));
04032       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04033       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04034                                getF32Constant(DAG, 0x40348e95));
04035       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04036       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
04037                                   getF32Constant(DAG, 0x3fdef31a));
04038     } else { // LimitFloatPrecision <= 18
04039       // For floating-point precision of 18:
04040       //
04041       //   LogOfMantissa =
04042       //     -2.1072184f +
04043       //       (4.2372794f +
04044       //         (-3.7029485f +
04045       //           (2.2781945f +
04046       //             (-0.87823314f +
04047       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
04048       //
04049       // error 0.0000023660568, which is better than 18 bits
04050       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04051                                getF32Constant(DAG, 0xbc91e5ac));
04052       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04053                                getF32Constant(DAG, 0x3e4350aa));
04054       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04055       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04056                                getF32Constant(DAG, 0x3f60d3e3));
04057       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04058       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04059                                getF32Constant(DAG, 0x4011cdf0));
04060       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04061       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
04062                                getF32Constant(DAG, 0x406cfd1c));
04063       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
04064       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
04065                                getF32Constant(DAG, 0x408797cb));
04066       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
04067       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
04068                                   getF32Constant(DAG, 0x4006dcab));
04069     }
04070 
04071     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
04072   }
04073 
04074   // No special expansion.
04075   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
04076 }
04077 
04078 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
04079 /// limited-precision mode.
04080 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
04081                           const TargetLowering &TLI) {
04082   if (Op.getValueType() == MVT::f32 &&
04083       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
04084     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
04085 
04086     // Get the exponent.
04087     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
04088 
04089     // Get the significand and build it into a floating-point number with
04090     // exponent of 1.
04091     SDValue X = GetSignificand(DAG, Op1, dl);
04092 
04093     // Different possible minimax approximations of significand in
04094     // floating-point for various degrees of accuracy over [1,2].
04095     SDValue Log2ofMantissa;
04096     if (LimitFloatPrecision <= 6) {
04097       // For floating-point precision of 6:
04098       //
04099       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
04100       //
04101       // error 0.0049451742, which is more than 7 bits
04102       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04103                                getF32Constant(DAG, 0xbeb08fe0));
04104       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04105                                getF32Constant(DAG, 0x40019463));
04106       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04107       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04108                                    getF32Constant(DAG, 0x3fd6633d));
04109     } else if (LimitFloatPrecision <= 12) {
04110       // For floating-point precision of 12:
04111       //
04112       //   Log2ofMantissa =
04113       //     -2.51285454f +
04114       //       (4.07009056f +
04115       //         (-2.12067489f +
04116       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
04117       //
04118       // error 0.0000876136000, which is better than 13 bits
04119       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04120                                getF32Constant(DAG, 0xbda7262e));
04121       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04122                                getF32Constant(DAG, 0x3f25280b));
04123       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04124       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04125                                getF32Constant(DAG, 0x4007b923));
04126       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04127       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04128                                getF32Constant(DAG, 0x40823e2f));
04129       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04130       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
04131                                    getF32Constant(DAG, 0x4020d29c));
04132     } else { // LimitFloatPrecision <= 18
04133       // For floating-point precision of 18:
04134       //
04135       //   Log2ofMantissa =
04136       //     -3.0400495f +
04137       //       (6.1129976f +
04138       //         (-5.3420409f +
04139       //           (3.2865683f +
04140       //             (-1.2669343f +
04141       //               (0.27515199f -
04142       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
04143       //
04144       // error 0.0000018516, which is better than 18 bits
04145       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04146                                getF32Constant(DAG, 0xbcd2769e));
04147       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04148                                getF32Constant(DAG, 0x3e8ce0b9));
04149       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04150       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04151                                getF32Constant(DAG, 0x3fa22ae7));
04152       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04153       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04154                                getF32Constant(DAG, 0x40525723));
04155       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04156       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
04157                                getF32Constant(DAG, 0x40aaf200));
04158       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
04159       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
04160                                getF32Constant(DAG, 0x40c39dad));
04161       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
04162       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
04163                                    getF32Constant(DAG, 0x4042902c));
04164     }
04165 
04166     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
04167   }
04168 
04169   // No special expansion.
04170   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
04171 }
04172 
04173 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
04174 /// limited-precision mode.
04175 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
04176                            const TargetLowering &TLI) {
04177   if (Op.getValueType() == MVT::f32 &&
04178       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
04179     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
04180 
04181     // Scale the exponent by log10(2) [0.30102999f].
04182     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
04183     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
04184                                         getF32Constant(DAG, 0x3e9a209a));
04185 
04186     // Get the significand and build it into a floating-point number with
04187     // exponent of 1.
04188     SDValue X = GetSignificand(DAG, Op1, dl);
04189 
04190     SDValue Log10ofMantissa;
04191     if (LimitFloatPrecision <= 6) {
04192       // For floating-point precision of 6:
04193       //
04194       //   Log10ofMantissa =
04195       //     -0.50419619f +
04196       //       (0.60948995f - 0.10380950f * x) * x;
04197       //
04198       // error 0.0014886165, which is 6 bits
04199       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04200                                getF32Constant(DAG, 0xbdd49a13));
04201       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
04202                                getF32Constant(DAG, 0x3f1c0789));
04203       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04204       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
04205                                     getF32Constant(DAG, 0x3f011300));
04206     } else if (LimitFloatPrecision <= 12) {
04207       // For floating-point precision of 12:
04208       //
04209       //   Log10ofMantissa =
04210       //     -0.64831180f +
04211       //       (0.91751397f +
04212       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
04213       //
04214       // error 0.00019228036, which is better than 12 bits
04215       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04216                                getF32Constant(DAG, 0x3d431f31));
04217       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
04218                                getF32Constant(DAG, 0x3ea21fb2));
04219       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04220       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04221                                getF32Constant(DAG, 0x3f6ae232));
04222       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04223       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
04224                                     getF32Constant(DAG, 0x3f25f7c3));
04225     } else { // LimitFloatPrecision <= 18
04226       // For floating-point precision of 18:
04227       //
04228       //   Log10ofMantissa =
04229       //     -0.84299375f +
04230       //       (1.5327582f +
04231       //         (-1.0688956f +
04232       //           (0.49102474f +
04233       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
04234       //
04235       // error 0.0000037995730, which is better than 18 bits
04236       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04237                                getF32Constant(DAG, 0x3c5d51ce));
04238       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
04239                                getF32Constant(DAG, 0x3e00685a));
04240       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
04241       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04242                                getF32Constant(DAG, 0x3efb6798));
04243       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04244       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
04245                                getF32Constant(DAG, 0x3f88d192));
04246       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04247       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
04248                                getF32Constant(DAG, 0x3fc4316c));
04249       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
04250       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
04251                                     getF32Constant(DAG, 0x3f57ce70));
04252     }
04253 
04254     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
04255   }
04256 
04257   // No special expansion.
04258   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
04259 }
04260 
04261 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
04262 /// limited-precision mode.
04263 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
04264                           const TargetLowering &TLI) {
04265   if (Op.getValueType() == MVT::f32 &&
04266       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
04267     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
04268 
04269     //   FractionalPartOfX = x - (float)IntegerPartOfX;
04270     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
04271     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
04272 
04273     //   IntegerPartOfX <<= 23;
04274     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
04275                                  DAG.getConstant(23, TLI.getPointerTy()));
04276 
04277     SDValue TwoToFractionalPartOfX;
04278     if (LimitFloatPrecision <= 6) {
04279       // For floating-point precision of 6:
04280       //
04281       //   TwoToFractionalPartOfX =
04282       //     0.997535578f +
04283       //       (0.735607626f + 0.252464424f * x) * x;
04284       //
04285       // error 0.0144103317, which is 6 bits
04286       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04287                                getF32Constant(DAG, 0x3e814304));
04288       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04289                                getF32Constant(DAG, 0x3f3c50c8));
04290       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04291       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04292                                            getF32Constant(DAG, 0x3f7f5e7e));
04293     } else if (LimitFloatPrecision <= 12) {
04294       // For floating-point precision of 12:
04295       //
04296       //   TwoToFractionalPartOfX =
04297       //     0.999892986f +
04298       //       (0.696457318f +
04299       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
04300       //
04301       // error 0.000107046256, which is 13 to 14 bits
04302       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04303                                getF32Constant(DAG, 0x3da235e3));
04304       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04305                                getF32Constant(DAG, 0x3e65b8f3));
04306       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04307       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04308                                getF32Constant(DAG, 0x3f324b07));
04309       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04310       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
04311                                            getF32Constant(DAG, 0x3f7ff8fd));
04312     } else { // LimitFloatPrecision <= 18
04313       // For floating-point precision of 18:
04314       //
04315       //   TwoToFractionalPartOfX =
04316       //     0.999999982f +
04317       //       (0.693148872f +
04318       //         (0.240227044f +
04319       //           (0.554906021e-1f +
04320       //             (0.961591928e-2f +
04321       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
04322       // error 2.47208000*10^(-7), which is better than 18 bits
04323       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04324                                getF32Constant(DAG, 0x3924b03e));
04325       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04326                                getF32Constant(DAG, 0x3ab24b87));
04327       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04328       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04329                                getF32Constant(DAG, 0x3c1d8c17));
04330       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04331       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
04332                                getF32Constant(DAG, 0x3d634a1d));
04333       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
04334       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
04335                                getF32Constant(DAG, 0x3e75fe14));
04336       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
04337       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
04338                                 getF32Constant(DAG, 0x3f317234));
04339       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
04340       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
04341                                            getF32Constant(DAG, 0x3f800000));
04342     }
04343 
04344     // Add the exponent into the result in integer domain.
04345     SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
04346                               TwoToFractionalPartOfX);
04347     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
04348                        DAG.getNode(ISD::ADD, dl, MVT::i32,
04349                                    t13, IntegerPartOfX));
04350   }
04351 
04352   // No special expansion.
04353   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
04354 }
04355 
04356 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
04357 /// limited-precision mode with x == 10.0f.
04358 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
04359                          SelectionDAG &DAG, const TargetLowering &TLI) {
04360   bool IsExp10 = false;
04361   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
04362       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
04363     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
04364       APFloat Ten(10.0f);
04365       IsExp10 = LHSC->isExactlyValue(Ten);
04366     }
04367   }
04368 
04369   if (IsExp10) {
04370     // Put the exponent in the right bit position for later addition to the
04371     // final result:
04372     //
04373     //   #define LOG2OF10 3.3219281f
04374     //   IntegerPartOfX = (int32_t)(x * LOG2OF10);
04375     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
04376                              getF32Constant(DAG, 0x40549a78));
04377     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
04378 
04379     //   FractionalPartOfX = x - (float)IntegerPartOfX;
04380     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
04381     SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
04382 
04383     //   IntegerPartOfX <<= 23;
04384     IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
04385                                  DAG.getConstant(23, TLI.getPointerTy()));
04386 
04387     SDValue TwoToFractionalPartOfX;
04388     if (LimitFloatPrecision <= 6) {
04389       // For floating-point precision of 6:
04390       //
04391       //   twoToFractionalPartOfX =
04392       //     0.997535578f +
04393       //       (0.735607626f + 0.252464424f * x) * x;
04394       //
04395       // error 0.0144103317, which is 6 bits
04396       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04397                                getF32Constant(DAG, 0x3e814304));
04398       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04399                                getF32Constant(DAG, 0x3f3c50c8));
04400       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04401       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04402                                            getF32Constant(DAG, 0x3f7f5e7e));
04403     } else if (LimitFloatPrecision <= 12) {
04404       // For floating-point precision of 12:
04405       //
04406       //   TwoToFractionalPartOfX =
04407       //     0.999892986f +
04408       //       (0.696457318f +
04409       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
04410       //
04411       // error 0.000107046256, which is 13 to 14 bits
04412       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04413                                getF32Constant(DAG, 0x3da235e3));
04414       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04415                                getF32Constant(DAG, 0x3e65b8f3));
04416       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04417       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04418                                getF32Constant(DAG, 0x3f324b07));
04419       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04420       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
04421                                            getF32Constant(DAG, 0x3f7ff8fd));
04422     } else { // LimitFloatPrecision <= 18
04423       // For floating-point precision of 18:
04424       //
04425       //   TwoToFractionalPartOfX =
04426       //     0.999999982f +
04427       //       (0.693148872f +
04428       //         (0.240227044f +
04429       //           (0.554906021e-1f +
04430       //             (0.961591928e-2f +
04431       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
04432       // error 2.47208000*10^(-7), which is better than 18 bits
04433       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
04434                                getF32Constant(DAG, 0x3924b03e));
04435       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
04436                                getF32Constant(DAG, 0x3ab24b87));
04437       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
04438       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
04439                                getF32Constant(DAG, 0x3c1d8c17));
04440       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
04441       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
04442                                getF32Constant(DAG, 0x3d634a1d));
04443       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
04444       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
04445                                getF32Constant(DAG, 0x3e75fe14));
04446       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
04447       SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
04448                                 getF32Constant(DAG, 0x3f317234));
04449       SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
04450       TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
04451                                            getF32Constant(DAG, 0x3f800000));
04452     }
04453 
04454     SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
04455     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
04456                        DAG.getNode(ISD::ADD, dl, MVT::i32,
04457                                    t13, IntegerPartOfX));
04458   }
04459 
04460   // No special expansion.
04461   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
04462 }
04463 
04464 
04465 /// ExpandPowI - Expand a llvm.powi intrinsic.
04466 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
04467                           SelectionDAG &DAG) {
04468   // If RHS is a constant, we can expand this out to a multiplication tree,
04469   // otherwise we end up lowering to a call to __powidf2 (for example).  When
04470   // optimizing for size, we only want to do this if the expansion would produce
04471   // a small number of multiplies, otherwise we do the full expansion.
04472   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
04473     // Get the exponent as a positive value.
04474     unsigned Val = RHSC->getSExtValue();
04475     if ((int)Val < 0) Val = -Val;
04476 
04477     // powi(x, 0) -> 1.0
04478     if (Val == 0)
04479       return DAG.getConstantFP(1.0, LHS.getValueType());
04480 
04481     const Function *F = DAG.getMachineFunction().getFunction();
04482     if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
04483                                          Attribute::OptimizeForSize) ||
04484         // If optimizing for size, don't insert too many multiplies.  This
04485         // inserts up to 5 multiplies.
04486         CountPopulation_32(Val)+Log2_32(Val) < 7) {
04487       // We use the simple binary decomposition method to generate the multiply
04488       // sequence.  There are more optimal ways to do this (for example,
04489       // powi(x,15) generates one more multiply than it should), but this has
04490       // the benefit of being both really simple and much better than a libcall.
04491       SDValue Res;  // Logically starts equal to 1.0
04492       SDValue CurSquare = LHS;
04493       while (Val) {
04494         if (Val & 1) {
04495           if (Res.getNode())
04496             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
04497           else
04498             Res = CurSquare;  // 1.0*CurSquare.
04499         }
04500 
04501         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
04502                                 CurSquare, CurSquare);
04503         Val >>= 1;
04504       }
04505 
04506       // If the original was negative, invert the result, producing 1/(x*x*x).
04507       if (RHSC->getSExtValue() < 0)
04508         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
04509                           DAG.getConstantFP(1.0, LHS.getValueType()), Res);
04510       return Res;
04511     }
04512   }
04513 
04514   // Otherwise, expand to a libcall.
04515   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
04516 }
04517 
04518 // getTruncatedArgReg - Find underlying register used for an truncated
04519 // argument.
04520 static unsigned getTruncatedArgReg(const SDValue &N) {
04521   if (N.getOpcode() != ISD::TRUNCATE)
04522     return 0;
04523 
04524   const SDValue &Ext = N.getOperand(0);
04525   if (Ext.getOpcode() == ISD::AssertZext ||
04526       Ext.getOpcode() == ISD::AssertSext) {
04527     const SDValue &CFR = Ext.getOperand(0);
04528     if (CFR.getOpcode() == ISD::CopyFromReg)
04529       return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
04530     if (CFR.getOpcode() == ISD::TRUNCATE)
04531       return getTruncatedArgReg(CFR);
04532   }
04533   return 0;
04534 }
04535 
04536 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
04537 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
04538 /// At the end of instruction selection, they will be inserted to the entry BB.
04539 bool
04540 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
04541                                               int64_t Offset,
04542                                               const SDValue &N) {
04543   const Argument *Arg = dyn_cast<Argument>(V);
04544   if (!Arg)
04545     return false;
04546 
04547   MachineFunction &MF = DAG.getMachineFunction();
04548   const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
04549 
04550   // Ignore inlined function arguments here.
04551   DIVariable DV(Variable);
04552   if (DV.isInlinedFnArgument(MF.getFunction()))
04553     return false;
04554 
04555   Optional<MachineOperand> Op;
04556   // Some arguments' frame index is recorded during argument lowering.
04557   if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
04558     Op = MachineOperand::CreateFI(FI);
04559 
04560   if (!Op && N.getNode()) {
04561     unsigned Reg;
04562     if (N.getOpcode() == ISD::CopyFromReg)
04563       Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
04564     else
04565       Reg = getTruncatedArgReg(N);
04566     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
04567       MachineRegisterInfo &RegInfo = MF.getRegInfo();
04568       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
04569       if (PR)
04570         Reg = PR;
04571     }
04572     if (Reg)
04573       Op = MachineOperand::CreateReg(Reg, false);
04574   }
04575 
04576   if (!Op) {
04577     // Check if ValueMap has reg number.
04578     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
04579     if (VMI != FuncInfo.ValueMap.end())
04580       Op = MachineOperand::CreateReg(VMI->second, false);
04581   }
04582 
04583   if (!Op && N.getNode())
04584     // Check if frame index is available.
04585     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
04586       if (FrameIndexSDNode *FINode =
04587           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
04588         Op = MachineOperand::CreateFI(FINode->getIndex());
04589 
04590   if (!Op)
04591     return false;
04592 
04593   // FIXME: This does not handle register-indirect values at offset 0.
04594   bool IsIndirect = Offset != 0;
04595   if (Op->isReg())
04596     FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(),
04597                                             TII->get(TargetOpcode::DBG_VALUE),
04598                                             IsIndirect,
04599                                             Op->getReg(), Offset, Variable));
04600   else
04601     FuncInfo.ArgDbgValues.push_back(
04602       BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
04603           .addOperand(*Op).addImm(Offset).addMetadata(Variable));
04604 
04605   return true;
04606 }
04607 
04608 // VisualStudio defines setjmp as _setjmp
04609 #if defined(_MSC_VER) && defined(setjmp) && \
04610                          !defined(setjmp_undefined_for_msvc)
04611 #  pragma push_macro("setjmp")
04612 #  undef setjmp
04613 #  define setjmp_undefined_for_msvc
04614 #endif
04615 
04616 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
04617 /// we want to emit this as a call to a named external function, return the name
04618 /// otherwise lower it and return null.
04619 const char *
04620 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
04621   const TargetLowering *TLI = TM.getTargetLowering();
04622   SDLoc sdl = getCurSDLoc();
04623   DebugLoc dl = getCurDebugLoc();
04624   SDValue Res;
04625 
04626   switch (Intrinsic) {
04627   default:
04628     // By default, turn this into a target intrinsic node.
04629     visitTargetIntrinsic(I, Intrinsic);
04630     return nullptr;
04631   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
04632   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
04633   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
04634   case Intrinsic::returnaddress:
04635     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(),
04636                              getValue(I.getArgOperand(0))));
04637     return nullptr;
04638   case Intrinsic::frameaddress:
04639     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(),
04640                              getValue(I.getArgOperand(0))));
04641     return nullptr;
04642   case Intrinsic::setjmp:
04643     return &"_setjmp"[!TLI->usesUnderscoreSetJmp()];
04644   case Intrinsic::longjmp:
04645     return &"_longjmp"[!TLI->usesUnderscoreLongJmp()];
04646   case Intrinsic::memcpy: {
04647     // Assert for address < 256 since we support only user defined address
04648     // spaces.
04649     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
04650            < 256 &&
04651            cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
04652            < 256 &&
04653            "Unknown address space");
04654     SDValue Op1 = getValue(I.getArgOperand(0));
04655     SDValue Op2 = getValue(I.getArgOperand(1));
04656     SDValue Op3 = getValue(I.getArgOperand(2));
04657     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
04658     if (!Align)
04659       Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
04660     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
04661     DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
04662                               MachinePointerInfo(I.getArgOperand(0)),
04663                               MachinePointerInfo(I.getArgOperand(1))));
04664     return nullptr;
04665   }
04666   case Intrinsic::memset: {
04667     // Assert for address < 256 since we support only user defined address
04668     // spaces.
04669     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
04670            < 256 &&
04671            "Unknown address space");
04672     SDValue Op1 = getValue(I.getArgOperand(0));
04673     SDValue Op2 = getValue(I.getArgOperand(1));
04674     SDValue Op3 = getValue(I.getArgOperand(2));
04675     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
04676     if (!Align)
04677       Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
04678     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
04679     DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
04680                               MachinePointerInfo(I.getArgOperand(0))));
04681     return nullptr;
04682   }
04683   case Intrinsic::memmove: {
04684     // Assert for address < 256 since we support only user defined address
04685     // spaces.
04686     assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
04687            < 256 &&
04688            cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
04689            < 256 &&
04690            "Unknown address space");
04691     SDValue Op1 = getValue(I.getArgOperand(0));
04692     SDValue Op2 = getValue(I.getArgOperand(1));
04693     SDValue Op3 = getValue(I.getArgOperand(2));
04694     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
04695     if (!Align)
04696       Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
04697     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
04698     DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
04699                                MachinePointerInfo(I.getArgOperand(0)),
04700                                MachinePointerInfo(I.getArgOperand(1))));
04701     return nullptr;
04702   }
04703   case Intrinsic::dbg_declare: {
04704     const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
04705     MDNode *Variable = DI.getVariable();
04706     const Value *Address = DI.getAddress();
04707     DIVariable DIVar(Variable);
04708     assert((!DIVar || DIVar.isVariable()) &&
04709       "Variable in DbgDeclareInst should be either null or a DIVariable.");
04710     if (!Address || !DIVar) {
04711       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04712       return nullptr;
04713     }
04714 
04715     // Check if address has undef value.
04716     if (isa<UndefValue>(Address) ||
04717         (Address->use_empty() && !isa<Argument>(Address))) {
04718       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04719       return nullptr;
04720     }
04721 
04722     SDValue &N = NodeMap[Address];
04723     if (!N.getNode() && isa<Argument>(Address))
04724       // Check unused arguments map.
04725       N = UnusedArgNodeMap[Address];
04726     SDDbgValue *SDV;
04727     if (N.getNode()) {
04728       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
04729         Address = BCI->getOperand(0);
04730       // Parameters are handled specially.
04731       bool isParameter =
04732         (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
04733          isa<Argument>(Address));
04734 
04735       const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
04736 
04737       if (isParameter && !AI) {
04738         FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
04739         if (FINode)
04740           // Byval parameter.  We have a frame index at this point.
04741           SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
04742                                 0, dl, SDNodeOrder);
04743         else {
04744           // Address is an argument, so try to emit its dbg value using
04745           // virtual register info from the FuncInfo.ValueMap.
04746           EmitFuncArgumentDbgValue(Address, Variable, 0, N);
04747           return nullptr;
04748         }
04749       } else if (AI)
04750         SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
04751                               0, dl, SDNodeOrder);
04752       else {
04753         // Can't do anything with other non-AI cases yet.
04754         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04755         DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
04756         DEBUG(Address->dump());
04757         return nullptr;
04758       }
04759       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
04760     } else {
04761       // If Address is an argument then try to emit its dbg value using
04762       // virtual register info from the FuncInfo.ValueMap.
04763       if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
04764         // If variable is pinned by a alloca in dominating bb then
04765         // use StaticAllocaMap.
04766         if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
04767           if (AI->getParent() != DI.getParent()) {
04768             DenseMap<const AllocaInst*, int>::iterator SI =
04769               FuncInfo.StaticAllocaMap.find(AI);
04770             if (SI != FuncInfo.StaticAllocaMap.end()) {
04771               SDV = DAG.getDbgValue(Variable, SI->second,
04772                                     0, dl, SDNodeOrder);
04773               DAG.AddDbgValue(SDV, nullptr, false);
04774               return nullptr;
04775             }
04776           }
04777         }
04778         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04779       }
04780     }
04781     return nullptr;
04782   }
04783   case Intrinsic::dbg_value: {
04784     const DbgValueInst &DI = cast<DbgValueInst>(I);
04785     DIVariable DIVar(DI.getVariable());
04786     assert((!DIVar || DIVar.isVariable()) &&
04787       "Variable in DbgValueInst should be either null or a DIVariable.");
04788     if (!DIVar)
04789       return nullptr;
04790 
04791     MDNode *Variable = DI.getVariable();
04792     uint64_t Offset = DI.getOffset();
04793     const Value *V = DI.getValue();
04794     if (!V)
04795       return nullptr;
04796 
04797     SDDbgValue *SDV;
04798     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
04799       SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
04800       DAG.AddDbgValue(SDV, nullptr, false);
04801     } else {
04802       // Do not use getValue() in here; we don't want to generate code at
04803       // this point if it hasn't been done yet.
04804       SDValue N = NodeMap[V];
04805       if (!N.getNode() && isa<Argument>(V))
04806         // Check unused arguments map.
04807         N = UnusedArgNodeMap[V];
04808       if (N.getNode()) {
04809         if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
04810           SDV = DAG.getDbgValue(Variable, N.getNode(),
04811                                 N.getResNo(), Offset, dl, SDNodeOrder);
04812           DAG.AddDbgValue(SDV, N.getNode(), false);
04813         }
04814       } else if (!V->use_empty() ) {
04815         // Do not call getValue(V) yet, as we don't want to generate code.
04816         // Remember it for later.
04817         DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
04818         DanglingDebugInfoMap[V] = DDI;
04819       } else {
04820         // We may expand this to cover more cases.  One case where we have no
04821         // data available is an unreferenced parameter.
04822         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
04823       }
04824     }
04825 
04826     // Build a debug info table entry.
04827     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
04828       V = BCI->getOperand(0);
04829     const AllocaInst *AI = dyn_cast<AllocaInst>(V);
04830     // Don't handle byval struct arguments or VLAs, for example.
04831     if (!AI) {
04832       DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
04833       DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
04834       return nullptr;
04835     }
04836     DenseMap<const AllocaInst*, int>::iterator SI =
04837       FuncInfo.StaticAllocaMap.find(AI);
04838     if (SI == FuncInfo.StaticAllocaMap.end())
04839       return nullptr; // VLAs.
04840     int FI = SI->second;
04841 
04842     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
04843     if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
04844       MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
04845     return nullptr;
04846   }
04847 
04848   case Intrinsic::eh_typeid_for: {
04849     // Find the type id for the given typeinfo.
04850     GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
04851     unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
04852     Res = DAG.getConstant(TypeID, MVT::i32);
04853     setValue(&I, Res);
04854     return nullptr;
04855   }
04856 
04857   case Intrinsic::eh_return_i32:
04858   case Intrinsic::eh_return_i64:
04859     DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
04860     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
04861                             MVT::Other,
04862                             getControlRoot(),
04863                             getValue(I.getArgOperand(0)),
04864                             getValue(I.getArgOperand(1))));
04865     return nullptr;
04866   case Intrinsic::eh_unwind_init:
04867     DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
04868     return nullptr;
04869   case Intrinsic::eh_dwarf_cfa: {
04870     SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
04871                                         TLI->getPointerTy());
04872     SDValue Offset = DAG.getNode(ISD::ADD, sdl,
04873                                  CfaArg.getValueType(),
04874                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
04875                                              CfaArg.getValueType()),
04876                                  CfaArg);
04877     SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl,
04878                              TLI->getPointerTy(),
04879                              DAG.getConstant(0, TLI->getPointerTy()));
04880     setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
04881                              FA, Offset));
04882     return nullptr;
04883   }
04884   case Intrinsic::eh_sjlj_callsite: {
04885     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
04886     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
04887     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
04888     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
04889 
04890     MMI.setCurrentCallSite(CI->getZExtValue());
04891     return nullptr;
04892   }
04893   case Intrinsic::eh_sjlj_functioncontext: {
04894     // Get and store the index of the function context.
04895     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
04896     AllocaInst *FnCtx =
04897       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
04898     int FI = FuncInfo.StaticAllocaMap[FnCtx];
04899     MFI->setFunctionContextIndex(FI);
04900     return nullptr;
04901   }
04902   case Intrinsic::eh_sjlj_setjmp: {
04903     SDValue Ops[2];
04904     Ops[0] = getRoot();
04905     Ops[1] = getValue(I.getArgOperand(0));
04906     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
04907                              DAG.getVTList(MVT::i32, MVT::Other),
04908                              Ops, 2);
04909     setValue(&I, Op.getValue(0));
04910     DAG.setRoot(Op.getValue(1));
04911     return nullptr;
04912   }
04913   case Intrinsic::eh_sjlj_longjmp: {
04914     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
04915                             getRoot(), getValue(I.getArgOperand(0))));
04916     return nullptr;
04917   }
04918 
04919   case Intrinsic::x86_mmx_pslli_w:
04920   case Intrinsic::x86_mmx_pslli_d:
04921   case Intrinsic::x86_mmx_pslli_q:
04922   case Intrinsic::x86_mmx_psrli_w:
04923   case Intrinsic::x86_mmx_psrli_d:
04924   case Intrinsic::x86_mmx_psrli_q:
04925   case Intrinsic::x86_mmx_psrai_w:
04926   case Intrinsic::x86_mmx_psrai_d: {
04927     SDValue ShAmt = getValue(I.getArgOperand(1));
04928     if (isa<ConstantSDNode>(ShAmt)) {
04929       visitTargetIntrinsic(I, Intrinsic);
04930       return nullptr;
04931     }
04932     unsigned NewIntrinsic = 0;
04933     EVT ShAmtVT = MVT::v2i32;
04934     switch (Intrinsic) {
04935     case Intrinsic::x86_mmx_pslli_w:
04936       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
04937       break;
04938     case Intrinsic::x86_mmx_pslli_d:
04939       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
04940       break;
04941     case Intrinsic::x86_mmx_pslli_q:
04942       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
04943       break;
04944     case Intrinsic::x86_mmx_psrli_w:
04945       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
04946       break;
04947     case Intrinsic::x86_mmx_psrli_d:
04948       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
04949       break;
04950     case Intrinsic::x86_mmx_psrli_q:
04951       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
04952       break;
04953     case Intrinsic::x86_mmx_psrai_w:
04954       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
04955       break;
04956     case Intrinsic::x86_mmx_psrai_d:
04957       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
04958       break;
04959     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
04960     }
04961 
04962     // The vector shift intrinsics with scalars uses 32b shift amounts but
04963     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
04964     // to be zero.
04965     // We must do this early because v2i32 is not a legal type.
04966     SDValue ShOps[2];
04967     ShOps[0] = ShAmt;
04968     ShOps[1] = DAG.getConstant(0, MVT::i32);
04969     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, &ShOps[0], 2);
04970     EVT DestVT = TLI->getValueType(I.getType());
04971     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
04972     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
04973                        DAG.getConstant(NewIntrinsic, MVT::i32),
04974                        getValue(I.getArgOperand(0)), ShAmt);
04975     setValue(&I, Res);
04976     return nullptr;
04977   }
04978   case Intrinsic::x86_avx_vinsertf128_pd_256:
04979   case Intrinsic::x86_avx_vinsertf128_ps_256:
04980   case Intrinsic::x86_avx_vinsertf128_si_256:
04981   case Intrinsic::x86_avx2_vinserti128: {
04982     EVT DestVT = TLI->getValueType(I.getType());
04983     EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType());
04984     uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
04985                    ElVT.getVectorNumElements();
04986     Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
04987                       getValue(I.getArgOperand(0)),
04988                       getValue(I.getArgOperand(1)),
04989                       DAG.getConstant(Idx, TLI->getVectorIdxTy()));
04990     setValue(&I, Res);
04991     return nullptr;
04992   }
04993   case Intrinsic::x86_avx_vextractf128_pd_256:
04994   case Intrinsic::x86_avx_vextractf128_ps_256:
04995   case Intrinsic::x86_avx_vextractf128_si_256:
04996   case Intrinsic::x86_avx2_vextracti128: {
04997     EVT DestVT = TLI->getValueType(I.getType());
04998     uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
04999                    DestVT.getVectorNumElements();
05000     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
05001                       getValue(I.getArgOperand(0)),
05002                       DAG.getConstant(Idx, TLI->getVectorIdxTy()));
05003     setValue(&I, Res);
05004     return nullptr;
05005   }
05006   case Intrinsic::convertff:
05007   case Intrinsic::convertfsi:
05008   case Intrinsic::convertfui:
05009   case Intrinsic::convertsif:
05010   case Intrinsic::convertuif:
05011   case Intrinsic::convertss:
05012   case Intrinsic::convertsu:
05013   case Intrinsic::convertus:
05014   case Intrinsic::convertuu: {
05015     ISD::CvtCode Code = ISD::CVT_INVALID;
05016     switch (Intrinsic) {
05017     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
05018     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
05019     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
05020     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
05021     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
05022     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
05023     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
05024     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
05025     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
05026     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
05027     }
05028     EVT DestVT = TLI->getValueType(I.getType());
05029     const Value *Op1 = I.getArgOperand(0);
05030     Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
05031                                DAG.getValueType(DestVT),
05032                                DAG.getValueType(getValue(Op1).getValueType()),
05033                                getValue(I.getArgOperand(1)),
05034                                getValue(I.getArgOperand(2)),
05035                                Code);
05036     setValue(&I, Res);
05037     return nullptr;
05038   }
05039   case Intrinsic::powi:
05040     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
05041                             getValue(I.getArgOperand(1)), DAG));
05042     return nullptr;
05043   case Intrinsic::log:
05044     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
05045     return nullptr;
05046   case Intrinsic::log2:
05047     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
05048     return nullptr;
05049   case Intrinsic::log10:
05050     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
05051     return nullptr;
05052   case Intrinsic::exp:
05053     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
05054     return nullptr;
05055   case Intrinsic::exp2:
05056     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
05057     return nullptr;
05058   case Intrinsic::pow:
05059     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
05060                            getValue(I.getArgOperand(1)), DAG, *TLI));
05061     return nullptr;
05062   case Intrinsic::sqrt:
05063   case Intrinsic::fabs:
05064   case Intrinsic::sin:
05065   case Intrinsic::cos:
05066   case Intrinsic::floor:
05067   case Intrinsic::ceil:
05068   case Intrinsic::trunc:
05069   case Intrinsic::rint:
05070   case Intrinsic::nearbyint:
05071   case Intrinsic::round: {
05072     unsigned Opcode;
05073     switch (Intrinsic) {
05074     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
05075     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
05076     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
05077     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
05078     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
05079     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
05080     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
05081     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
05082     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
05083     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
05084     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
05085     }
05086 
05087     setValue(&I, DAG.getNode(Opcode, sdl,
05088                              getValue(I.getArgOperand(0)).getValueType(),
05089                              getValue(I.getArgOperand(0))));
05090     return nullptr;
05091   }
05092   case Intrinsic::copysign:
05093     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
05094                              getValue(I.getArgOperand(0)).getValueType(),
05095                              getValue(I.getArgOperand(0)),
05096                              getValue(I.getArgOperand(1))));
05097     return nullptr;
05098   case Intrinsic::fma:
05099     setValue(&I, DAG.getNode(ISD::FMA, sdl,
05100                              getValue(I.getArgOperand(0)).getValueType(),
05101                              getValue(I.getArgOperand(0)),
05102                              getValue(I.getArgOperand(1)),
05103                              getValue(I.getArgOperand(2))));
05104     return nullptr;
05105   case Intrinsic::fmuladd: {
05106     EVT VT = TLI->getValueType(I.getType());
05107     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
05108         TLI->isFMAFasterThanFMulAndFAdd(VT)) {
05109       setValue(&I, DAG.getNode(ISD::FMA, sdl,
05110                                getValue(I.getArgOperand(0)).getValueType(),
05111                                getValue(I.getArgOperand(0)),
05112                                getValue(I.getArgOperand(1)),
05113                                getValue(I.getArgOperand(2))));
05114     } else {
05115       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
05116                                 getValue(I.getArgOperand(0)).getValueType(),
05117                                 getValue(I.getArgOperand(0)),
05118                                 getValue(I.getArgOperand(1)));
05119       SDValue Add = DAG.getNode(ISD::FADD, sdl,
05120                                 getValue(I.getArgOperand(0)).getValueType(),
05121                                 Mul,
05122                                 getValue(I.getArgOperand(2)));
05123       setValue(&I, Add);
05124     }
05125     return nullptr;
05126   }
05127   case Intrinsic::convert_to_fp16:
05128     setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, sdl,
05129                              MVT::i16, getValue(I.getArgOperand(0))));
05130     return nullptr;
05131   case Intrinsic::convert_from_fp16:
05132     setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, sdl,
05133                              MVT::f32, getValue(I.getArgOperand(0))));
05134     return nullptr;
05135   case Intrinsic::pcmarker: {
05136     SDValue Tmp = getValue(I.getArgOperand(0));
05137     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
05138     return nullptr;
05139   }
05140   case Intrinsic::readcyclecounter: {
05141     SDValue Op = getRoot();
05142     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
05143                       DAG.getVTList(MVT::i64, MVT::Other),
05144                       &Op, 1);
05145     setValue(&I, Res);
05146     DAG.setRoot(Res.getValue(1));
05147     return nullptr;
05148   }
05149   case Intrinsic::bswap:
05150     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
05151                              getValue(I.getArgOperand(0)).getValueType(),
05152                              getValue(I.getArgOperand(0))));
05153     return nullptr;
05154   case Intrinsic::cttz: {
05155     SDValue Arg = getValue(I.getArgOperand(0));
05156     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
05157     EVT Ty = Arg.getValueType();
05158     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
05159                              sdl, Ty, Arg));
05160     return nullptr;
05161   }
05162   case Intrinsic::ctlz: {
05163     SDValue Arg = getValue(I.getArgOperand(0));
05164     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
05165     EVT Ty = Arg.getValueType();
05166     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
05167                              sdl, Ty, Arg));
05168     return nullptr;
05169   }
05170   case Intrinsic::ctpop: {
05171     SDValue Arg = getValue(I.getArgOperand(0));
05172     EVT Ty = Arg.getValueType();
05173     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
05174     return nullptr;
05175   }
05176   case Intrinsic::stacksave: {
05177     SDValue Op = getRoot();
05178     Res = DAG.getNode(ISD::STACKSAVE, sdl,
05179                       DAG.getVTList(TLI->getPointerTy(), MVT::Other), &Op, 1);
05180     setValue(&I, Res);
05181     DAG.setRoot(Res.getValue(1));
05182     return nullptr;
05183   }
05184   case Intrinsic::stackrestore: {
05185     Res = getValue(I.getArgOperand(0));
05186     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
05187     return nullptr;
05188   }
05189   case Intrinsic::stackprotector: {
05190     // Emit code into the DAG to store the stack guard onto the stack.
05191     MachineFunction &MF = DAG.getMachineFunction();
05192     MachineFrameInfo *MFI = MF.getFrameInfo();
05193     EVT PtrTy = TLI->getPointerTy();
05194 
05195     SDValue Src = getValue(I.getArgOperand(0));   // The guard's value.
05196     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
05197 
05198     int FI = FuncInfo.StaticAllocaMap[Slot];
05199     MFI->setStackProtectorIndex(FI);
05200 
05201     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
05202 
05203     // Store the stack protector onto the stack.
05204     Res = DAG.getStore(getRoot(), sdl, Src, FIN,
05205                        MachinePointerInfo::getFixedStack(FI),
05206                        true, false, 0);
05207     setValue(&I, Res);
05208     DAG.setRoot(Res);
05209     return nullptr;
05210   }
05211   case Intrinsic::objectsize: {
05212     // If we don't know by now, we're never going to know.
05213     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
05214 
05215     assert(CI && "Non-constant type in __builtin_object_size?");
05216 
05217     SDValue Arg = getValue(I.getCalledValue());
05218     EVT Ty = Arg.getValueType();
05219 
05220     if (CI->isZero())
05221       Res = DAG.getConstant(-1ULL, Ty);
05222     else
05223       Res = DAG.getConstant(0, Ty);
05224 
05225     setValue(&I, Res);
05226     return nullptr;
05227   }
05228   case Intrinsic::annotation:
05229   case Intrinsic::ptr_annotation:
05230     // Drop the intrinsic, but forward the value
05231     setValue(&I, getValue(I.getOperand(0)));
05232     return nullptr;
05233   case Intrinsic::var_annotation:
05234     // Discard annotate attributes
05235     return nullptr;
05236 
05237   case Intrinsic::init_trampoline: {
05238     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
05239 
05240     SDValue Ops[6];
05241     Ops[0] = getRoot();
05242     Ops[1] = getValue(I.getArgOperand(0));
05243     Ops[2] = getValue(I.getArgOperand(1));
05244     Ops[3] = getValue(I.getArgOperand(2));
05245     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
05246     Ops[5] = DAG.getSrcValue(F);
05247 
05248     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops, 6);
05249 
05250     DAG.setRoot(Res);
05251     return nullptr;
05252   }
05253   case Intrinsic::adjust_trampoline: {
05254     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
05255                              TLI->getPointerTy(),
05256                              getValue(I.getArgOperand(0))));
05257     return nullptr;
05258   }
05259   case Intrinsic::gcroot:
05260     if (GFI) {
05261       const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
05262       const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
05263 
05264       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
05265       GFI->addStackRoot(FI->getIndex(), TypeMap);
05266     }
05267     return nullptr;
05268   case Intrinsic::gcread:
05269   case Intrinsic::gcwrite:
05270     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
05271   case Intrinsic::flt_rounds:
05272     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
05273     return nullptr;
05274 
05275   case Intrinsic::expect: {
05276     // Just replace __builtin_expect(exp, c) with EXP.
05277     setValue(&I, getValue(I.getArgOperand(0)));
05278     return nullptr;
05279   }
05280 
05281   case Intrinsic::debugtrap:
05282   case Intrinsic::trap: {
05283     StringRef TrapFuncName = TM.Options.getTrapFunctionName();
05284     if (TrapFuncName.empty()) {
05285       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
05286         ISD::TRAP : ISD::DEBUGTRAP;
05287       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
05288       return nullptr;
05289     }
05290     TargetLowering::ArgListTy Args;
05291     TargetLowering::
05292     CallLoweringInfo CLI(getRoot(), I.getType(),
05293                  false, false, false, false, 0, CallingConv::C,
05294                  /*isTailCall=*/false,
05295                  /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
05296                  DAG.getExternalSymbol(TrapFuncName.data(),
05297                                        TLI->getPointerTy()),
05298                  Args, DAG, sdl);
05299     std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
05300     DAG.setRoot(Result.second);
05301     return nullptr;
05302   }
05303 
05304   case Intrinsic::uadd_with_overflow:
05305   case Intrinsic::sadd_with_overflow:
05306   case Intrinsic::usub_with_overflow:
05307   case Intrinsic::ssub_with_overflow:
05308   case Intrinsic::umul_with_overflow:
05309   case Intrinsic::smul_with_overflow: {
05310     ISD::NodeType Op;
05311     switch (Intrinsic) {
05312     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
05313     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
05314     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
05315     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
05316     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
05317     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
05318     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
05319     }
05320     SDValue Op1 = getValue(I.getArgOperand(0));
05321     SDValue Op2 = getValue(I.getArgOperand(1));
05322 
05323     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
05324     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
05325     return nullptr;
05326   }
05327   case Intrinsic::prefetch: {
05328     SDValue Ops[5];
05329     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
05330     Ops[0] = getRoot();
05331     Ops[1] = getValue(I.getArgOperand(0));
05332     Ops[2] = getValue(I.getArgOperand(1));
05333     Ops[3] = getValue(I.getArgOperand(2));
05334     Ops[4] = getValue(I.getArgOperand(3));
05335     DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
05336                                         DAG.getVTList(MVT::Other),
05337                                         &Ops[0], 5,
05338                                         EVT::getIntegerVT(*Context, 8),
05339                                         MachinePointerInfo(I.getArgOperand(0)),
05340                                         0, /* align */
05341                                         false, /* volatile */
05342                                         rw==0, /* read */
05343                                         rw==1)); /* write */
05344     return nullptr;
05345   }
05346   case Intrinsic::lifetime_start:
05347   case Intrinsic::lifetime_end: {
05348     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
05349     // Stack coloring is not enabled in O0, discard region information.
05350     if (TM.getOptLevel() == CodeGenOpt::None)
05351       return nullptr;
05352 
05353     SmallVector<Value *, 4> Allocas;
05354     GetUnderlyingObjects(I.getArgOperand(1), Allocas, DL);
05355 
05356     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
05357            E = Allocas.end(); Object != E; ++Object) {
05358       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
05359 
05360       // Could not find an Alloca.
05361       if (!LifetimeObject)
05362         continue;
05363 
05364       int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
05365 
05366       SDValue Ops[2];
05367       Ops[0] = getRoot();
05368       Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true);
05369       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
05370 
05371       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops, 2);
05372       DAG.setRoot(Res);
05373     }
05374     return nullptr;
05375   }
05376   case Intrinsic::invariant_start:
05377     // Discard region information.
05378     setValue(&I, DAG.getUNDEF(TLI->getPointerTy()));
05379     return nullptr;
05380   case Intrinsic::invariant_end:
05381     // Discard region information.
05382     return nullptr;
05383   case Intrinsic::stackprotectorcheck: {
05384     // Do not actually emit anything for this basic block. Instead we initialize
05385     // the stack protector descriptor and export the guard variable so we can
05386     // access it in FinishBasicBlock.
05387     const BasicBlock *BB = I.getParent();
05388     SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
05389     ExportFromCurrentBlock(SPDescriptor.getGuard());
05390 
05391     // Flush our exports since we are going to process a terminator.
05392     (void)getControlRoot();
05393     return nullptr;
05394   }
05395   case Intrinsic::clear_cache:
05396     return TLI->getClearCacheBuiltinName();
05397   case Intrinsic::donothing:
05398     // ignore
05399     return nullptr;
05400   case Intrinsic::experimental_stackmap: {
05401     visitStackmap(I);
05402     return nullptr;
05403   }
05404   case Intrinsic::experimental_patchpoint_void:
05405   case Intrinsic::experimental_patchpoint_i64: {
05406     visitPatchpoint(I);
05407     return nullptr;
05408   }
05409   }
05410 }
05411 
05412 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
05413                                       bool isTailCall,
05414                                       MachineBasicBlock *LandingPad) {
05415   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
05416   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
05417   Type *RetTy = FTy->getReturnType();
05418   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
05419   MCSymbol *BeginLabel = nullptr;
05420 
05421   TargetLowering::ArgListTy Args;
05422   TargetLowering::ArgListEntry Entry;
05423   Args.reserve(CS.arg_size());
05424 
05425   // Check whether the function can return without sret-demotion.
05426   SmallVector<ISD::OutputArg, 4> Outs;
05427   const TargetLowering *TLI = TM.getTargetLowering();
05428   GetReturnInfo(RetTy, CS.getAttributes(), Outs, *TLI);
05429 
05430   bool CanLowerReturn = TLI->CanLowerReturn(CS.getCallingConv(),
05431                                             DAG.getMachineFunction(),
05432                                             FTy->isVarArg(), Outs,
05433                                             FTy->getContext());
05434 
05435   SDValue DemoteStackSlot;
05436   int DemoteStackIdx = -100;
05437 
05438   if (!CanLowerReturn) {
05439     assert(!CS.hasInAllocaArgument() &&
05440            "sret demotion is incompatible with inalloca");
05441     uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(
05442                       FTy->getReturnType());
05443     unsigned Align  = TLI->getDataLayout()->getPrefTypeAlignment(
05444                       FTy->getReturnType());
05445     MachineFunction &MF = DAG.getMachineFunction();
05446     DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
05447     Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
05448 
05449     DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI->getPointerTy());
05450     Entry.Node = DemoteStackSlot;
05451     Entry.Ty = StackSlotPtrType;
05452     Entry.isSExt = false;
05453     Entry.isZExt = false;
05454     Entry.isInReg = false;
05455     Entry.isSRet = true;
05456     Entry.isNest = false;
05457     Entry.isByVal = false;
05458     Entry.isReturned = false;
05459     Entry.Alignment = Align;
05460     Args.push_back(Entry);
05461     RetTy = Type::getVoidTy(FTy->getContext());
05462   }
05463 
05464   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
05465        i != e; ++i) {
05466     const Value *V = *i;
05467 
05468     // Skip empty types
05469     if (V->getType()->isEmptyTy())
05470       continue;
05471 
05472     SDValue ArgNode = getValue(V);
05473     Entry.Node = ArgNode; Entry.Ty = V->getType();
05474 
05475     // Skip the first return-type Attribute to get to params.
05476     Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
05477     Args.push_back(Entry);
05478   }
05479 
05480   if (LandingPad) {
05481     // Insert a label before the invoke call to mark the try range.  This can be
05482     // used to detect deletion of the invoke via the MachineModuleInfo.
05483     BeginLabel = MMI.getContext().CreateTempSymbol();
05484 
05485     // For SjLj, keep track of which landing pads go with which invokes
05486     // so as to maintain the ordering of pads in the LSDA.
05487     unsigned CallSiteIndex = MMI.getCurrentCallSite();
05488     if (CallSiteIndex) {
05489       MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
05490       LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
05491 
05492       // Now that the call site is handled, stop tracking it.
05493       MMI.setCurrentCallSite(0);
05494     }
05495 
05496     // Both PendingLoads and PendingExports must be flushed here;
05497     // this call might not return.
05498     (void)getRoot();
05499     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
05500   }
05501 
05502   // Check if target-independent constraints permit a tail call here.
05503   // Target-dependent constraints are checked within TLI->LowerCallTo.
05504   if (isTailCall && !isInTailCallPosition(CS, *TLI))
05505     isTailCall = false;
05506 
05507   TargetLowering::
05508   CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
05509                        getCurSDLoc(), CS);
05510   std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI);
05511   assert((isTailCall || Result.second.getNode()) &&
05512          "Non-null chain expected with non-tail call!");
05513   assert((Result.second.getNode() || !Result.first.getNode()) &&
05514          "Null value expected with tail call!");
05515   if (Result.first.getNode()) {
05516     setValue(CS.getInstruction(), Result.first);
05517   } else if (!CanLowerReturn && Result.second.getNode()) {
05518     // The instruction result is the result of loading from the
05519     // hidden sret parameter.
05520     SmallVector<EVT, 1> PVTs;
05521     Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
05522 
05523     ComputeValueVTs(*TLI, PtrRetTy, PVTs);
05524     assert(PVTs.size() == 1 && "Pointers should fit in one register");
05525     EVT PtrVT = PVTs[0];
05526 
05527     SmallVector<EVT, 4> RetTys;
05528     SmallVector<uint64_t, 4> Offsets;
05529     RetTy = FTy->getReturnType();
05530     ComputeValueVTs(*TLI, RetTy, RetTys, &Offsets);
05531 
05532     unsigned NumValues = RetTys.size();
05533     SmallVector<SDValue, 4> Values(NumValues);
05534     SmallVector<SDValue, 4> Chains(NumValues);
05535 
05536     for (unsigned i = 0; i < NumValues; ++i) {
05537       SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT,
05538                                 DemoteStackSlot,
05539                                 DAG.getConstant(Offsets[i], PtrVT));
05540       SDValue L = DAG.getLoad(RetTys[i], getCurSDLoc(), Result.second, Add,
05541                   MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
05542                               false, false, false, 1);
05543       Values[i] = L;
05544       Chains[i] = L.getValue(1);
05545     }
05546 
05547     SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
05548                                 MVT::Other, &Chains[0], NumValues);
05549     PendingLoads.push_back(Chain);
05550 
05551     setValue(CS.getInstruction(),
05552              DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
05553                          DAG.getVTList(RetTys),
05554                          &Values[0], Values.size()));
05555   }
05556 
05557   if (!Result.second.getNode()) {
05558     // As a special case, a null chain means that a tail call has been emitted
05559     // and the DAG root is already updated.
05560     HasTailCall = true;
05561 
05562     // Since there's no actual continuation from this block, nothing can be
05563     // relying on us setting vregs for them.
05564     PendingExports.clear();
05565   } else {
05566     DAG.setRoot(Result.second);
05567   }
05568 
05569   if (LandingPad) {
05570     // Insert a label at the end of the invoke call to mark the try range.  This
05571     // can be used to detect deletion of the invoke via the MachineModuleInfo.
05572     MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
05573     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
05574 
05575     // Inform MachineModuleInfo of range.
05576     MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
05577   }
05578 }
05579 
05580 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
05581 /// value is equal or not-equal to zero.
05582 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
05583   for (const User *U : V->users()) {
05584     if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
05585       if (IC->isEquality())
05586         if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
05587           if (C->isNullValue())
05588             continue;
05589     // Unknown instruction.
05590     return false;
05591   }
05592   return true;
05593 }
05594 
05595 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
05596                              Type *LoadTy,
05597                              SelectionDAGBuilder &Builder) {
05598 
05599   // Check to see if this load can be trivially constant folded, e.g. if the
05600   // input is from a string literal.
05601   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
05602     // Cast pointer to the type we really want to load.
05603     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
05604                                          PointerType::getUnqual(LoadTy));
05605 
05606     if (const Constant *LoadCst =
05607           ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
05608                                        Builder.DL))
05609       return Builder.getValue(LoadCst);
05610   }
05611 
05612   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
05613   // still constant memory, the input chain can be the entry node.
05614   SDValue Root;
05615   bool ConstantMemory = false;
05616 
05617   // Do not serialize (non-volatile) loads of constant memory with anything.
05618   if (Builder.AA->pointsToConstantMemory(PtrVal)) {
05619     Root = Builder.DAG.getEntryNode();
05620     ConstantMemory = true;
05621   } else {
05622     // Do not serialize non-volatile loads against each other.
05623     Root = Builder.DAG.getRoot();
05624   }
05625 
05626   SDValue Ptr = Builder.getValue(PtrVal);
05627   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
05628                                         Ptr, MachinePointerInfo(PtrVal),
05629                                         false /*volatile*/,
05630                                         false /*nontemporal*/,
05631                                         false /*isinvariant*/, 1 /* align=1 */);
05632 
05633   if (!ConstantMemory)
05634     Builder.PendingLoads.push_back(LoadVal.getValue(1));
05635   return LoadVal;
05636 }
05637 
05638 /// processIntegerCallValue - Record the value for an instruction that
05639 /// produces an integer result, converting the type where necessary.
05640 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
05641                                                   SDValue Value,
05642                                                   bool IsSigned) {
05643   EVT VT = TM.getTargetLowering()->getValueType(I.getType(), true);
05644   if (IsSigned)
05645     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
05646   else
05647     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
05648   setValue(&I, Value);
05649 }
05650 
05651 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
05652 /// If so, return true and lower it, otherwise return false and it will be
05653 /// lowered like a normal call.
05654 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
05655   // Verify that the prototype makes sense.  int memcmp(void*,void*,size_t)
05656   if (I.getNumArgOperands() != 3)
05657     return false;
05658 
05659   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
05660   if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
05661       !I.getArgOperand(2)->getType()->isIntegerTy() ||
05662       !I.getType()->isIntegerTy())
05663     return false;
05664 
05665   const Value *Size = I.getArgOperand(2);
05666   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
05667   if (CSize && CSize->getZExtValue() == 0) {
05668     EVT CallVT = TM.getTargetLowering()->getValueType(I.getType(), true);
05669     setValue(&I, DAG.getConstant(0, CallVT));
05670     return true;
05671   }
05672 
05673   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05674   std::pair<SDValue, SDValue> Res =
05675     TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
05676                                 getValue(LHS), getValue(RHS), getValue(Size),
05677                                 MachinePointerInfo(LHS),
05678                                 MachinePointerInfo(RHS));
05679   if (Res.first.getNode()) {
05680     processIntegerCallValue(I, Res.first, true);
05681     PendingLoads.push_back(Res.second);
05682     return true;
05683   }
05684 
05685   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
05686   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
05687   if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
05688     bool ActuallyDoIt = true;
05689     MVT LoadVT;
05690     Type *LoadTy;
05691     switch (CSize->getZExtValue()) {
05692     default:
05693       LoadVT = MVT::Other;
05694       LoadTy = nullptr;
05695       ActuallyDoIt = false;
05696       break;
05697     case 2:
05698       LoadVT = MVT::i16;
05699       LoadTy = Type::getInt16Ty(CSize->getContext());
05700       break;
05701     case 4:
05702       LoadVT = MVT::i32;
05703       LoadTy = Type::getInt32Ty(CSize->getContext());
05704       break;
05705     case 8:
05706       LoadVT = MVT::i64;
05707       LoadTy = Type::getInt64Ty(CSize->getContext());
05708       break;
05709         /*
05710     case 16:
05711       LoadVT = MVT::v4i32;
05712       LoadTy = Type::getInt32Ty(CSize->getContext());
05713       LoadTy = VectorType::get(LoadTy, 4);
05714       break;
05715          */
05716     }
05717 
05718     // This turns into unaligned loads.  We only do this if the target natively
05719     // supports the MVT we'll be loading or if it is small enough (<= 4) that
05720     // we'll only produce a small number of byte loads.
05721 
05722     // Require that we can find a legal MVT, and only do this if the target
05723     // supports unaligned loads of that type.  Expanding into byte loads would
05724     // bloat the code.
05725     const TargetLowering *TLI = TM.getTargetLowering();
05726     if (ActuallyDoIt && CSize->getZExtValue() > 4) {
05727       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
05728       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
05729       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
05730       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
05731       if (!TLI->isTypeLegal(LoadVT) ||
05732           !TLI->allowsUnalignedMemoryAccesses(LoadVT, SrcAS) ||
05733           !TLI->allowsUnalignedMemoryAccesses(LoadVT, DstAS))
05734         ActuallyDoIt = false;
05735     }
05736 
05737     if (ActuallyDoIt) {
05738       SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
05739       SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
05740 
05741       SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
05742                                  ISD::SETNE);
05743       processIntegerCallValue(I, Res, false);
05744       return true;
05745     }
05746   }
05747 
05748 
05749   return false;
05750 }
05751 
05752 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
05753 /// form.  If so, return true and lower it, otherwise return false and it
05754 /// will be lowered like a normal call.
05755 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
05756   // Verify that the prototype makes sense.  void *memchr(void *, int, size_t)
05757   if (I.getNumArgOperands() != 3)
05758     return false;
05759 
05760   const Value *Src = I.getArgOperand(0);
05761   const Value *Char = I.getArgOperand(1);
05762   const Value *Length = I.getArgOperand(2);
05763   if (!Src->getType()->isPointerTy() ||
05764       !Char->getType()->isIntegerTy() ||
05765       !Length->getType()->isIntegerTy() ||
05766       !I.getType()->isPointerTy())
05767     return false;
05768 
05769   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05770   std::pair<SDValue, SDValue> Res =
05771     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
05772                                 getValue(Src), getValue(Char), getValue(Length),
05773                                 MachinePointerInfo(Src));
05774   if (Res.first.getNode()) {
05775     setValue(&I, Res.first);
05776     PendingLoads.push_back(Res.second);
05777     return true;
05778   }
05779 
05780   return false;
05781 }
05782 
05783 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
05784 /// optimized form.  If so, return true and lower it, otherwise return false
05785 /// and it will be lowered like a normal call.
05786 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
05787   // Verify that the prototype makes sense.  char *strcpy(char *, char *)
05788   if (I.getNumArgOperands() != 2)
05789     return false;
05790 
05791   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
05792   if (!Arg0->getType()->isPointerTy() ||
05793       !Arg1->getType()->isPointerTy() ||
05794       !I.getType()->isPointerTy())
05795     return false;
05796 
05797   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05798   std::pair<SDValue, SDValue> Res =
05799     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
05800                                 getValue(Arg0), getValue(Arg1),
05801                                 MachinePointerInfo(Arg0),
05802                                 MachinePointerInfo(Arg1), isStpcpy);
05803   if (Res.first.getNode()) {
05804     setValue(&I, Res.first);
05805     DAG.setRoot(Res.second);
05806     return true;
05807   }
05808 
05809   return false;
05810 }
05811 
05812 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
05813 /// If so, return true and lower it, otherwise return false and it will be
05814 /// lowered like a normal call.
05815 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
05816   // Verify that the prototype makes sense.  int strcmp(void*,void*)
05817   if (I.getNumArgOperands() != 2)
05818     return false;
05819 
05820   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
05821   if (!Arg0->getType()->isPointerTy() ||
05822       !Arg1->getType()->isPointerTy() ||
05823       !I.getType()->isIntegerTy())
05824     return false;
05825 
05826   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05827   std::pair<SDValue, SDValue> Res =
05828     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
05829                                 getValue(Arg0), getValue(Arg1),
05830                                 MachinePointerInfo(Arg0),
05831                                 MachinePointerInfo(Arg1));
05832   if (Res.first.getNode()) {
05833     processIntegerCallValue(I, Res.first, true);
05834     PendingLoads.push_back(Res.second);
05835     return true;
05836   }
05837 
05838   return false;
05839 }
05840 
05841 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
05842 /// form.  If so, return true and lower it, otherwise return false and it
05843 /// will be lowered like a normal call.
05844 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
05845   // Verify that the prototype makes sense.  size_t strlen(char *)
05846   if (I.getNumArgOperands() != 1)
05847     return false;
05848 
05849   const Value *Arg0 = I.getArgOperand(0);
05850   if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
05851     return false;
05852 
05853   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05854   std::pair<SDValue, SDValue> Res =
05855     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
05856                                 getValue(Arg0), MachinePointerInfo(Arg0));
05857   if (Res.first.getNode()) {
05858     processIntegerCallValue(I, Res.first, false);
05859     PendingLoads.push_back(Res.second);
05860     return true;
05861   }
05862 
05863   return false;
05864 }
05865 
05866 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
05867 /// form.  If so, return true and lower it, otherwise return false and it
05868 /// will be lowered like a normal call.
05869 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
05870   // Verify that the prototype makes sense.  size_t strnlen(char *, size_t)
05871   if (I.getNumArgOperands() != 2)
05872     return false;
05873 
05874   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
05875   if (!Arg0->getType()->isPointerTy() ||
05876       !Arg1->getType()->isIntegerTy() ||
05877       !I.getType()->isIntegerTy())
05878     return false;
05879 
05880   const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
05881   std::pair<SDValue, SDValue> Res =
05882     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
05883                                  getValue(Arg0), getValue(Arg1),
05884                                  MachinePointerInfo(Arg0));
05885   if (Res.first.getNode()) {
05886     processIntegerCallValue(I, Res.first, false);
05887     PendingLoads.push_back(Res.second);
05888     return true;
05889   }
05890 
05891   return false;
05892 }
05893 
05894 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
05895 /// operation (as expected), translate it to an SDNode with the specified opcode
05896 /// and return true.
05897 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
05898                                               unsigned Opcode) {
05899   // Sanity check that it really is a unary floating-point call.
05900   if (I.getNumArgOperands() != 1 ||
05901       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
05902       I.getType() != I.getArgOperand(0)->getType() ||
05903       !I.onlyReadsMemory())
05904     return false;
05905 
05906   SDValue Tmp = getValue(I.getArgOperand(0));
05907   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
05908   return true;
05909 }
05910 
05911 void SelectionDAGBuilder::visitCall(const CallInst &I) {
05912   // Handle inline assembly differently.
05913   if (isa<InlineAsm>(I.getCalledValue())) {
05914     visitInlineAsm(&I);
05915     return;
05916   }
05917 
05918   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
05919   ComputeUsesVAFloatArgument(I, &MMI);
05920 
05921   const char *RenameFn = nullptr;
05922   if (Function *F = I.getCalledFunction()) {
05923     if (F->isDeclaration()) {
05924       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
05925         if (unsigned IID = II->getIntrinsicID(F)) {
05926           RenameFn = visitIntrinsicCall(I, IID);
05927           if (!RenameFn)
05928             return;
05929         }
05930       }
05931       if (unsigned IID = F->getIntrinsicID()) {
05932         RenameFn = visitIntrinsicCall(I, IID);
05933         if (!RenameFn)
05934           return;
05935       }
05936     }
05937 
05938     // Check for well-known libc/libm calls.  If the function is internal, it
05939     // can't be a library call.
05940     LibFunc::Func Func;
05941     if (!F->hasLocalLinkage() && F->hasName() &&
05942         LibInfo->getLibFunc(F->getName(), Func) &&
05943         LibInfo->hasOptimizedCodeGen(Func)) {
05944       switch (Func) {
05945       default: break;
05946       case LibFunc::copysign:
05947       case LibFunc::copysignf:
05948       case LibFunc::copysignl:
05949         if (I.getNumArgOperands() == 2 &&   // Basic sanity checks.
05950             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
05951             I.getType() == I.getArgOperand(0)->getType() &&
05952             I.getType() == I.getArgOperand(1)->getType() &&
05953             I.onlyReadsMemory()) {
05954           SDValue LHS = getValue(I.getArgOperand(0));
05955           SDValue RHS = getValue(I.getArgOperand(1));
05956           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
05957                                    LHS.getValueType(), LHS, RHS));
05958           return;
05959         }
05960         break;
05961       case LibFunc::fabs:
05962       case LibFunc::fabsf:
05963       case LibFunc::fabsl:
05964         if (visitUnaryFloatCall(I, ISD::FABS))
05965           return;
05966         break;
05967       case LibFunc::sin:
05968       case LibFunc::sinf:
05969       case LibFunc::sinl:
05970         if (visitUnaryFloatCall(I, ISD::FSIN))
05971           return;
05972         break;
05973       case LibFunc::cos:
05974       case LibFunc::cosf:
05975       case LibFunc::cosl:
05976         if (visitUnaryFloatCall(I, ISD::FCOS))
05977           return;
05978         break;
05979       case LibFunc::sqrt:
05980       case LibFunc::sqrtf:
05981       case LibFunc::sqrtl:
05982       case LibFunc::sqrt_finite:
05983       case LibFunc::sqrtf_finite:
05984       case LibFunc::sqrtl_finite:
05985         if (visitUnaryFloatCall(I, ISD::FSQRT))
05986           return;
05987         break;
05988       case LibFunc::floor:
05989       case LibFunc::floorf:
05990       case LibFunc::floorl:
05991         if (visitUnaryFloatCall(I, ISD::FFLOOR))
05992           return;
05993         break;
05994       case LibFunc::nearbyint:
05995       case LibFunc::nearbyintf:
05996       case LibFunc::nearbyintl:
05997         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
05998           return;
05999         break;
06000       case LibFunc::ceil:
06001       case LibFunc::ceilf:
06002       case LibFunc::ceill:
06003         if (visitUnaryFloatCall(I, ISD::FCEIL))
06004           return;
06005         break;
06006       case LibFunc::rint:
06007       case LibFunc::rintf:
06008       case LibFunc::rintl:
06009         if (visitUnaryFloatCall(I, ISD::FRINT))
06010           return;
06011         break;
06012       case LibFunc::round:
06013       case LibFunc::roundf:
06014       case LibFunc::roundl:
06015         if (visitUnaryFloatCall(I, ISD::FROUND))
06016           return;
06017         break;
06018       case LibFunc::trunc:
06019       case LibFunc::truncf:
06020       case LibFunc::truncl:
06021         if (visitUnaryFloatCall(I, ISD::FTRUNC))
06022           return;
06023         break;
06024       case LibFunc::log2:
06025       case LibFunc::log2f:
06026       case LibFunc::log2l:
06027         if (visitUnaryFloatCall(I, ISD::FLOG2))
06028           return;
06029         break;
06030       case LibFunc::exp2:
06031       case LibFunc::exp2f:
06032       case LibFunc::exp2l:
06033         if (visitUnaryFloatCall(I, ISD::FEXP2))
06034           return;
06035         break;
06036       case LibFunc::memcmp:
06037         if (visitMemCmpCall(I))
06038           return;
06039         break;
06040       case LibFunc::memchr:
06041         if (visitMemChrCall(I))
06042           return;
06043         break;
06044       case LibFunc::strcpy:
06045         if (visitStrCpyCall(I, false))
06046           return;
06047         break;
06048       case LibFunc::stpcpy:
06049         if (visitStrCpyCall(I, true))
06050           return;
06051         break;
06052       case LibFunc::strcmp:
06053         if (visitStrCmpCall(I))
06054           return;
06055         break;
06056       case LibFunc::strlen:
06057         if (visitStrLenCall(I))
06058           return;
06059         break;
06060       case LibFunc::strnlen:
06061         if (visitStrNLenCall(I))
06062           return;
06063         break;
06064       }
06065     }
06066   }
06067 
06068   SDValue Callee;
06069   if (!RenameFn)
06070     Callee = getValue(I.getCalledValue());
06071   else
06072     Callee = DAG.getExternalSymbol(RenameFn,
06073                                    TM.getTargetLowering()->getPointerTy());
06074 
06075   // Check if we can potentially perform a tail call. More detailed checking is
06076   // be done within LowerCallTo, after more information about the call is known.
06077   LowerCallTo(&I, Callee, I.isTailCall());
06078 }
06079 
06080 namespace {
06081 
06082 /// AsmOperandInfo - This contains information for each constraint that we are
06083 /// lowering.
06084 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
06085 public:
06086   /// CallOperand - If this is the result output operand or a clobber
06087   /// this is null, otherwise it is the incoming operand to the CallInst.
06088   /// This gets modified as the asm is processed.
06089   SDValue CallOperand;
06090 
06091   /// AssignedRegs - If this is a register or register class operand, this
06092   /// contains the set of register corresponding to the operand.
06093   RegsForValue AssignedRegs;
06094 
06095   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
06096     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
06097   }
06098 
06099   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
06100   /// corresponds to.  If there is no Value* for this operand, it returns
06101   /// MVT::Other.
06102   EVT getCallOperandValEVT(LLVMContext &Context,
06103                            const TargetLowering &TLI,
06104                            const DataLayout *DL) const {
06105     if (!CallOperandVal) return MVT::Other;
06106 
06107     if (isa<BasicBlock>(CallOperandVal))
06108       return TLI.getPointerTy();
06109 
06110     llvm::Type *OpTy = CallOperandVal->getType();
06111 
06112     // FIXME: code duplicated from TargetLowering::ParseConstraints().
06113     // If this is an indirect operand, the operand is a pointer to the
06114     // accessed type.
06115     if (isIndirect) {
06116       llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
06117       if (!PtrTy)
06118         report_fatal_error("Indirect operand for inline asm not a pointer!");
06119       OpTy = PtrTy->getElementType();
06120     }
06121 
06122     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
06123     if (StructType *STy = dyn_cast<StructType>(OpTy))
06124       if (STy->getNumElements() == 1)
06125         OpTy = STy->getElementType(0);
06126 
06127     // If OpTy is not a single value, it may be a struct/union that we
06128     // can tile with integers.
06129     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
06130       unsigned BitSize = DL->getTypeSizeInBits(OpTy);
06131       switch (BitSize) {
06132       default: break;
06133       case 1:
06134       case 8:
06135       case 16:
06136       case 32:
06137       case 64:
06138       case 128:
06139         OpTy = IntegerType::get(Context, BitSize);
06140         break;
06141       }
06142     }
06143 
06144     return TLI.getValueType(OpTy, true);
06145   }
06146 };
06147 
06148 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
06149 
06150 } // end anonymous namespace
06151 
06152 /// GetRegistersForValue - Assign registers (virtual or physical) for the
06153 /// specified operand.  We prefer to assign virtual registers, to allow the
06154 /// register allocator to handle the assignment process.  However, if the asm
06155 /// uses features that we can't model on machineinstrs, we have SDISel do the
06156 /// allocation.  This produces generally horrible, but correct, code.
06157 ///
06158 ///   OpInfo describes the operand.
06159 ///
06160 static void GetRegistersForValue(SelectionDAG &DAG,
06161                                  const TargetLowering &TLI,
06162                                  SDLoc DL,
06163                                  SDISelAsmOperandInfo &OpInfo) {
06164   LLVMContext &Context = *DAG.getContext();
06165 
06166   MachineFunction &MF = DAG.getMachineFunction();
06167   SmallVector<unsigned, 4> Regs;
06168 
06169   // If this is a constraint for a single physreg, or a constraint for a
06170   // register class, find it.
06171   std::pair<unsigned, const TargetRegisterClass*> PhysReg =
06172     TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
06173                                      OpInfo.ConstraintVT);
06174 
06175   unsigned NumRegs = 1;
06176   if (OpInfo.ConstraintVT != MVT::Other) {
06177     // If this is a FP input in an integer register (or visa versa) insert a bit
06178     // cast of the input value.  More generally, handle any case where the input
06179     // value disagrees with the register class we plan to stick this in.
06180     if (OpInfo.Type == InlineAsm::isInput &&
06181         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
06182       // Try to convert to the first EVT that the reg class contains.  If the
06183       // types are identical size, use a bitcast to convert (e.g. two differing
06184       // vector types).
06185       MVT RegVT = *PhysReg.second->vt_begin();
06186       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
06187         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
06188                                          RegVT, OpInfo.CallOperand);
06189         OpInfo.ConstraintVT = RegVT;
06190       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
06191         // If the input is a FP value and we want it in FP registers, do a
06192         // bitcast to the corresponding integer type.  This turns an f64 value
06193         // into i64, which can be passed with two i32 values on a 32-bit
06194         // machine.
06195         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
06196         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
06197                                          RegVT, OpInfo.CallOperand);
06198         OpInfo.ConstraintVT = RegVT;
06199       }
06200     }
06201 
06202     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
06203   }
06204 
06205   MVT RegVT;
06206   EVT ValueVT = OpInfo.ConstraintVT;
06207 
06208   // If this is a constraint for a specific physical register, like {r17},
06209   // assign it now.
06210   if (unsigned AssignedReg = PhysReg.first) {
06211     const TargetRegisterClass *RC = PhysReg.second;
06212     if (OpInfo.ConstraintVT == MVT::Other)
06213       ValueVT = *RC->vt_begin();
06214 
06215     // Get the actual register value type.  This is important, because the user
06216     // may have asked for (e.g.) the AX register in i32 type.  We need to
06217     // remember that AX is actually i16 to get the right extension.
06218     RegVT = *RC->vt_begin();
06219 
06220     // This is a explicit reference to a physical register.
06221     Regs.push_back(AssignedReg);
06222 
06223     // If this is an expanded reference, add the rest of the regs to Regs.
06224     if (NumRegs != 1) {
06225       TargetRegisterClass::iterator I = RC->begin();
06226       for (; *I != AssignedReg; ++I)
06227         assert(I != RC->end() && "Didn't find reg!");
06228 
06229       // Already added the first reg.
06230       --NumRegs; ++I;
06231       for (; NumRegs; --NumRegs, ++I) {
06232         assert(I != RC->end() && "Ran out of registers to allocate!");
06233         Regs.push_back(*I);
06234       }
06235     }
06236 
06237     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
06238     return;
06239   }
06240 
06241   // Otherwise, if this was a reference to an LLVM register class, create vregs
06242   // for this reference.
06243   if (const TargetRegisterClass *RC = PhysReg.second) {
06244     RegVT = *RC->vt_begin();
06245     if (OpInfo.ConstraintVT == MVT::Other)
06246       ValueVT = RegVT;
06247 
06248     // Create the appropriate number of virtual registers.
06249     MachineRegisterInfo &RegInfo = MF.getRegInfo();
06250     for (; NumRegs; --NumRegs)
06251