SelectionDAGBuilder.cpp revision 10c6d12a9fd4dab411091f64db4db69670b88850
1f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal//===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===// 2f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal// 3f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal// The LLVM Compiler Infrastructure 4f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal// 5f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal// This file is distributed under the University of Illinois Open Source 63cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal// License. See LICENSE.TXT for details. 73cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal// 83cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal//===----------------------------------------------------------------------===// 93cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal// 10f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal// This implements routines for translating from LLVM IR into SelectionDAG IR. 11f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal// 12f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal//===----------------------------------------------------------------------===// 133cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal 143cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal#define DEBUG_TYPE "isel" 153cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal#include "SDNodeDbgValue.h" 163cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal#include "SelectionDAGBuilder.h" 173cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal#include "llvm/ADT/BitVector.h" 183cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal#include "llvm/ADT/PostOrderIterator.h" 19f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/ADT/SmallSet.h" 20f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Analysis/AliasAnalysis.h" 21f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Analysis/ConstantFolding.h" 22f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Constants.h" 23f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CallingConv.h" 242a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal#include "llvm/DerivedTypes.h" 252a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal#include "llvm/Function.h" 263cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal#include "llvm/GlobalVariable.h" 273cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal#include "llvm/InlineAsm.h" 28f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Instructions.h" 29f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Intrinsics.h" 30f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/IntrinsicInst.h" 31f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/LLVMContext.h" 32f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Module.h" 33f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/Analysis.h" 34f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/FastISel.h" 35f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/FunctionLoweringInfo.h" 36f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/GCStrategy.h" 37f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/GCMetadata.h" 38f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/MachineFunction.h" 39f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/MachineFrameInfo.h" 40f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/MachineInstrBuilder.h" 41f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/MachineJumpTableInfo.h" 42f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/MachineModuleInfo.h" 43f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/MachineRegisterInfo.h" 44f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/PseudoSourceValue.h" 45f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/CodeGen/SelectionDAG.h" 46f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Analysis/DebugInfo.h" 47f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Target/TargetData.h" 48f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Target/TargetFrameLowering.h" 49f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Target/TargetInstrInfo.h" 50f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Target/TargetIntrinsicInfo.h" 51f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Target/TargetLowering.h" 52f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Target/TargetOptions.h" 53f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Support/CommandLine.h" 54f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Support/Debug.h" 55f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Support/ErrorHandling.h" 56f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Support/MathExtras.h" 57f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include "llvm/Support/raw_ostream.h" 58f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal#include <algorithm> 59f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwalusing namespace llvm; 60f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal 61f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal/// LimitFloatPrecision - Generate low-precision inline sequences for 62f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal/// some float libcalls (6, 8 or 12 bits). 63f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwalstatic unsigned LimitFloatPrecision; 642a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal 652a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwalstatic cl::opt<unsigned, true> 663cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak AggarwalLimitFPPrecision("limit-float-precision", 672a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal cl::desc("Generate low-precision inline sequences " 682a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal "for some float libcalls"), 693cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal cl::location(LimitFloatPrecision), 703cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal cl::init(0)); 712a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal 722a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// Limit the width of DAG chains. This is important in general to prevent 732a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// prevent DAG-based analysis from blowing up. For example, alias analysis and 742a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// load clustering may not complete in reasonable time. It is difficult to 752a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// recognize and avoid this situation within each individual analysis, and 762a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// future analyses are likely to have the same behavior. Limiting DAG width is 772a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// the safe approach, and will be especially important with global DAGs. 782a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// 792a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// MaxParallelChains default is arbitrarily high to avoid affecting 802a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// optimization, but could be lowered to improve compile time. Any ld-ld-st-st 812a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// sequence over this should have been converted to llvm.memcpy by the 822a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// frontend. It easy to induce this behavior with .ll code such as: 832a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// %buffer = alloca [4096 x i8] 842a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// %data = load [4096 x i8]* %argPtr 852a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal// store [4096 x i8] %data, [4096 x i8]* %buffer 862a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwalstatic const unsigned MaxParallelChains = 64; 872a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal 882a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwalstatic SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL, 892a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal const SDValue *Parts, unsigned NumParts, 902a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal EVT PartVT, EVT ValueVT); 912a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal 922a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal/// getCopyFromParts - Create a value that contains the specified legal parts 933cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal/// combined into the value they represent. If the parts combine to a type 94f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal/// larger then ValueVT then AssertOp can be used to specify whether the extra 953cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 96f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal/// (ISD::AssertSext). 97f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwalstatic SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc DL, 98f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal const SDValue *Parts, 99f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal unsigned NumParts, EVT PartVT, EVT ValueVT, 100f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal ISD::NodeType AssertOp = ISD::DELETED_NODE) { 101f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal if (ValueVT.isVector()) 1022a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT); 1032a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal 1042a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal assert(NumParts > 0 && "No parts to assemble!"); 1052a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1062a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal SDValue Val = Parts[0]; 107f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal 108f94e0fb97765a9927e21028499f43771264f37cbSarthak Aggarwal if (NumParts > 1) { 1093cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal // Assemble the value from multiple parts. 1103cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal if (ValueVT.isInteger()) { 1113cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal unsigned PartBits = PartVT.getSizeInBits(); 1123cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal unsigned ValueBits = ValueVT.getSizeInBits(); 1133cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal 1143cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal // Assemble the power of 2 part. 1153cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal unsigned RoundParts = NumParts & (NumParts - 1) ? 1162a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal 1 << Log2_32(NumParts) : NumParts; 1173cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal unsigned RoundBits = PartBits * RoundParts; 1183cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal EVT RoundVT = RoundBits == ValueBits ? 1193cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 1203cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal SDValue Lo, Hi; 1213cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal 1223cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 1233cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal 1243cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal if (RoundParts > 2) { 1253cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 1263cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal PartVT, HalfVT); 1273cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 1283cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal RoundParts / 2, PartVT, HalfVT); 1293cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal } else { 1303cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 1313cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 1323cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal } 1332a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal 1342a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal if (TLI.isBigEndian()) 1353cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal std::swap(Lo, Hi); 1362a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal 1372a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 1383cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal 1392a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal if (RoundParts < NumParts) { 1402a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal // Assemble the trailing non-power-of-2 part. 1412a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal unsigned OddParts = NumParts - RoundParts; 1422a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 1432a0736ac288d2057129b5b8961cc5536066493c6Sarthak Aggarwal Hi = getCopyFromParts(DAG, DL, 1443cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal Parts + RoundParts, OddParts, PartVT, OddVT); 1453cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal 1463cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal // Combine the round and odd parts. 1473cf002e003ada481d0aae4ba77bb05f95be216c7Sarthak Aggarwal Lo = Val; 148 if (TLI.isBigEndian()) 149 std::swap(Lo, Hi); 150 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 151 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 152 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 153 DAG.getConstant(Lo.getValueType().getSizeInBits(), 154 TLI.getPointerTy())); 155 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 156 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 157 } 158 } else if (PartVT.isFloatingPoint()) { 159 // FP split into multiple FP parts (for ppcf128) 160 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) && 161 "Unexpected split"); 162 SDValue Lo, Hi; 163 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 164 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 165 if (TLI.isBigEndian()) 166 std::swap(Lo, Hi); 167 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 168 } else { 169 // FP split into integer parts (soft fp) 170 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 171 !PartVT.isVector() && "Unexpected split"); 172 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 173 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT); 174 } 175 } 176 177 // There is now one part, held in Val. Correct it to match ValueVT. 178 PartVT = Val.getValueType(); 179 180 if (PartVT == ValueVT) 181 return Val; 182 183 if (PartVT.isInteger() && ValueVT.isInteger()) { 184 if (ValueVT.bitsLT(PartVT)) { 185 // For a truncate, see if we have any information to 186 // indicate whether the truncated bits will always be 187 // zero or sign-extension. 188 if (AssertOp != ISD::DELETED_NODE) 189 Val = DAG.getNode(AssertOp, DL, PartVT, Val, 190 DAG.getValueType(ValueVT)); 191 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 192 } 193 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 194 } 195 196 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 197 // FP_ROUND's are always exact here. 198 if (ValueVT.bitsLT(Val.getValueType())) 199 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, 200 DAG.getIntPtrConstant(1)); 201 202 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 203 } 204 205 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) 206 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 207 208 llvm_unreachable("Unknown mismatch!"); 209 return SDValue(); 210} 211 212/// getCopyFromParts - Create a value that contains the specified legal parts 213/// combined into the value they represent. If the parts combine to a type 214/// larger then ValueVT then AssertOp can be used to specify whether the extra 215/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 216/// (ISD::AssertSext). 217static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL, 218 const SDValue *Parts, unsigned NumParts, 219 EVT PartVT, EVT ValueVT) { 220 assert(ValueVT.isVector() && "Not a vector value"); 221 assert(NumParts > 0 && "No parts to assemble!"); 222 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 223 SDValue Val = Parts[0]; 224 225 // Handle a multi-element vector. 226 if (NumParts > 1) { 227 EVT IntermediateVT, RegisterVT; 228 unsigned NumIntermediates; 229 unsigned NumRegs = 230 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 231 NumIntermediates, RegisterVT); 232 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 233 NumParts = NumRegs; // Silence a compiler warning. 234 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 235 assert(RegisterVT == Parts[0].getValueType() && 236 "Part type doesn't match part!"); 237 238 // Assemble the parts into intermediate operands. 239 SmallVector<SDValue, 8> Ops(NumIntermediates); 240 if (NumIntermediates == NumParts) { 241 // If the register was not expanded, truncate or copy the value, 242 // as appropriate. 243 for (unsigned i = 0; i != NumParts; ++i) 244 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 245 PartVT, IntermediateVT); 246 } else if (NumParts > 0) { 247 // If the intermediate type was expanded, build the intermediate 248 // operands from the parts. 249 assert(NumParts % NumIntermediates == 0 && 250 "Must expand into a divisible number of parts!"); 251 unsigned Factor = NumParts / NumIntermediates; 252 for (unsigned i = 0; i != NumIntermediates; ++i) 253 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 254 PartVT, IntermediateVT); 255 } 256 257 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 258 // intermediate operands. 259 Val = DAG.getNode(IntermediateVT.isVector() ? 260 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL, 261 ValueVT, &Ops[0], NumIntermediates); 262 } 263 264 // There is now one part, held in Val. Correct it to match ValueVT. 265 PartVT = Val.getValueType(); 266 267 if (PartVT == ValueVT) 268 return Val; 269 270 if (PartVT.isVector()) { 271 // If the element type of the source/dest vectors are the same, but the 272 // parts vector has more elements than the value vector, then we have a 273 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 274 // elements we want. 275 if (PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 276 assert(PartVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 277 "Cannot narrow, it would be a lossy transformation"); 278 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 279 DAG.getIntPtrConstant(0)); 280 } 281 282 // Vector/Vector bitcast. 283 if (ValueVT.getSizeInBits() == PartVT.getSizeInBits()) 284 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 285 286 assert(PartVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 287 "Cannot handle this kind of promotion"); 288 // Promoted vector extract 289 bool Smaller = ValueVT.bitsLE(PartVT); 290 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 291 DL, ValueVT, Val); 292 293 } 294 295 // Trivial bitcast if the types are the same size and the destination 296 // vector type is legal. 297 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits() && 298 TLI.isTypeLegal(ValueVT)) 299 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 300 301 // Handle cases such as i8 -> <1 x i1> 302 assert(ValueVT.getVectorNumElements() == 1 && 303 "Only trivial scalar-to-vector conversions should get here!"); 304 305 if (ValueVT.getVectorNumElements() == 1 && 306 ValueVT.getVectorElementType() != PartVT) { 307 bool Smaller = ValueVT.bitsLE(PartVT); 308 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 309 DL, ValueVT.getScalarType(), Val); 310 } 311 312 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val); 313} 314 315 316 317 318static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc dl, 319 SDValue Val, SDValue *Parts, unsigned NumParts, 320 EVT PartVT); 321 322/// getCopyToParts - Create a series of nodes that contain the specified value 323/// split into legal parts. If the parts contain more bits than Val, then, for 324/// integers, ExtendKind can be used to specify how to generate the extra bits. 325static void getCopyToParts(SelectionDAG &DAG, DebugLoc DL, 326 SDValue Val, SDValue *Parts, unsigned NumParts, 327 EVT PartVT, 328 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 329 EVT ValueVT = Val.getValueType(); 330 331 // Handle the vector case separately. 332 if (ValueVT.isVector()) 333 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT); 334 335 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 336 unsigned PartBits = PartVT.getSizeInBits(); 337 unsigned OrigNumParts = NumParts; 338 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!"); 339 340 if (NumParts == 0) 341 return; 342 343 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 344 if (PartVT == ValueVT) { 345 assert(NumParts == 1 && "No-op copy with multiple parts!"); 346 Parts[0] = Val; 347 return; 348 } 349 350 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 351 // If the parts cover more bits than the value has, promote the value. 352 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 353 assert(NumParts == 1 && "Do not know what to promote to!"); 354 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 355 } else { 356 assert(PartVT.isInteger() && ValueVT.isInteger() && 357 "Unknown mismatch!"); 358 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 359 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 360 } 361 } else if (PartBits == ValueVT.getSizeInBits()) { 362 // Different types of the same size. 363 assert(NumParts == 1 && PartVT != ValueVT); 364 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 365 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 366 // If the parts cover less bits than value has, truncate the value. 367 assert(PartVT.isInteger() && ValueVT.isInteger() && 368 "Unknown mismatch!"); 369 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 370 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 371 } 372 373 // The value may have changed - recompute ValueVT. 374 ValueVT = Val.getValueType(); 375 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 376 "Failed to tile the value with PartVT!"); 377 378 if (NumParts == 1) { 379 assert(PartVT == ValueVT && "Type conversion failed!"); 380 Parts[0] = Val; 381 return; 382 } 383 384 // Expand the value into multiple parts. 385 if (NumParts & (NumParts - 1)) { 386 // The number of parts is not a power of 2. Split off and copy the tail. 387 assert(PartVT.isInteger() && ValueVT.isInteger() && 388 "Do not know what to expand to!"); 389 unsigned RoundParts = 1 << Log2_32(NumParts); 390 unsigned RoundBits = RoundParts * PartBits; 391 unsigned OddParts = NumParts - RoundParts; 392 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 393 DAG.getIntPtrConstant(RoundBits)); 394 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT); 395 396 if (TLI.isBigEndian()) 397 // The odd parts were reversed by getCopyToParts - unreverse them. 398 std::reverse(Parts + RoundParts, Parts + NumParts); 399 400 NumParts = RoundParts; 401 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 402 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 403 } 404 405 // The number of parts is a power of 2. Repeatedly bisect the value using 406 // EXTRACT_ELEMENT. 407 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 408 EVT::getIntegerVT(*DAG.getContext(), 409 ValueVT.getSizeInBits()), 410 Val); 411 412 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 413 for (unsigned i = 0; i < NumParts; i += StepSize) { 414 unsigned ThisBits = StepSize * PartBits / 2; 415 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 416 SDValue &Part0 = Parts[i]; 417 SDValue &Part1 = Parts[i+StepSize/2]; 418 419 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 420 ThisVT, Part0, DAG.getIntPtrConstant(1)); 421 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 422 ThisVT, Part0, DAG.getIntPtrConstant(0)); 423 424 if (ThisBits == PartBits && ThisVT != PartVT) { 425 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 426 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 427 } 428 } 429 } 430 431 if (TLI.isBigEndian()) 432 std::reverse(Parts, Parts + OrigNumParts); 433} 434 435 436/// getCopyToPartsVector - Create a series of nodes that contain the specified 437/// value split into legal parts. 438static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc DL, 439 SDValue Val, SDValue *Parts, unsigned NumParts, 440 EVT PartVT) { 441 EVT ValueVT = Val.getValueType(); 442 assert(ValueVT.isVector() && "Not a vector"); 443 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 444 445 if (NumParts == 1) { 446 if (PartVT == ValueVT) { 447 // Nothing to do. 448 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 449 // Bitconvert vector->vector case. 450 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 451 } else if (PartVT.isVector() && 452 PartVT.getVectorElementType() == ValueVT.getVectorElementType() && 453 PartVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { 454 EVT ElementVT = PartVT.getVectorElementType(); 455 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 456 // undef elements. 457 SmallVector<SDValue, 16> Ops; 458 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) 459 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 460 ElementVT, Val, DAG.getIntPtrConstant(i))); 461 462 for (unsigned i = ValueVT.getVectorNumElements(), 463 e = PartVT.getVectorNumElements(); i != e; ++i) 464 Ops.push_back(DAG.getUNDEF(ElementVT)); 465 466 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size()); 467 468 // FIXME: Use CONCAT for 2x -> 4x. 469 470 //SDValue UndefElts = DAG.getUNDEF(VectorTy); 471 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); 472 } else if (PartVT.isVector() && 473 PartVT.getVectorElementType().bitsGE( 474 ValueVT.getVectorElementType()) && 475 PartVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 476 477 // Promoted vector extract 478 bool Smaller = PartVT.bitsLE(ValueVT); 479 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 480 DL, PartVT, Val); 481 } else{ 482 // Vector -> scalar conversion. 483 assert(ValueVT.getVectorNumElements() == 1 && 484 "Only trivial vector-to-scalar conversions should get here!"); 485 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 486 PartVT, Val, DAG.getIntPtrConstant(0)); 487 488 bool Smaller = ValueVT.bitsLE(PartVT); 489 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 490 DL, PartVT, Val); 491 } 492 493 Parts[0] = Val; 494 return; 495 } 496 497 // Handle a multi-element vector. 498 EVT IntermediateVT, RegisterVT; 499 unsigned NumIntermediates; 500 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, 501 IntermediateVT, 502 NumIntermediates, RegisterVT); 503 unsigned NumElements = ValueVT.getVectorNumElements(); 504 505 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 506 NumParts = NumRegs; // Silence a compiler warning. 507 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 508 509 // Split the vector into intermediate operands. 510 SmallVector<SDValue, 8> Ops(NumIntermediates); 511 for (unsigned i = 0; i != NumIntermediates; ++i) { 512 if (IntermediateVT.isVector()) 513 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, 514 IntermediateVT, Val, 515 DAG.getIntPtrConstant(i * (NumElements / NumIntermediates))); 516 else 517 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 518 IntermediateVT, Val, DAG.getIntPtrConstant(i)); 519 } 520 521 // Split the intermediate operands into legal parts. 522 if (NumParts == NumIntermediates) { 523 // If the register was not expanded, promote or copy the value, 524 // as appropriate. 525 for (unsigned i = 0; i != NumParts; ++i) 526 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT); 527 } else if (NumParts > 0) { 528 // If the intermediate type was expanded, split each the value into 529 // legal parts. 530 assert(NumParts % NumIntermediates == 0 && 531 "Must expand into a divisible number of parts!"); 532 unsigned Factor = NumParts / NumIntermediates; 533 for (unsigned i = 0; i != NumIntermediates; ++i) 534 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT); 535 } 536} 537 538 539 540 541namespace { 542 /// RegsForValue - This struct represents the registers (physical or virtual) 543 /// that a particular set of values is assigned, and the type information 544 /// about the value. The most common situation is to represent one value at a 545 /// time, but struct or array values are handled element-wise as multiple 546 /// values. The splitting of aggregates is performed recursively, so that we 547 /// never have aggregate-typed registers. The values at this point do not 548 /// necessarily have legal types, so each value may require one or more 549 /// registers of some legal type. 550 /// 551 struct RegsForValue { 552 /// ValueVTs - The value types of the values, which may not be legal, and 553 /// may need be promoted or synthesized from one or more registers. 554 /// 555 SmallVector<EVT, 4> ValueVTs; 556 557 /// RegVTs - The value types of the registers. This is the same size as 558 /// ValueVTs and it records, for each value, what the type of the assigned 559 /// register or registers are. (Individual values are never synthesized 560 /// from more than one type of register.) 561 /// 562 /// With virtual registers, the contents of RegVTs is redundant with TLI's 563 /// getRegisterType member function, however when with physical registers 564 /// it is necessary to have a separate record of the types. 565 /// 566 SmallVector<EVT, 4> RegVTs; 567 568 /// Regs - This list holds the registers assigned to the values. 569 /// Each legal or promoted value requires one register, and each 570 /// expanded value requires multiple registers. 571 /// 572 SmallVector<unsigned, 4> Regs; 573 574 RegsForValue() {} 575 576 RegsForValue(const SmallVector<unsigned, 4> ®s, 577 EVT regvt, EVT valuevt) 578 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {} 579 580 RegsForValue(LLVMContext &Context, const TargetLowering &tli, 581 unsigned Reg, Type *Ty) { 582 ComputeValueVTs(tli, Ty, ValueVTs); 583 584 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 585 EVT ValueVT = ValueVTs[Value]; 586 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT); 587 EVT RegisterVT = tli.getRegisterType(Context, ValueVT); 588 for (unsigned i = 0; i != NumRegs; ++i) 589 Regs.push_back(Reg + i); 590 RegVTs.push_back(RegisterVT); 591 Reg += NumRegs; 592 } 593 } 594 595 /// areValueTypesLegal - Return true if types of all the values are legal. 596 bool areValueTypesLegal(const TargetLowering &TLI) { 597 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 598 EVT RegisterVT = RegVTs[Value]; 599 if (!TLI.isTypeLegal(RegisterVT)) 600 return false; 601 } 602 return true; 603 } 604 605 /// append - Add the specified values to this one. 606 void append(const RegsForValue &RHS) { 607 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end()); 608 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end()); 609 Regs.append(RHS.Regs.begin(), RHS.Regs.end()); 610 } 611 612 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 613 /// this value and returns the result as a ValueVTs value. This uses 614 /// Chain/Flag as the input and updates them for the output Chain/Flag. 615 /// If the Flag pointer is NULL, no flag is used. 616 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, 617 DebugLoc dl, 618 SDValue &Chain, SDValue *Flag) const; 619 620 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 621 /// specified value into the registers specified by this object. This uses 622 /// Chain/Flag as the input and updates them for the output Chain/Flag. 623 /// If the Flag pointer is NULL, no flag is used. 624 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, 625 SDValue &Chain, SDValue *Flag) const; 626 627 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 628 /// operand list. This adds the code marker, matching input operand index 629 /// (if applicable), and includes the number of values added into it. 630 void AddInlineAsmOperands(unsigned Kind, 631 bool HasMatching, unsigned MatchingIdx, 632 SelectionDAG &DAG, 633 std::vector<SDValue> &Ops) const; 634 }; 635} 636 637/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 638/// this value and returns the result as a ValueVT value. This uses 639/// Chain/Flag as the input and updates them for the output Chain/Flag. 640/// If the Flag pointer is NULL, no flag is used. 641SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 642 FunctionLoweringInfo &FuncInfo, 643 DebugLoc dl, 644 SDValue &Chain, SDValue *Flag) const { 645 // A Value with type {} or [0 x %t] needs no registers. 646 if (ValueVTs.empty()) 647 return SDValue(); 648 649 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 650 651 // Assemble the legal parts into the final values. 652 SmallVector<SDValue, 4> Values(ValueVTs.size()); 653 SmallVector<SDValue, 8> Parts; 654 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 655 // Copy the legal parts from the registers. 656 EVT ValueVT = ValueVTs[Value]; 657 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 658 EVT RegisterVT = RegVTs[Value]; 659 660 Parts.resize(NumRegs); 661 for (unsigned i = 0; i != NumRegs; ++i) { 662 SDValue P; 663 if (Flag == 0) { 664 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 665 } else { 666 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 667 *Flag = P.getValue(2); 668 } 669 670 Chain = P.getValue(1); 671 Parts[i] = P; 672 673 // If the source register was virtual and if we know something about it, 674 // add an assert node. 675 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 676 !RegisterVT.isInteger() || RegisterVT.isVector()) 677 continue; 678 679 const FunctionLoweringInfo::LiveOutInfo *LOI = 680 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 681 if (!LOI) 682 continue; 683 684 unsigned RegSize = RegisterVT.getSizeInBits(); 685 unsigned NumSignBits = LOI->NumSignBits; 686 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes(); 687 688 // FIXME: We capture more information than the dag can represent. For 689 // now, just use the tightest assertzext/assertsext possible. 690 bool isSExt = true; 691 EVT FromVT(MVT::Other); 692 if (NumSignBits == RegSize) 693 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1 694 else if (NumZeroBits >= RegSize-1) 695 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1 696 else if (NumSignBits > RegSize-8) 697 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8 698 else if (NumZeroBits >= RegSize-8) 699 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8 700 else if (NumSignBits > RegSize-16) 701 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16 702 else if (NumZeroBits >= RegSize-16) 703 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16 704 else if (NumSignBits > RegSize-32) 705 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32 706 else if (NumZeroBits >= RegSize-32) 707 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32 708 else 709 continue; 710 711 // Add an assertion node. 712 assert(FromVT != MVT::Other); 713 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 714 RegisterVT, P, DAG.getValueType(FromVT)); 715 } 716 717 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 718 NumRegs, RegisterVT, ValueVT); 719 Part += NumRegs; 720 Parts.clear(); 721 } 722 723 return DAG.getNode(ISD::MERGE_VALUES, dl, 724 DAG.getVTList(&ValueVTs[0], ValueVTs.size()), 725 &Values[0], ValueVTs.size()); 726} 727 728/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 729/// specified value into the registers specified by this object. This uses 730/// Chain/Flag as the input and updates them for the output Chain/Flag. 731/// If the Flag pointer is NULL, no flag is used. 732void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, 733 SDValue &Chain, SDValue *Flag) const { 734 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 735 736 // Get the list of the values's legal parts. 737 unsigned NumRegs = Regs.size(); 738 SmallVector<SDValue, 8> Parts(NumRegs); 739 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 740 EVT ValueVT = ValueVTs[Value]; 741 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 742 EVT RegisterVT = RegVTs[Value]; 743 744 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), 745 &Parts[Part], NumParts, RegisterVT); 746 Part += NumParts; 747 } 748 749 // Copy the parts into the registers. 750 SmallVector<SDValue, 8> Chains(NumRegs); 751 for (unsigned i = 0; i != NumRegs; ++i) { 752 SDValue Part; 753 if (Flag == 0) { 754 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 755 } else { 756 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 757 *Flag = Part.getValue(1); 758 } 759 760 Chains[i] = Part.getValue(0); 761 } 762 763 if (NumRegs == 1 || Flag) 764 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 765 // flagged to it. That is the CopyToReg nodes and the user are considered 766 // a single scheduling unit. If we create a TokenFactor and return it as 767 // chain, then the TokenFactor is both a predecessor (operand) of the 768 // user as well as a successor (the TF operands are flagged to the user). 769 // c1, f1 = CopyToReg 770 // c2, f2 = CopyToReg 771 // c3 = TokenFactor c1, c2 772 // ... 773 // = op c3, ..., f2 774 Chain = Chains[NumRegs-1]; 775 else 776 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs); 777} 778 779/// AddInlineAsmOperands - Add this value to the specified inlineasm node 780/// operand list. This adds the code marker and includes the number of 781/// values added into it. 782void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 783 unsigned MatchingIdx, 784 SelectionDAG &DAG, 785 std::vector<SDValue> &Ops) const { 786 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 787 788 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 789 if (HasMatching) 790 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 791 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32); 792 Ops.push_back(Res); 793 794 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 795 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 796 EVT RegisterVT = RegVTs[Value]; 797 for (unsigned i = 0; i != NumRegs; ++i) { 798 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 799 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT)); 800 } 801 } 802} 803 804void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) { 805 AA = &aa; 806 GFI = gfi; 807 TD = DAG.getTarget().getTargetData(); 808} 809 810/// clear - Clear out the current SelectionDAG and the associated 811/// state and prepare this SelectionDAGBuilder object to be used 812/// for a new block. This doesn't clear out information about 813/// additional blocks that are needed to complete switch lowering 814/// or PHI node updating; that information is cleared out as it is 815/// consumed. 816void SelectionDAGBuilder::clear() { 817 NodeMap.clear(); 818 UnusedArgNodeMap.clear(); 819 PendingLoads.clear(); 820 PendingExports.clear(); 821 CurDebugLoc = DebugLoc(); 822 HasTailCall = false; 823} 824 825/// clearDanglingDebugInfo - Clear the dangling debug information 826/// map. This function is seperated from the clear so that debug 827/// information that is dangling in a basic block can be properly 828/// resolved in a different basic block. This allows the 829/// SelectionDAG to resolve dangling debug information attached 830/// to PHI nodes. 831void SelectionDAGBuilder::clearDanglingDebugInfo() { 832 DanglingDebugInfoMap.clear(); 833} 834 835/// getRoot - Return the current virtual root of the Selection DAG, 836/// flushing any PendingLoad items. This must be done before emitting 837/// a store or any other node that may need to be ordered after any 838/// prior load instructions. 839/// 840SDValue SelectionDAGBuilder::getRoot() { 841 if (PendingLoads.empty()) 842 return DAG.getRoot(); 843 844 if (PendingLoads.size() == 1) { 845 SDValue Root = PendingLoads[0]; 846 DAG.setRoot(Root); 847 PendingLoads.clear(); 848 return Root; 849 } 850 851 // Otherwise, we have to make a token factor node. 852 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 853 &PendingLoads[0], PendingLoads.size()); 854 PendingLoads.clear(); 855 DAG.setRoot(Root); 856 return Root; 857} 858 859/// getControlRoot - Similar to getRoot, but instead of flushing all the 860/// PendingLoad items, flush all the PendingExports items. It is necessary 861/// to do this before emitting a terminator instruction. 862/// 863SDValue SelectionDAGBuilder::getControlRoot() { 864 SDValue Root = DAG.getRoot(); 865 866 if (PendingExports.empty()) 867 return Root; 868 869 // Turn all of the CopyToReg chains into one factored node. 870 if (Root.getOpcode() != ISD::EntryToken) { 871 unsigned i = 0, e = PendingExports.size(); 872 for (; i != e; ++i) { 873 assert(PendingExports[i].getNode()->getNumOperands() > 1); 874 if (PendingExports[i].getNode()->getOperand(0) == Root) 875 break; // Don't add the root if we already indirectly depend on it. 876 } 877 878 if (i == e) 879 PendingExports.push_back(Root); 880 } 881 882 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 883 &PendingExports[0], 884 PendingExports.size()); 885 PendingExports.clear(); 886 DAG.setRoot(Root); 887 return Root; 888} 889 890void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) { 891 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering. 892 DAG.AssignOrdering(Node, SDNodeOrder); 893 894 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) 895 AssignOrderingToNode(Node->getOperand(I).getNode()); 896} 897 898void SelectionDAGBuilder::visit(const Instruction &I) { 899 // Set up outgoing PHI node register values before emitting the terminator. 900 if (isa<TerminatorInst>(&I)) 901 HandlePHINodesInSuccessorBlocks(I.getParent()); 902 903 CurDebugLoc = I.getDebugLoc(); 904 905 visit(I.getOpcode(), I); 906 907 if (!isa<TerminatorInst>(&I) && !HasTailCall) 908 CopyToExportRegsIfNeeded(&I); 909 910 CurDebugLoc = DebugLoc(); 911} 912 913void SelectionDAGBuilder::visitPHI(const PHINode &) { 914 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 915} 916 917void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 918 // Note: this doesn't use InstVisitor, because it has to work with 919 // ConstantExpr's in addition to instructions. 920 switch (Opcode) { 921 default: llvm_unreachable("Unknown instruction type encountered!"); 922 // Build the switch statement using the Instruction.def file. 923#define HANDLE_INST(NUM, OPCODE, CLASS) \ 924 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break; 925#include "llvm/Instruction.def" 926 } 927 928 // Assign the ordering to the freshly created DAG nodes. 929 if (NodeMap.count(&I)) { 930 ++SDNodeOrder; 931 AssignOrderingToNode(getValue(&I).getNode()); 932 } 933} 934 935// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 936// generate the debug data structures now that we've seen its definition. 937void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 938 SDValue Val) { 939 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V]; 940 if (DDI.getDI()) { 941 const DbgValueInst *DI = DDI.getDI(); 942 DebugLoc dl = DDI.getdl(); 943 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 944 MDNode *Variable = DI->getVariable(); 945 uint64_t Offset = DI->getOffset(); 946 SDDbgValue *SDV; 947 if (Val.getNode()) { 948 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) { 949 SDV = DAG.getDbgValue(Variable, Val.getNode(), 950 Val.getResNo(), Offset, dl, DbgSDNodeOrder); 951 DAG.AddDbgValue(SDV, Val.getNode(), false); 952 } 953 } else 954 DEBUG(dbgs() << "Dropping debug info for " << DI); 955 DanglingDebugInfoMap[V] = DanglingDebugInfo(); 956 } 957} 958 959// getValue - Return an SDValue for the given Value. 960SDValue SelectionDAGBuilder::getValue(const Value *V) { 961 // If we already have an SDValue for this value, use it. It's important 962 // to do this first, so that we don't create a CopyFromReg if we already 963 // have a regular SDValue. 964 SDValue &N = NodeMap[V]; 965 if (N.getNode()) return N; 966 967 // If there's a virtual register allocated and initialized for this 968 // value, use it. 969 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 970 if (It != FuncInfo.ValueMap.end()) { 971 unsigned InReg = It->second; 972 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType()); 973 SDValue Chain = DAG.getEntryNode(); 974 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain,NULL); 975 resolveDanglingDebugInfo(V, N); 976 return N; 977 } 978 979 // Otherwise create a new SDValue and remember it. 980 SDValue Val = getValueImpl(V); 981 NodeMap[V] = Val; 982 resolveDanglingDebugInfo(V, Val); 983 return Val; 984} 985 986/// getNonRegisterValue - Return an SDValue for the given Value, but 987/// don't look in FuncInfo.ValueMap for a virtual register. 988SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 989 // If we already have an SDValue for this value, use it. 990 SDValue &N = NodeMap[V]; 991 if (N.getNode()) return N; 992 993 // Otherwise create a new SDValue and remember it. 994 SDValue Val = getValueImpl(V); 995 NodeMap[V] = Val; 996 resolveDanglingDebugInfo(V, Val); 997 return Val; 998} 999 1000/// getValueImpl - Helper function for getValue and getNonRegisterValue. 1001/// Create an SDValue for the given value. 1002SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1003 if (const Constant *C = dyn_cast<Constant>(V)) { 1004 EVT VT = TLI.getValueType(V->getType(), true); 1005 1006 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1007 return DAG.getConstant(*CI, VT); 1008 1009 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1010 return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT); 1011 1012 if (isa<ConstantPointerNull>(C)) 1013 return DAG.getConstant(0, TLI.getPointerTy()); 1014 1015 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1016 return DAG.getConstantFP(*CFP, VT); 1017 1018 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1019 return DAG.getUNDEF(VT); 1020 1021 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1022 visit(CE->getOpcode(), *CE); 1023 SDValue N1 = NodeMap[V]; 1024 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1025 return N1; 1026 } 1027 1028 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1029 SmallVector<SDValue, 4> Constants; 1030 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1031 OI != OE; ++OI) { 1032 SDNode *Val = getValue(*OI).getNode(); 1033 // If the operand is an empty aggregate, there are no values. 1034 if (!Val) continue; 1035 // Add each leaf value from the operand to the Constants list 1036 // to form a flattened list of all the values. 1037 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1038 Constants.push_back(SDValue(Val, i)); 1039 } 1040 1041 return DAG.getMergeValues(&Constants[0], Constants.size(), 1042 getCurDebugLoc()); 1043 } 1044 1045 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1046 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1047 "Unknown struct or array constant!"); 1048 1049 SmallVector<EVT, 4> ValueVTs; 1050 ComputeValueVTs(TLI, C->getType(), ValueVTs); 1051 unsigned NumElts = ValueVTs.size(); 1052 if (NumElts == 0) 1053 return SDValue(); // empty struct 1054 SmallVector<SDValue, 4> Constants(NumElts); 1055 for (unsigned i = 0; i != NumElts; ++i) { 1056 EVT EltVT = ValueVTs[i]; 1057 if (isa<UndefValue>(C)) 1058 Constants[i] = DAG.getUNDEF(EltVT); 1059 else if (EltVT.isFloatingPoint()) 1060 Constants[i] = DAG.getConstantFP(0, EltVT); 1061 else 1062 Constants[i] = DAG.getConstant(0, EltVT); 1063 } 1064 1065 return DAG.getMergeValues(&Constants[0], NumElts, 1066 getCurDebugLoc()); 1067 } 1068 1069 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1070 return DAG.getBlockAddress(BA, VT); 1071 1072 VectorType *VecTy = cast<VectorType>(V->getType()); 1073 unsigned NumElements = VecTy->getNumElements(); 1074 1075 // Now that we know the number and type of the elements, get that number of 1076 // elements into the Ops array based on what kind of constant it is. 1077 SmallVector<SDValue, 16> Ops; 1078 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) { 1079 for (unsigned i = 0; i != NumElements; ++i) 1080 Ops.push_back(getValue(CP->getOperand(i))); 1081 } else { 1082 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1083 EVT EltVT = TLI.getValueType(VecTy->getElementType()); 1084 1085 SDValue Op; 1086 if (EltVT.isFloatingPoint()) 1087 Op = DAG.getConstantFP(0, EltVT); 1088 else 1089 Op = DAG.getConstant(0, EltVT); 1090 Ops.assign(NumElements, Op); 1091 } 1092 1093 // Create a BUILD_VECTOR node. 1094 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 1095 VT, &Ops[0], Ops.size()); 1096 } 1097 1098 // If this is a static alloca, generate it as the frameindex instead of 1099 // computation. 1100 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1101 DenseMap<const AllocaInst*, int>::iterator SI = 1102 FuncInfo.StaticAllocaMap.find(AI); 1103 if (SI != FuncInfo.StaticAllocaMap.end()) 1104 return DAG.getFrameIndex(SI->second, TLI.getPointerTy()); 1105 } 1106 1107 // If this is an instruction which fast-isel has deferred, select it now. 1108 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1109 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1110 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType()); 1111 SDValue Chain = DAG.getEntryNode(); 1112 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL); 1113 } 1114 1115 llvm_unreachable("Can't get register for value!"); 1116 return SDValue(); 1117} 1118 1119void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1120 SDValue Chain = getControlRoot(); 1121 SmallVector<ISD::OutputArg, 8> Outs; 1122 SmallVector<SDValue, 8> OutVals; 1123 1124 if (!FuncInfo.CanLowerReturn) { 1125 unsigned DemoteReg = FuncInfo.DemoteRegister; 1126 const Function *F = I.getParent()->getParent(); 1127 1128 // Emit a store of the return value through the virtual register. 1129 // Leave Outs empty so that LowerReturn won't try to load return 1130 // registers the usual way. 1131 SmallVector<EVT, 1> PtrValueVTs; 1132 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()), 1133 PtrValueVTs); 1134 1135 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]); 1136 SDValue RetOp = getValue(I.getOperand(0)); 1137 1138 SmallVector<EVT, 4> ValueVTs; 1139 SmallVector<uint64_t, 4> Offsets; 1140 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1141 unsigned NumValues = ValueVTs.size(); 1142 1143 SmallVector<SDValue, 4> Chains(NumValues); 1144 for (unsigned i = 0; i != NumValues; ++i) { 1145 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), 1146 RetPtr.getValueType(), RetPtr, 1147 DAG.getIntPtrConstant(Offsets[i])); 1148 Chains[i] = 1149 DAG.getStore(Chain, getCurDebugLoc(), 1150 SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1151 // FIXME: better loc info would be nice. 1152 Add, MachinePointerInfo(), false, false, 0); 1153 } 1154 1155 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 1156 MVT::Other, &Chains[0], NumValues); 1157 } else if (I.getNumOperands() != 0) { 1158 SmallVector<EVT, 4> ValueVTs; 1159 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs); 1160 unsigned NumValues = ValueVTs.size(); 1161 if (NumValues) { 1162 SDValue RetOp = getValue(I.getOperand(0)); 1163 for (unsigned j = 0, f = NumValues; j != f; ++j) { 1164 EVT VT = ValueVTs[j]; 1165 1166 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1167 1168 const Function *F = I.getParent()->getParent(); 1169 if (F->paramHasAttr(0, Attribute::SExt)) 1170 ExtendKind = ISD::SIGN_EXTEND; 1171 else if (F->paramHasAttr(0, Attribute::ZExt)) 1172 ExtendKind = ISD::ZERO_EXTEND; 1173 1174 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1175 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind); 1176 1177 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT); 1178 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT); 1179 SmallVector<SDValue, 4> Parts(NumParts); 1180 getCopyToParts(DAG, getCurDebugLoc(), 1181 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1182 &Parts[0], NumParts, PartVT, ExtendKind); 1183 1184 // 'inreg' on function refers to return value 1185 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1186 if (F->paramHasAttr(0, Attribute::InReg)) 1187 Flags.setInReg(); 1188 1189 // Propagate extension type if any 1190 if (ExtendKind == ISD::SIGN_EXTEND) 1191 Flags.setSExt(); 1192 else if (ExtendKind == ISD::ZERO_EXTEND) 1193 Flags.setZExt(); 1194 1195 for (unsigned i = 0; i < NumParts; ++i) { 1196 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1197 /*isfixed=*/true)); 1198 OutVals.push_back(Parts[i]); 1199 } 1200 } 1201 } 1202 } 1203 1204 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); 1205 CallingConv::ID CallConv = 1206 DAG.getMachineFunction().getFunction()->getCallingConv(); 1207 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg, 1208 Outs, OutVals, getCurDebugLoc(), DAG); 1209 1210 // Verify that the target's LowerReturn behaved as expected. 1211 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1212 "LowerReturn didn't return a valid chain!"); 1213 1214 // Update the DAG with the new chain value resulting from return lowering. 1215 DAG.setRoot(Chain); 1216} 1217 1218/// CopyToExportRegsIfNeeded - If the given value has virtual registers 1219/// created for it, emit nodes to copy the value into the virtual 1220/// registers. 1221void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1222 // Skip empty types 1223 if (V->getType()->isEmptyTy()) 1224 return; 1225 1226 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1227 if (VMI != FuncInfo.ValueMap.end()) { 1228 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1229 CopyValueToVirtualRegister(V, VMI->second); 1230 } 1231} 1232 1233/// ExportFromCurrentBlock - If this condition isn't known to be exported from 1234/// the current basic block, add it to ValueMap now so that we'll get a 1235/// CopyTo/FromReg. 1236void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1237 // No need to export constants. 1238 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1239 1240 // Already exported? 1241 if (FuncInfo.isExportedInst(V)) return; 1242 1243 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1244 CopyValueToVirtualRegister(V, Reg); 1245} 1246 1247bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1248 const BasicBlock *FromBB) { 1249 // The operands of the setcc have to be in this block. We don't know 1250 // how to export them from some other block. 1251 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1252 // Can export from current BB. 1253 if (VI->getParent() == FromBB) 1254 return true; 1255 1256 // Is already exported, noop. 1257 return FuncInfo.isExportedInst(V); 1258 } 1259 1260 // If this is an argument, we can export it if the BB is the entry block or 1261 // if it is already exported. 1262 if (isa<Argument>(V)) { 1263 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1264 return true; 1265 1266 // Otherwise, can only export this if it is already exported. 1267 return FuncInfo.isExportedInst(V); 1268 } 1269 1270 // Otherwise, constants can always be exported. 1271 return true; 1272} 1273 1274/// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1275uint32_t SelectionDAGBuilder::getEdgeWeight(MachineBasicBlock *Src, 1276 MachineBasicBlock *Dst) { 1277 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1278 if (!BPI) 1279 return 0; 1280 const BasicBlock *SrcBB = Src->getBasicBlock(); 1281 const BasicBlock *DstBB = Dst->getBasicBlock(); 1282 return BPI->getEdgeWeight(SrcBB, DstBB); 1283} 1284 1285void SelectionDAGBuilder:: 1286addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst, 1287 uint32_t Weight /* = 0 */) { 1288 if (!Weight) 1289 Weight = getEdgeWeight(Src, Dst); 1290 Src->addSuccessor(Dst, Weight); 1291} 1292 1293 1294static bool InBlock(const Value *V, const BasicBlock *BB) { 1295 if (const Instruction *I = dyn_cast<Instruction>(V)) 1296 return I->getParent() == BB; 1297 return true; 1298} 1299 1300/// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1301/// This function emits a branch and is used at the leaves of an OR or an 1302/// AND operator tree. 1303/// 1304void 1305SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1306 MachineBasicBlock *TBB, 1307 MachineBasicBlock *FBB, 1308 MachineBasicBlock *CurBB, 1309 MachineBasicBlock *SwitchBB) { 1310 const BasicBlock *BB = CurBB->getBasicBlock(); 1311 1312 // If the leaf of the tree is a comparison, merge the condition into 1313 // the caseblock. 1314 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1315 // The operands of the cmp have to be in this block. We don't know 1316 // how to export them from some other block. If this is the first block 1317 // of the sequence, no exporting is needed. 1318 if (CurBB == SwitchBB || 1319 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1320 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1321 ISD::CondCode Condition; 1322 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1323 Condition = getICmpCondCode(IC->getPredicate()); 1324 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) { 1325 Condition = getFCmpCondCode(FC->getPredicate()); 1326 } else { 1327 Condition = ISD::SETEQ; // silence warning. 1328 llvm_unreachable("Unknown compare instruction"); 1329 } 1330 1331 CaseBlock CB(Condition, BOp->getOperand(0), 1332 BOp->getOperand(1), NULL, TBB, FBB, CurBB); 1333 SwitchCases.push_back(CB); 1334 return; 1335 } 1336 } 1337 1338 // Create a CaseBlock record representing this branch. 1339 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()), 1340 NULL, TBB, FBB, CurBB); 1341 SwitchCases.push_back(CB); 1342} 1343 1344/// FindMergedConditions - If Cond is an expression like 1345void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1346 MachineBasicBlock *TBB, 1347 MachineBasicBlock *FBB, 1348 MachineBasicBlock *CurBB, 1349 MachineBasicBlock *SwitchBB, 1350 unsigned Opc) { 1351 // If this node is not part of the or/and tree, emit it as a branch. 1352 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1353 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1354 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || 1355 BOp->getParent() != CurBB->getBasicBlock() || 1356 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1357 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1358 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB); 1359 return; 1360 } 1361 1362 // Create TmpBB after CurBB. 1363 MachineFunction::iterator BBI = CurBB; 1364 MachineFunction &MF = DAG.getMachineFunction(); 1365 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1366 CurBB->getParent()->insert(++BBI, TmpBB); 1367 1368 if (Opc == Instruction::Or) { 1369 // Codegen X | Y as: 1370 // jmp_if_X TBB 1371 // jmp TmpBB 1372 // TmpBB: 1373 // jmp_if_Y TBB 1374 // jmp FBB 1375 // 1376 1377 // Emit the LHS condition. 1378 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc); 1379 1380 // Emit the RHS condition into TmpBB. 1381 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc); 1382 } else { 1383 assert(Opc == Instruction::And && "Unknown merge op!"); 1384 // Codegen X & Y as: 1385 // jmp_if_X TmpBB 1386 // jmp FBB 1387 // TmpBB: 1388 // jmp_if_Y TBB 1389 // jmp FBB 1390 // 1391 // This requires creation of TmpBB after CurBB. 1392 1393 // Emit the LHS condition. 1394 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc); 1395 1396 // Emit the RHS condition into TmpBB. 1397 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc); 1398 } 1399} 1400 1401/// If the set of cases should be emitted as a series of branches, return true. 1402/// If we should emit this as a bunch of and/or'd together conditions, return 1403/// false. 1404bool 1405SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){ 1406 if (Cases.size() != 2) return true; 1407 1408 // If this is two comparisons of the same values or'd or and'd together, they 1409 // will get folded into a single comparison, so don't emit two blocks. 1410 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1411 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1412 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1413 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1414 return false; 1415 } 1416 1417 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1418 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1419 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1420 Cases[0].CC == Cases[1].CC && 1421 isa<Constant>(Cases[0].CmpRHS) && 1422 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1423 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1424 return false; 1425 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1426 return false; 1427 } 1428 1429 return true; 1430} 1431 1432void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1433 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1434 1435 // Update machine-CFG edges. 1436 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1437 1438 // Figure out which block is immediately after the current one. 1439 MachineBasicBlock *NextBlock = 0; 1440 MachineFunction::iterator BBI = BrMBB; 1441 if (++BBI != FuncInfo.MF->end()) 1442 NextBlock = BBI; 1443 1444 if (I.isUnconditional()) { 1445 // Update machine-CFG edges. 1446 BrMBB->addSuccessor(Succ0MBB); 1447 1448 // If this is not a fall-through branch, emit the branch. 1449 if (Succ0MBB != NextBlock) 1450 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 1451 MVT::Other, getControlRoot(), 1452 DAG.getBasicBlock(Succ0MBB))); 1453 1454 return; 1455 } 1456 1457 // If this condition is one of the special cases we handle, do special stuff 1458 // now. 1459 const Value *CondVal = I.getCondition(); 1460 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1461 1462 // If this is a series of conditions that are or'd or and'd together, emit 1463 // this as a sequence of branches instead of setcc's with and/or operations. 1464 // As long as jumps are not expensive, this should improve performance. 1465 // For example, instead of something like: 1466 // cmp A, B 1467 // C = seteq 1468 // cmp D, E 1469 // F = setle 1470 // or C, F 1471 // jnz foo 1472 // Emit: 1473 // cmp A, B 1474 // je foo 1475 // cmp D, E 1476 // jle foo 1477 // 1478 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1479 if (!TLI.isJumpExpensive() && 1480 BOp->hasOneUse() && 1481 (BOp->getOpcode() == Instruction::And || 1482 BOp->getOpcode() == Instruction::Or)) { 1483 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 1484 BOp->getOpcode()); 1485 // If the compares in later blocks need to use values not currently 1486 // exported from this block, export them now. This block should always 1487 // be the first entry. 1488 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 1489 1490 // Allow some cases to be rejected. 1491 if (ShouldEmitAsBranches(SwitchCases)) { 1492 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1493 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1494 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1495 } 1496 1497 // Emit the branch for this block. 1498 visitSwitchCase(SwitchCases[0], BrMBB); 1499 SwitchCases.erase(SwitchCases.begin()); 1500 return; 1501 } 1502 1503 // Okay, we decided not to do this, remove any inserted MBB's and clear 1504 // SwitchCases. 1505 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1506 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 1507 1508 SwitchCases.clear(); 1509 } 1510 } 1511 1512 // Create a CaseBlock record representing this branch. 1513 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 1514 NULL, Succ0MBB, Succ1MBB, BrMBB); 1515 1516 // Use visitSwitchCase to actually insert the fast branch sequence for this 1517 // cond branch. 1518 visitSwitchCase(CB, BrMBB); 1519} 1520 1521/// visitSwitchCase - Emits the necessary code to represent a single node in 1522/// the binary search tree resulting from lowering a switch instruction. 1523void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 1524 MachineBasicBlock *SwitchBB) { 1525 SDValue Cond; 1526 SDValue CondLHS = getValue(CB.CmpLHS); 1527 DebugLoc dl = getCurDebugLoc(); 1528 1529 // Build the setcc now. 1530 if (CB.CmpMHS == NULL) { 1531 // Fold "(X == true)" to X and "(X == false)" to !X to 1532 // handle common cases produced by branch lowering. 1533 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 1534 CB.CC == ISD::SETEQ) 1535 Cond = CondLHS; 1536 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 1537 CB.CC == ISD::SETEQ) { 1538 SDValue True = DAG.getConstant(1, CondLHS.getValueType()); 1539 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 1540 } else 1541 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1542 } else { 1543 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 1544 1545 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 1546 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 1547 1548 SDValue CmpOp = getValue(CB.CmpMHS); 1549 EVT VT = CmpOp.getValueType(); 1550 1551 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 1552 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT), 1553 ISD::SETLE); 1554 } else { 1555 SDValue SUB = DAG.getNode(ISD::SUB, dl, 1556 VT, CmpOp, DAG.getConstant(Low, VT)); 1557 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 1558 DAG.getConstant(High-Low, VT), ISD::SETULE); 1559 } 1560 } 1561 1562 // Update successor info 1563 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight); 1564 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight); 1565 1566 // Set NextBlock to be the MBB immediately after the current one, if any. 1567 // This is used to avoid emitting unnecessary branches to the next block. 1568 MachineBasicBlock *NextBlock = 0; 1569 MachineFunction::iterator BBI = SwitchBB; 1570 if (++BBI != FuncInfo.MF->end()) 1571 NextBlock = BBI; 1572 1573 // If the lhs block is the next block, invert the condition so that we can 1574 // fall through to the lhs instead of the rhs block. 1575 if (CB.TrueBB == NextBlock) { 1576 std::swap(CB.TrueBB, CB.FalseBB); 1577 SDValue True = DAG.getConstant(1, Cond.getValueType()); 1578 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 1579 } 1580 1581 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1582 MVT::Other, getControlRoot(), Cond, 1583 DAG.getBasicBlock(CB.TrueBB)); 1584 1585 // Insert the false branch. Do this even if it's a fall through branch, 1586 // this makes it easier to do DAG optimizations which require inverting 1587 // the branch condition. 1588 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1589 DAG.getBasicBlock(CB.FalseBB)); 1590 1591 DAG.setRoot(BrCond); 1592} 1593 1594/// visitJumpTable - Emit JumpTable node in the current MBB 1595void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 1596 // Emit the code for the jump table 1597 assert(JT.Reg != -1U && "Should lower JT Header first!"); 1598 EVT PTy = TLI.getPointerTy(); 1599 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), 1600 JT.Reg, PTy); 1601 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 1602 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(), 1603 MVT::Other, Index.getValue(1), 1604 Table, Index); 1605 DAG.setRoot(BrJumpTable); 1606} 1607 1608/// visitJumpTableHeader - This function emits necessary code to produce index 1609/// in the JumpTable from switch case. 1610void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 1611 JumpTableHeader &JTH, 1612 MachineBasicBlock *SwitchBB) { 1613 // Subtract the lowest switch case value from the value being switched on and 1614 // conditional branch to default mbb if the result is greater than the 1615 // difference between smallest and largest cases. 1616 SDValue SwitchOp = getValue(JTH.SValue); 1617 EVT VT = SwitchOp.getValueType(); 1618 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp, 1619 DAG.getConstant(JTH.First, VT)); 1620 1621 // The SDNode we just created, which holds the value being switched on minus 1622 // the smallest case value, needs to be copied to a virtual register so it 1623 // can be used as an index into the jump table in a subsequent basic block. 1624 // This value may be smaller or larger than the target's pointer type, and 1625 // therefore require extension or truncating. 1626 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy()); 1627 1628 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy()); 1629 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(), 1630 JumpTableReg, SwitchOp); 1631 JT.Reg = JumpTableReg; 1632 1633 // Emit the range check for the jump table, and branch to the default block 1634 // for the switch statement if the value being switched on exceeds the largest 1635 // case in the switch. 1636 SDValue CMP = DAG.getSetCC(getCurDebugLoc(), 1637 TLI.getSetCCResultType(Sub.getValueType()), Sub, 1638 DAG.getConstant(JTH.Last-JTH.First,VT), 1639 ISD::SETUGT); 1640 1641 // Set NextBlock to be the MBB immediately after the current one, if any. 1642 // This is used to avoid emitting unnecessary branches to the next block. 1643 MachineBasicBlock *NextBlock = 0; 1644 MachineFunction::iterator BBI = SwitchBB; 1645 1646 if (++BBI != FuncInfo.MF->end()) 1647 NextBlock = BBI; 1648 1649 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1650 MVT::Other, CopyTo, CMP, 1651 DAG.getBasicBlock(JT.Default)); 1652 1653 if (JT.MBB != NextBlock) 1654 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond, 1655 DAG.getBasicBlock(JT.MBB)); 1656 1657 DAG.setRoot(BrCond); 1658} 1659 1660/// visitBitTestHeader - This function emits necessary code to produce value 1661/// suitable for "bit tests" 1662void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 1663 MachineBasicBlock *SwitchBB) { 1664 // Subtract the minimum value 1665 SDValue SwitchOp = getValue(B.SValue); 1666 EVT VT = SwitchOp.getValueType(); 1667 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp, 1668 DAG.getConstant(B.First, VT)); 1669 1670 // Check range 1671 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(), 1672 TLI.getSetCCResultType(Sub.getValueType()), 1673 Sub, DAG.getConstant(B.Range, VT), 1674 ISD::SETUGT); 1675 1676 // Determine the type of the test operands. 1677 bool UsePtrType = false; 1678 if (!TLI.isTypeLegal(VT)) 1679 UsePtrType = true; 1680 else { 1681 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 1682 if ((uint64_t)((int64_t)B.Cases[i].Mask >> VT.getSizeInBits()) + 1 >= 2) { 1683 // Switch table case range are encoded into series of masks. 1684 // Just use pointer type, it's guaranteed to fit. 1685 UsePtrType = true; 1686 break; 1687 } 1688 } 1689 if (UsePtrType) { 1690 VT = TLI.getPointerTy(); 1691 Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT); 1692 } 1693 1694 B.RegVT = VT; 1695 B.Reg = FuncInfo.CreateReg(VT); 1696 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(), 1697 B.Reg, Sub); 1698 1699 // Set NextBlock to be the MBB immediately after the current one, if any. 1700 // This is used to avoid emitting unnecessary branches to the next block. 1701 MachineBasicBlock *NextBlock = 0; 1702 MachineFunction::iterator BBI = SwitchBB; 1703 if (++BBI != FuncInfo.MF->end()) 1704 NextBlock = BBI; 1705 1706 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 1707 1708 addSuccessorWithWeight(SwitchBB, B.Default); 1709 addSuccessorWithWeight(SwitchBB, MBB); 1710 1711 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1712 MVT::Other, CopyTo, RangeCmp, 1713 DAG.getBasicBlock(B.Default)); 1714 1715 if (MBB != NextBlock) 1716 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo, 1717 DAG.getBasicBlock(MBB)); 1718 1719 DAG.setRoot(BrRange); 1720} 1721 1722/// visitBitTestCase - this function produces one "bit test" 1723void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 1724 MachineBasicBlock* NextMBB, 1725 unsigned Reg, 1726 BitTestCase &B, 1727 MachineBasicBlock *SwitchBB) { 1728 EVT VT = BB.RegVT; 1729 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), 1730 Reg, VT); 1731 SDValue Cmp; 1732 unsigned PopCount = CountPopulation_64(B.Mask); 1733 if (PopCount == 1) { 1734 // Testing for a single bit; just compare the shift count with what it 1735 // would need to be to shift a 1 bit in that position. 1736 Cmp = DAG.getSetCC(getCurDebugLoc(), 1737 TLI.getSetCCResultType(VT), 1738 ShiftOp, 1739 DAG.getConstant(CountTrailingZeros_64(B.Mask), VT), 1740 ISD::SETEQ); 1741 } else if (PopCount == BB.Range) { 1742 // There is only one zero bit in the range, test for it directly. 1743 Cmp = DAG.getSetCC(getCurDebugLoc(), 1744 TLI.getSetCCResultType(VT), 1745 ShiftOp, 1746 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), 1747 ISD::SETNE); 1748 } else { 1749 // Make desired shift 1750 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT, 1751 DAG.getConstant(1, VT), ShiftOp); 1752 1753 // Emit bit tests and jumps 1754 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(), 1755 VT, SwitchVal, DAG.getConstant(B.Mask, VT)); 1756 Cmp = DAG.getSetCC(getCurDebugLoc(), 1757 TLI.getSetCCResultType(VT), 1758 AndOp, DAG.getConstant(0, VT), 1759 ISD::SETNE); 1760 } 1761 1762 addSuccessorWithWeight(SwitchBB, B.TargetBB); 1763 addSuccessorWithWeight(SwitchBB, NextMBB); 1764 1765 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1766 MVT::Other, getControlRoot(), 1767 Cmp, DAG.getBasicBlock(B.TargetBB)); 1768 1769 // Set NextBlock to be the MBB immediately after the current one, if any. 1770 // This is used to avoid emitting unnecessary branches to the next block. 1771 MachineBasicBlock *NextBlock = 0; 1772 MachineFunction::iterator BBI = SwitchBB; 1773 if (++BBI != FuncInfo.MF->end()) 1774 NextBlock = BBI; 1775 1776 if (NextMBB != NextBlock) 1777 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd, 1778 DAG.getBasicBlock(NextMBB)); 1779 1780 DAG.setRoot(BrAnd); 1781} 1782 1783void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 1784 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 1785 1786 // Retrieve successors. 1787 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 1788 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)]; 1789 1790 const Value *Callee(I.getCalledValue()); 1791 if (isa<InlineAsm>(Callee)) 1792 visitInlineAsm(&I); 1793 else 1794 LowerCallTo(&I, getValue(Callee), false, LandingPad); 1795 1796 // If the value of the invoke is used outside of its defining block, make it 1797 // available as a virtual register. 1798 CopyToExportRegsIfNeeded(&I); 1799 1800 // Update successor info 1801 InvokeMBB->addSuccessor(Return); 1802 InvokeMBB->addSuccessor(LandingPad); 1803 1804 // Drop into normal successor. 1805 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 1806 MVT::Other, getControlRoot(), 1807 DAG.getBasicBlock(Return))); 1808} 1809 1810void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) { 1811} 1812 1813/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for 1814/// small case ranges). 1815bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR, 1816 CaseRecVector& WorkList, 1817 const Value* SV, 1818 MachineBasicBlock *Default, 1819 MachineBasicBlock *SwitchBB) { 1820 Case& BackCase = *(CR.Range.second-1); 1821 1822 // Size is the number of Cases represented by this range. 1823 size_t Size = CR.Range.second - CR.Range.first; 1824 if (Size > 3) 1825 return false; 1826 1827 // Get the MachineFunction which holds the current MBB. This is used when 1828 // inserting any additional MBBs necessary to represent the switch. 1829 MachineFunction *CurMF = FuncInfo.MF; 1830 1831 // Figure out which block is immediately after the current one. 1832 MachineBasicBlock *NextBlock = 0; 1833 MachineFunction::iterator BBI = CR.CaseBB; 1834 1835 if (++BBI != FuncInfo.MF->end()) 1836 NextBlock = BBI; 1837 1838 // If any two of the cases has the same destination, and if one value 1839 // is the same as the other, but has one bit unset that the other has set, 1840 // use bit manipulation to do two compares at once. For example: 1841 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 1842 // TODO: This could be extended to merge any 2 cases in switches with 3 cases. 1843 // TODO: Handle cases where CR.CaseBB != SwitchBB. 1844 if (Size == 2 && CR.CaseBB == SwitchBB) { 1845 Case &Small = *CR.Range.first; 1846 Case &Big = *(CR.Range.second-1); 1847 1848 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) { 1849 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue(); 1850 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue(); 1851 1852 // Check that there is only one bit different. 1853 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 && 1854 (SmallValue | BigValue) == BigValue) { 1855 // Isolate the common bit. 1856 APInt CommonBit = BigValue & ~SmallValue; 1857 assert((SmallValue | CommonBit) == BigValue && 1858 CommonBit.countPopulation() == 1 && "Not a common bit?"); 1859 1860 SDValue CondLHS = getValue(SV); 1861 EVT VT = CondLHS.getValueType(); 1862 DebugLoc DL = getCurDebugLoc(); 1863 1864 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 1865 DAG.getConstant(CommonBit, VT)); 1866 SDValue Cond = DAG.getSetCC(DL, MVT::i1, 1867 Or, DAG.getConstant(BigValue, VT), 1868 ISD::SETEQ); 1869 1870 // Update successor info. 1871 addSuccessorWithWeight(SwitchBB, Small.BB); 1872 addSuccessorWithWeight(SwitchBB, Default); 1873 1874 // Insert the true branch. 1875 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other, 1876 getControlRoot(), Cond, 1877 DAG.getBasicBlock(Small.BB)); 1878 1879 // Insert the false branch. 1880 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 1881 DAG.getBasicBlock(Default)); 1882 1883 DAG.setRoot(BrCond); 1884 return true; 1885 } 1886 } 1887 } 1888 1889 // Rearrange the case blocks so that the last one falls through if possible. 1890 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) { 1891 // The last case block won't fall through into 'NextBlock' if we emit the 1892 // branches in this order. See if rearranging a case value would help. 1893 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) { 1894 if (I->BB == NextBlock) { 1895 std::swap(*I, BackCase); 1896 break; 1897 } 1898 } 1899 } 1900 1901 // Create a CaseBlock record representing a conditional branch to 1902 // the Case's target mbb if the value being switched on SV is equal 1903 // to C. 1904 MachineBasicBlock *CurBlock = CR.CaseBB; 1905 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) { 1906 MachineBasicBlock *FallThrough; 1907 if (I != E-1) { 1908 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock()); 1909 CurMF->insert(BBI, FallThrough); 1910 1911 // Put SV in a virtual register to make it available from the new blocks. 1912 ExportFromCurrentBlock(SV); 1913 } else { 1914 // If the last case doesn't match, go to the default block. 1915 FallThrough = Default; 1916 } 1917 1918 const Value *RHS, *LHS, *MHS; 1919 ISD::CondCode CC; 1920 if (I->High == I->Low) { 1921 // This is just small small case range :) containing exactly 1 case 1922 CC = ISD::SETEQ; 1923 LHS = SV; RHS = I->High; MHS = NULL; 1924 } else { 1925 CC = ISD::SETLE; 1926 LHS = I->Low; MHS = SV; RHS = I->High; 1927 } 1928 1929 uint32_t ExtraWeight = I->ExtraWeight; 1930 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough, 1931 /* me */ CurBlock, 1932 /* trueweight */ ExtraWeight / 2, /* falseweight */ ExtraWeight / 2); 1933 1934 // If emitting the first comparison, just call visitSwitchCase to emit the 1935 // code into the current block. Otherwise, push the CaseBlock onto the 1936 // vector to be later processed by SDISel, and insert the node's MBB 1937 // before the next MBB. 1938 if (CurBlock == SwitchBB) 1939 visitSwitchCase(CB, SwitchBB); 1940 else 1941 SwitchCases.push_back(CB); 1942 1943 CurBlock = FallThrough; 1944 } 1945 1946 return true; 1947} 1948 1949static inline bool areJTsAllowed(const TargetLowering &TLI) { 1950 return !DisableJumpTables && 1951 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) || 1952 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other)); 1953} 1954 1955static APInt ComputeRange(const APInt &First, const APInt &Last) { 1956 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1; 1957 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth); 1958 return (LastExt - FirstExt + 1ULL); 1959} 1960 1961/// handleJTSwitchCase - Emit jumptable for current switch case range 1962bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR, 1963 CaseRecVector& WorkList, 1964 const Value* SV, 1965 MachineBasicBlock* Default, 1966 MachineBasicBlock *SwitchBB) { 1967 Case& FrontCase = *CR.Range.first; 1968 Case& BackCase = *(CR.Range.second-1); 1969 1970 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 1971 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 1972 1973 APInt TSize(First.getBitWidth(), 0); 1974 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1975 I!=E; ++I) 1976 TSize += I->size(); 1977 1978 if (!areJTsAllowed(TLI) || TSize.ult(4)) 1979 return false; 1980 1981 APInt Range = ComputeRange(First, Last); 1982 double Density = TSize.roundToDouble() / Range.roundToDouble(); 1983 if (Density < 0.4) 1984 return false; 1985 1986 DEBUG(dbgs() << "Lowering jump table\n" 1987 << "First entry: " << First << ". Last entry: " << Last << '\n' 1988 << "Range: " << Range 1989 << ". Size: " << TSize << ". Density: " << Density << "\n\n"); 1990 1991 // Get the MachineFunction which holds the current MBB. This is used when 1992 // inserting any additional MBBs necessary to represent the switch. 1993 MachineFunction *CurMF = FuncInfo.MF; 1994 1995 // Figure out which block is immediately after the current one. 1996 MachineFunction::iterator BBI = CR.CaseBB; 1997 ++BBI; 1998 1999 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 2000 2001 // Create a new basic block to hold the code for loading the address 2002 // of the jump table, and jumping to it. Update successor information; 2003 // we will either branch to the default case for the switch, or the jump 2004 // table. 2005 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2006 CurMF->insert(BBI, JumpTableBB); 2007 2008 addSuccessorWithWeight(CR.CaseBB, Default); 2009 addSuccessorWithWeight(CR.CaseBB, JumpTableBB); 2010 2011 // Build a vector of destination BBs, corresponding to each target 2012 // of the jump table. If the value of the jump table slot corresponds to 2013 // a case statement, push the case's BB onto the vector, otherwise, push 2014 // the default BB. 2015 std::vector<MachineBasicBlock*> DestBBs; 2016 APInt TEI = First; 2017 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) { 2018 const APInt &Low = cast<ConstantInt>(I->Low)->getValue(); 2019 const APInt &High = cast<ConstantInt>(I->High)->getValue(); 2020 2021 if (Low.sle(TEI) && TEI.sle(High)) { 2022 DestBBs.push_back(I->BB); 2023 if (TEI==High) 2024 ++I; 2025 } else { 2026 DestBBs.push_back(Default); 2027 } 2028 } 2029 2030 // Update successor info. Add one edge to each unique successor. 2031 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs()); 2032 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 2033 E = DestBBs.end(); I != E; ++I) { 2034 if (!SuccsHandled[(*I)->getNumber()]) { 2035 SuccsHandled[(*I)->getNumber()] = true; 2036 addSuccessorWithWeight(JumpTableBB, *I); 2037 } 2038 } 2039 2040 // Create a jump table index for this jump table. 2041 unsigned JTEncoding = TLI.getJumpTableEncoding(); 2042 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding) 2043 ->createJumpTableIndex(DestBBs); 2044 2045 // Set the jump table information so that we can codegen it as a second 2046 // MachineBasicBlock 2047 JumpTable JT(-1U, JTI, JumpTableBB, Default); 2048 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB)); 2049 if (CR.CaseBB == SwitchBB) 2050 visitJumpTableHeader(JT, JTH, SwitchBB); 2051 2052 JTCases.push_back(JumpTableBlock(JTH, JT)); 2053 2054 return true; 2055} 2056 2057/// handleBTSplitSwitchCase - emit comparison and split binary search tree into 2058/// 2 subtrees. 2059bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR, 2060 CaseRecVector& WorkList, 2061 const Value* SV, 2062 MachineBasicBlock *Default, 2063 MachineBasicBlock *SwitchBB) { 2064 // Get the MachineFunction which holds the current MBB. This is used when 2065 // inserting any additional MBBs necessary to represent the switch. 2066 MachineFunction *CurMF = FuncInfo.MF; 2067 2068 // Figure out which block is immediately after the current one. 2069 MachineFunction::iterator BBI = CR.CaseBB; 2070 ++BBI; 2071 2072 Case& FrontCase = *CR.Range.first; 2073 Case& BackCase = *(CR.Range.second-1); 2074 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 2075 2076 // Size is the number of Cases represented by this range. 2077 unsigned Size = CR.Range.second - CR.Range.first; 2078 2079 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 2080 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 2081 double FMetric = 0; 2082 CaseItr Pivot = CR.Range.first + Size/2; 2083 2084 // Select optimal pivot, maximizing sum density of LHS and RHS. This will 2085 // (heuristically) allow us to emit JumpTable's later. 2086 APInt TSize(First.getBitWidth(), 0); 2087 for (CaseItr I = CR.Range.first, E = CR.Range.second; 2088 I!=E; ++I) 2089 TSize += I->size(); 2090 2091 APInt LSize = FrontCase.size(); 2092 APInt RSize = TSize-LSize; 2093 DEBUG(dbgs() << "Selecting best pivot: \n" 2094 << "First: " << First << ", Last: " << Last <<'\n' 2095 << "LSize: " << LSize << ", RSize: " << RSize << '\n'); 2096 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second; 2097 J!=E; ++I, ++J) { 2098 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue(); 2099 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue(); 2100 APInt Range = ComputeRange(LEnd, RBegin); 2101 assert((Range - 2ULL).isNonNegative() && 2102 "Invalid case distance"); 2103 // Use volatile double here to avoid excess precision issues on some hosts, 2104 // e.g. that use 80-bit X87 registers. 2105 volatile double LDensity = 2106 (double)LSize.roundToDouble() / 2107 (LEnd - First + 1ULL).roundToDouble(); 2108 volatile double RDensity = 2109 (double)RSize.roundToDouble() / 2110 (Last - RBegin + 1ULL).roundToDouble(); 2111 double Metric = Range.logBase2()*(LDensity+RDensity); 2112 // Should always split in some non-trivial place 2113 DEBUG(dbgs() <<"=>Step\n" 2114 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n' 2115 << "LDensity: " << LDensity 2116 << ", RDensity: " << RDensity << '\n' 2117 << "Metric: " << Metric << '\n'); 2118 if (FMetric < Metric) { 2119 Pivot = J; 2120 FMetric = Metric; 2121 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n'); 2122 } 2123 2124 LSize += J->size(); 2125 RSize -= J->size(); 2126 } 2127 if (areJTsAllowed(TLI)) { 2128 // If our case is dense we *really* should handle it earlier! 2129 assert((FMetric > 0) && "Should handle dense range earlier!"); 2130 } else { 2131 Pivot = CR.Range.first + Size/2; 2132 } 2133 2134 CaseRange LHSR(CR.Range.first, Pivot); 2135 CaseRange RHSR(Pivot, CR.Range.second); 2136 Constant *C = Pivot->Low; 2137 MachineBasicBlock *FalseBB = 0, *TrueBB = 0; 2138 2139 // We know that we branch to the LHS if the Value being switched on is 2140 // less than the Pivot value, C. We use this to optimize our binary 2141 // tree a bit, by recognizing that if SV is greater than or equal to the 2142 // LHS's Case Value, and that Case Value is exactly one less than the 2143 // Pivot's Value, then we can branch directly to the LHS's Target, 2144 // rather than creating a leaf node for it. 2145 if ((LHSR.second - LHSR.first) == 1 && 2146 LHSR.first->High == CR.GE && 2147 cast<ConstantInt>(C)->getValue() == 2148 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) { 2149 TrueBB = LHSR.first->BB; 2150 } else { 2151 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2152 CurMF->insert(BBI, TrueBB); 2153 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR)); 2154 2155 // Put SV in a virtual register to make it available from the new blocks. 2156 ExportFromCurrentBlock(SV); 2157 } 2158 2159 // Similar to the optimization above, if the Value being switched on is 2160 // known to be less than the Constant CR.LT, and the current Case Value 2161 // is CR.LT - 1, then we can branch directly to the target block for 2162 // the current Case Value, rather than emitting a RHS leaf node for it. 2163 if ((RHSR.second - RHSR.first) == 1 && CR.LT && 2164 cast<ConstantInt>(RHSR.first->Low)->getValue() == 2165 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) { 2166 FalseBB = RHSR.first->BB; 2167 } else { 2168 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2169 CurMF->insert(BBI, FalseBB); 2170 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR)); 2171 2172 // Put SV in a virtual register to make it available from the new blocks. 2173 ExportFromCurrentBlock(SV); 2174 } 2175 2176 // Create a CaseBlock record representing a conditional branch to 2177 // the LHS node if the value being switched on SV is less than C. 2178 // Otherwise, branch to LHS. 2179 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB); 2180 2181 if (CR.CaseBB == SwitchBB) 2182 visitSwitchCase(CB, SwitchBB); 2183 else 2184 SwitchCases.push_back(CB); 2185 2186 return true; 2187} 2188 2189/// handleBitTestsSwitchCase - if current case range has few destination and 2190/// range span less, than machine word bitwidth, encode case range into series 2191/// of masks and emit bit tests with these masks. 2192bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR, 2193 CaseRecVector& WorkList, 2194 const Value* SV, 2195 MachineBasicBlock* Default, 2196 MachineBasicBlock *SwitchBB){ 2197 EVT PTy = TLI.getPointerTy(); 2198 unsigned IntPtrBits = PTy.getSizeInBits(); 2199 2200 Case& FrontCase = *CR.Range.first; 2201 Case& BackCase = *(CR.Range.second-1); 2202 2203 // Get the MachineFunction which holds the current MBB. This is used when 2204 // inserting any additional MBBs necessary to represent the switch. 2205 MachineFunction *CurMF = FuncInfo.MF; 2206 2207 // If target does not have legal shift left, do not emit bit tests at all. 2208 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy())) 2209 return false; 2210 2211 size_t numCmps = 0; 2212 for (CaseItr I = CR.Range.first, E = CR.Range.second; 2213 I!=E; ++I) { 2214 // Single case counts one, case range - two. 2215 numCmps += (I->Low == I->High ? 1 : 2); 2216 } 2217 2218 // Count unique destinations 2219 SmallSet<MachineBasicBlock*, 4> Dests; 2220 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 2221 Dests.insert(I->BB); 2222 if (Dests.size() > 3) 2223 // Don't bother the code below, if there are too much unique destinations 2224 return false; 2225 } 2226 DEBUG(dbgs() << "Total number of unique destinations: " 2227 << Dests.size() << '\n' 2228 << "Total number of comparisons: " << numCmps << '\n'); 2229 2230 // Compute span of values. 2231 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue(); 2232 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue(); 2233 APInt cmpRange = maxValue - minValue; 2234 2235 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n' 2236 << "Low bound: " << minValue << '\n' 2237 << "High bound: " << maxValue << '\n'); 2238 2239 if (cmpRange.uge(IntPtrBits) || 2240 (!(Dests.size() == 1 && numCmps >= 3) && 2241 !(Dests.size() == 2 && numCmps >= 5) && 2242 !(Dests.size() >= 3 && numCmps >= 6))) 2243 return false; 2244 2245 DEBUG(dbgs() << "Emitting bit tests\n"); 2246 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth()); 2247 2248 // Optimize the case where all the case values fit in a 2249 // word without having to subtract minValue. In this case, 2250 // we can optimize away the subtraction. 2251 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) { 2252 cmpRange = maxValue; 2253 } else { 2254 lowBound = minValue; 2255 } 2256 2257 CaseBitsVector CasesBits; 2258 unsigned i, count = 0; 2259 2260 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 2261 MachineBasicBlock* Dest = I->BB; 2262 for (i = 0; i < count; ++i) 2263 if (Dest == CasesBits[i].BB) 2264 break; 2265 2266 if (i == count) { 2267 assert((count < 3) && "Too much destinations to test!"); 2268 CasesBits.push_back(CaseBits(0, Dest, 0)); 2269 count++; 2270 } 2271 2272 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue(); 2273 const APInt& highValue = cast<ConstantInt>(I->High)->getValue(); 2274 2275 uint64_t lo = (lowValue - lowBound).getZExtValue(); 2276 uint64_t hi = (highValue - lowBound).getZExtValue(); 2277 2278 for (uint64_t j = lo; j <= hi; j++) { 2279 CasesBits[i].Mask |= 1ULL << j; 2280 CasesBits[i].Bits++; 2281 } 2282 2283 } 2284 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp()); 2285 2286 BitTestInfo BTC; 2287 2288 // Figure out which block is immediately after the current one. 2289 MachineFunction::iterator BBI = CR.CaseBB; 2290 ++BBI; 2291 2292 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 2293 2294 DEBUG(dbgs() << "Cases:\n"); 2295 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) { 2296 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask 2297 << ", Bits: " << CasesBits[i].Bits 2298 << ", BB: " << CasesBits[i].BB << '\n'); 2299 2300 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2301 CurMF->insert(BBI, CaseBB); 2302 BTC.push_back(BitTestCase(CasesBits[i].Mask, 2303 CaseBB, 2304 CasesBits[i].BB)); 2305 2306 // Put SV in a virtual register to make it available from the new blocks. 2307 ExportFromCurrentBlock(SV); 2308 } 2309 2310 BitTestBlock BTB(lowBound, cmpRange, SV, 2311 -1U, MVT::Other, (CR.CaseBB == SwitchBB), 2312 CR.CaseBB, Default, BTC); 2313 2314 if (CR.CaseBB == SwitchBB) 2315 visitBitTestHeader(BTB, SwitchBB); 2316 2317 BitTestCases.push_back(BTB); 2318 2319 return true; 2320} 2321 2322/// Clusterify - Transform simple list of Cases into list of CaseRange's 2323size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases, 2324 const SwitchInst& SI) { 2325 size_t numCmps = 0; 2326 2327 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2328 // Start with "simple" cases 2329 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) { 2330 BasicBlock *SuccBB = SI.getSuccessor(i); 2331 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB]; 2332 2333 uint32_t ExtraWeight = BPI ? BPI->getEdgeWeight(SI.getParent(), SuccBB) : 0; 2334 2335 Cases.push_back(Case(SI.getSuccessorValue(i), 2336 SI.getSuccessorValue(i), 2337 SMBB, ExtraWeight)); 2338 } 2339 std::sort(Cases.begin(), Cases.end(), CaseCmp()); 2340 2341 // Merge case into clusters 2342 if (Cases.size() >= 2) 2343 // Must recompute end() each iteration because it may be 2344 // invalidated by erase if we hold on to it 2345 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin()); 2346 J != Cases.end(); ) { 2347 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue(); 2348 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue(); 2349 MachineBasicBlock* nextBB = J->BB; 2350 MachineBasicBlock* currentBB = I->BB; 2351 2352 // If the two neighboring cases go to the same destination, merge them 2353 // into a single case. 2354 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) { 2355 I->High = J->High; 2356 J = Cases.erase(J); 2357 2358 if (BranchProbabilityInfo *BPI = FuncInfo.BPI) { 2359 uint32_t CurWeight = currentBB->getBasicBlock() ? 2360 BPI->getEdgeWeight(SI.getParent(), currentBB->getBasicBlock()) : 16; 2361 uint32_t NextWeight = nextBB->getBasicBlock() ? 2362 BPI->getEdgeWeight(SI.getParent(), nextBB->getBasicBlock()) : 16; 2363 2364 BPI->setEdgeWeight(SI.getParent(), currentBB->getBasicBlock(), 2365 CurWeight + NextWeight); 2366 } 2367 } else { 2368 I = J++; 2369 } 2370 } 2371 2372 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) { 2373 if (I->Low != I->High) 2374 // A range counts double, since it requires two compares. 2375 ++numCmps; 2376 } 2377 2378 return numCmps; 2379} 2380 2381void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2382 MachineBasicBlock *Last) { 2383 // Update JTCases. 2384 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2385 if (JTCases[i].first.HeaderBB == First) 2386 JTCases[i].first.HeaderBB = Last; 2387 2388 // Update BitTestCases. 2389 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2390 if (BitTestCases[i].Parent == First) 2391 BitTestCases[i].Parent = Last; 2392} 2393 2394void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 2395 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 2396 2397 // Figure out which block is immediately after the current one. 2398 MachineBasicBlock *NextBlock = 0; 2399 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()]; 2400 2401 // If there is only the default destination, branch to it if it is not the 2402 // next basic block. Otherwise, just fall through. 2403 if (SI.getNumOperands() == 2) { 2404 // Update machine-CFG edges. 2405 2406 // If this is not a fall-through branch, emit the branch. 2407 SwitchMBB->addSuccessor(Default); 2408 if (Default != NextBlock) 2409 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 2410 MVT::Other, getControlRoot(), 2411 DAG.getBasicBlock(Default))); 2412 2413 return; 2414 } 2415 2416 // If there are any non-default case statements, create a vector of Cases 2417 // representing each one, and sort the vector so that we can efficiently 2418 // create a binary search tree from them. 2419 CaseVector Cases; 2420 size_t numCmps = Clusterify(Cases, SI); 2421 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size() 2422 << ". Total compares: " << numCmps << '\n'); 2423 numCmps = 0; 2424 2425 // Get the Value to be switched on and default basic blocks, which will be 2426 // inserted into CaseBlock records, representing basic blocks in the binary 2427 // search tree. 2428 const Value *SV = SI.getOperand(0); 2429 2430 // Push the initial CaseRec onto the worklist 2431 CaseRecVector WorkList; 2432 WorkList.push_back(CaseRec(SwitchMBB,0,0, 2433 CaseRange(Cases.begin(),Cases.end()))); 2434 2435 while (!WorkList.empty()) { 2436 // Grab a record representing a case range to process off the worklist 2437 CaseRec CR = WorkList.back(); 2438 WorkList.pop_back(); 2439 2440 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB)) 2441 continue; 2442 2443 // If the range has few cases (two or less) emit a series of specific 2444 // tests. 2445 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB)) 2446 continue; 2447 2448 // If the switch has more than 5 blocks, and at least 40% dense, and the 2449 // target supports indirect branches, then emit a jump table rather than 2450 // lowering the switch to a binary tree of conditional branches. 2451 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB)) 2452 continue; 2453 2454 // Emit binary tree. We need to pick a pivot, and push left and right ranges 2455 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call. 2456 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB); 2457 } 2458} 2459 2460void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2461 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2462 2463 // Update machine-CFG edges with unique successors. 2464 SmallVector<BasicBlock*, 32> succs; 2465 succs.reserve(I.getNumSuccessors()); 2466 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) 2467 succs.push_back(I.getSuccessor(i)); 2468 array_pod_sort(succs.begin(), succs.end()); 2469 succs.erase(std::unique(succs.begin(), succs.end()), succs.end()); 2470 for (unsigned i = 0, e = succs.size(); i != e; ++i) { 2471 MachineBasicBlock *Succ = FuncInfo.MBBMap[succs[i]]; 2472 addSuccessorWithWeight(IndirectBrMBB, Succ); 2473 } 2474 2475 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(), 2476 MVT::Other, getControlRoot(), 2477 getValue(I.getAddress()))); 2478} 2479 2480void SelectionDAGBuilder::visitFSub(const User &I) { 2481 // -0.0 - X --> fneg 2482 Type *Ty = I.getType(); 2483 if (isa<Constant>(I.getOperand(0)) && 2484 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2485 SDValue Op2 = getValue(I.getOperand(1)); 2486 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(), 2487 Op2.getValueType(), Op2)); 2488 return; 2489 } 2490 2491 visitBinary(I, ISD::FSUB); 2492} 2493 2494void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) { 2495 SDValue Op1 = getValue(I.getOperand(0)); 2496 SDValue Op2 = getValue(I.getOperand(1)); 2497 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(), 2498 Op1.getValueType(), Op1, Op2)); 2499} 2500 2501void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2502 SDValue Op1 = getValue(I.getOperand(0)); 2503 SDValue Op2 = getValue(I.getOperand(1)); 2504 2505 MVT ShiftTy = TLI.getShiftAmountTy(Op2.getValueType()); 2506 2507 // Coerce the shift amount to the right type if we can. 2508 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2509 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2510 unsigned Op2Size = Op2.getValueType().getSizeInBits(); 2511 DebugLoc DL = getCurDebugLoc(); 2512 2513 // If the operand is smaller than the shift count type, promote it. 2514 if (ShiftSize > Op2Size) 2515 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2516 2517 // If the operand is larger than the shift count type but the shift 2518 // count type has enough bits to represent any shift value, truncate 2519 // it now. This is a common case and it exposes the truncate to 2520 // optimization early. 2521 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits())) 2522 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2523 // Otherwise we'll need to temporarily settle for some other convenient 2524 // type. Type legalization will make adjustments once the shiftee is split. 2525 else 2526 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2527 } 2528 2529 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(), 2530 Op1.getValueType(), Op1, Op2)); 2531} 2532 2533void SelectionDAGBuilder::visitSDiv(const User &I) { 2534 SDValue Op1 = getValue(I.getOperand(0)); 2535 SDValue Op2 = getValue(I.getOperand(1)); 2536 2537 // Turn exact SDivs into multiplications. 2538 // FIXME: This should be in DAGCombiner, but it doesn't have access to the 2539 // exact bit. 2540 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() && 2541 !isa<ConstantSDNode>(Op1) && 2542 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue()) 2543 setValue(&I, TLI.BuildExactSDIV(Op1, Op2, getCurDebugLoc(), DAG)); 2544 else 2545 setValue(&I, DAG.getNode(ISD::SDIV, getCurDebugLoc(), Op1.getValueType(), 2546 Op1, Op2)); 2547} 2548 2549void SelectionDAGBuilder::visitICmp(const User &I) { 2550 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2551 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2552 predicate = IC->getPredicate(); 2553 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2554 predicate = ICmpInst::Predicate(IC->getPredicate()); 2555 SDValue Op1 = getValue(I.getOperand(0)); 2556 SDValue Op2 = getValue(I.getOperand(1)); 2557 ISD::CondCode Opcode = getICmpCondCode(predicate); 2558 2559 EVT DestVT = TLI.getValueType(I.getType()); 2560 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode)); 2561} 2562 2563void SelectionDAGBuilder::visitFCmp(const User &I) { 2564 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2565 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2566 predicate = FC->getPredicate(); 2567 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2568 predicate = FCmpInst::Predicate(FC->getPredicate()); 2569 SDValue Op1 = getValue(I.getOperand(0)); 2570 SDValue Op2 = getValue(I.getOperand(1)); 2571 ISD::CondCode Condition = getFCmpCondCode(predicate); 2572 EVT DestVT = TLI.getValueType(I.getType()); 2573 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition)); 2574} 2575 2576void SelectionDAGBuilder::visitSelect(const User &I) { 2577 SmallVector<EVT, 4> ValueVTs; 2578 ComputeValueVTs(TLI, I.getType(), ValueVTs); 2579 unsigned NumValues = ValueVTs.size(); 2580 if (NumValues == 0) return; 2581 2582 SmallVector<SDValue, 4> Values(NumValues); 2583 SDValue Cond = getValue(I.getOperand(0)); 2584 SDValue TrueVal = getValue(I.getOperand(1)); 2585 SDValue FalseVal = getValue(I.getOperand(2)); 2586 2587 for (unsigned i = 0; i != NumValues; ++i) 2588 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(), 2589 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i), 2590 Cond, 2591 SDValue(TrueVal.getNode(), 2592 TrueVal.getResNo() + i), 2593 SDValue(FalseVal.getNode(), 2594 FalseVal.getResNo() + i)); 2595 2596 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2597 DAG.getVTList(&ValueVTs[0], NumValues), 2598 &Values[0], NumValues)); 2599} 2600 2601void SelectionDAGBuilder::visitTrunc(const User &I) { 2602 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2603 SDValue N = getValue(I.getOperand(0)); 2604 EVT DestVT = TLI.getValueType(I.getType()); 2605 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N)); 2606} 2607 2608void SelectionDAGBuilder::visitZExt(const User &I) { 2609 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2610 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2611 SDValue N = getValue(I.getOperand(0)); 2612 EVT DestVT = TLI.getValueType(I.getType()); 2613 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N)); 2614} 2615 2616void SelectionDAGBuilder::visitSExt(const User &I) { 2617 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2618 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2619 SDValue N = getValue(I.getOperand(0)); 2620 EVT DestVT = TLI.getValueType(I.getType()); 2621 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N)); 2622} 2623 2624void SelectionDAGBuilder::visitFPTrunc(const User &I) { 2625 // FPTrunc is never a no-op cast, no need to check 2626 SDValue N = getValue(I.getOperand(0)); 2627 EVT DestVT = TLI.getValueType(I.getType()); 2628 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(), 2629 DestVT, N, DAG.getIntPtrConstant(0))); 2630} 2631 2632void SelectionDAGBuilder::visitFPExt(const User &I){ 2633 // FPTrunc is never a no-op cast, no need to check 2634 SDValue N = getValue(I.getOperand(0)); 2635 EVT DestVT = TLI.getValueType(I.getType()); 2636 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N)); 2637} 2638 2639void SelectionDAGBuilder::visitFPToUI(const User &I) { 2640 // FPToUI is never a no-op cast, no need to check 2641 SDValue N = getValue(I.getOperand(0)); 2642 EVT DestVT = TLI.getValueType(I.getType()); 2643 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N)); 2644} 2645 2646void SelectionDAGBuilder::visitFPToSI(const User &I) { 2647 // FPToSI is never a no-op cast, no need to check 2648 SDValue N = getValue(I.getOperand(0)); 2649 EVT DestVT = TLI.getValueType(I.getType()); 2650 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N)); 2651} 2652 2653void SelectionDAGBuilder::visitUIToFP(const User &I) { 2654 // UIToFP is never a no-op cast, no need to check 2655 SDValue N = getValue(I.getOperand(0)); 2656 EVT DestVT = TLI.getValueType(I.getType()); 2657 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N)); 2658} 2659 2660void SelectionDAGBuilder::visitSIToFP(const User &I){ 2661 // SIToFP is never a no-op cast, no need to check 2662 SDValue N = getValue(I.getOperand(0)); 2663 EVT DestVT = TLI.getValueType(I.getType()); 2664 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N)); 2665} 2666 2667void SelectionDAGBuilder::visitPtrToInt(const User &I) { 2668 // What to do depends on the size of the integer and the size of the pointer. 2669 // We can either truncate, zero extend, or no-op, accordingly. 2670 SDValue N = getValue(I.getOperand(0)); 2671 EVT DestVT = TLI.getValueType(I.getType()); 2672 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT)); 2673} 2674 2675void SelectionDAGBuilder::visitIntToPtr(const User &I) { 2676 // What to do depends on the size of the integer and the size of the pointer. 2677 // We can either truncate, zero extend, or no-op, accordingly. 2678 SDValue N = getValue(I.getOperand(0)); 2679 EVT DestVT = TLI.getValueType(I.getType()); 2680 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT)); 2681} 2682 2683void SelectionDAGBuilder::visitBitCast(const User &I) { 2684 SDValue N = getValue(I.getOperand(0)); 2685 EVT DestVT = TLI.getValueType(I.getType()); 2686 2687 // BitCast assures us that source and destination are the same size so this is 2688 // either a BITCAST or a no-op. 2689 if (DestVT != N.getValueType()) 2690 setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(), 2691 DestVT, N)); // convert types. 2692 else 2693 setValue(&I, N); // noop cast. 2694} 2695 2696void SelectionDAGBuilder::visitInsertElement(const User &I) { 2697 SDValue InVec = getValue(I.getOperand(0)); 2698 SDValue InVal = getValue(I.getOperand(1)); 2699 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 2700 TLI.getPointerTy(), 2701 getValue(I.getOperand(2))); 2702 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(), 2703 TLI.getValueType(I.getType()), 2704 InVec, InVal, InIdx)); 2705} 2706 2707void SelectionDAGBuilder::visitExtractElement(const User &I) { 2708 SDValue InVec = getValue(I.getOperand(0)); 2709 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 2710 TLI.getPointerTy(), 2711 getValue(I.getOperand(1))); 2712 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2713 TLI.getValueType(I.getType()), InVec, InIdx)); 2714} 2715 2716// Utility for visitShuffleVector - Returns true if the mask is mask starting 2717// from SIndx and increasing to the element length (undefs are allowed). 2718static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) { 2719 unsigned MaskNumElts = Mask.size(); 2720 for (unsigned i = 0; i != MaskNumElts; ++i) 2721 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx))) 2722 return false; 2723 return true; 2724} 2725 2726void SelectionDAGBuilder::visitShuffleVector(const User &I) { 2727 SmallVector<int, 8> Mask; 2728 SDValue Src1 = getValue(I.getOperand(0)); 2729 SDValue Src2 = getValue(I.getOperand(1)); 2730 2731 // Convert the ConstantVector mask operand into an array of ints, with -1 2732 // representing undef values. 2733 SmallVector<Constant*, 8> MaskElts; 2734 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts); 2735 unsigned MaskNumElts = MaskElts.size(); 2736 for (unsigned i = 0; i != MaskNumElts; ++i) { 2737 if (isa<UndefValue>(MaskElts[i])) 2738 Mask.push_back(-1); 2739 else 2740 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue()); 2741 } 2742 2743 EVT VT = TLI.getValueType(I.getType()); 2744 EVT SrcVT = Src1.getValueType(); 2745 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 2746 2747 if (SrcNumElts == MaskNumElts) { 2748 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2749 &Mask[0])); 2750 return; 2751 } 2752 2753 // Normalize the shuffle vector since mask and vector length don't match. 2754 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) { 2755 // Mask is longer than the source vectors and is a multiple of the source 2756 // vectors. We can use concatenate vector to make the mask and vectors 2757 // lengths match. 2758 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) { 2759 // The shuffle is concatenating two vectors together. 2760 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(), 2761 VT, Src1, Src2)); 2762 return; 2763 } 2764 2765 // Pad both vectors with undefs to make them the same length as the mask. 2766 unsigned NumConcat = MaskNumElts / SrcNumElts; 2767 bool Src1U = Src1.getOpcode() == ISD::UNDEF; 2768 bool Src2U = Src2.getOpcode() == ISD::UNDEF; 2769 SDValue UndefVal = DAG.getUNDEF(SrcVT); 2770 2771 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 2772 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 2773 MOps1[0] = Src1; 2774 MOps2[0] = Src2; 2775 2776 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2777 getCurDebugLoc(), VT, 2778 &MOps1[0], NumConcat); 2779 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2780 getCurDebugLoc(), VT, 2781 &MOps2[0], NumConcat); 2782 2783 // Readjust mask for new input vector length. 2784 SmallVector<int, 8> MappedOps; 2785 for (unsigned i = 0; i != MaskNumElts; ++i) { 2786 int Idx = Mask[i]; 2787 if (Idx < (int)SrcNumElts) 2788 MappedOps.push_back(Idx); 2789 else 2790 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts); 2791 } 2792 2793 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2794 &MappedOps[0])); 2795 return; 2796 } 2797 2798 if (SrcNumElts > MaskNumElts) { 2799 // Analyze the access pattern of the vector to see if we can extract 2800 // two subvectors and do the shuffle. The analysis is done by calculating 2801 // the range of elements the mask access on both vectors. 2802 int MinRange[2] = { static_cast<int>(SrcNumElts+1), 2803 static_cast<int>(SrcNumElts+1)}; 2804 int MaxRange[2] = {-1, -1}; 2805 2806 for (unsigned i = 0; i != MaskNumElts; ++i) { 2807 int Idx = Mask[i]; 2808 int Input = 0; 2809 if (Idx < 0) 2810 continue; 2811 2812 if (Idx >= (int)SrcNumElts) { 2813 Input = 1; 2814 Idx -= SrcNumElts; 2815 } 2816 if (Idx > MaxRange[Input]) 2817 MaxRange[Input] = Idx; 2818 if (Idx < MinRange[Input]) 2819 MinRange[Input] = Idx; 2820 } 2821 2822 // Check if the access is smaller than the vector size and can we find 2823 // a reasonable extract index. 2824 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not 2825 // Extract. 2826 int StartIdx[2]; // StartIdx to extract from 2827 for (int Input=0; Input < 2; ++Input) { 2828 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) { 2829 RangeUse[Input] = 0; // Unused 2830 StartIdx[Input] = 0; 2831 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) { 2832 // Fits within range but we should see if we can find a good 2833 // start index that is a multiple of the mask length. 2834 if (MaxRange[Input] < (int)MaskNumElts) { 2835 RangeUse[Input] = 1; // Extract from beginning of the vector 2836 StartIdx[Input] = 0; 2837 } else { 2838 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts; 2839 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts && 2840 StartIdx[Input] + MaskNumElts <= SrcNumElts) 2841 RangeUse[Input] = 1; // Extract from a multiple of the mask length. 2842 } 2843 } 2844 } 2845 2846 if (RangeUse[0] == 0 && RangeUse[1] == 0) { 2847 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 2848 return; 2849 } 2850 else if (RangeUse[0] < 2 && RangeUse[1] < 2) { 2851 // Extract appropriate subvector and generate a vector shuffle 2852 for (int Input=0; Input < 2; ++Input) { 2853 SDValue &Src = Input == 0 ? Src1 : Src2; 2854 if (RangeUse[Input] == 0) 2855 Src = DAG.getUNDEF(VT); 2856 else 2857 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT, 2858 Src, DAG.getIntPtrConstant(StartIdx[Input])); 2859 } 2860 2861 // Calculate new mask. 2862 SmallVector<int, 8> MappedOps; 2863 for (unsigned i = 0; i != MaskNumElts; ++i) { 2864 int Idx = Mask[i]; 2865 if (Idx < 0) 2866 MappedOps.push_back(Idx); 2867 else if (Idx < (int)SrcNumElts) 2868 MappedOps.push_back(Idx - StartIdx[0]); 2869 else 2870 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts); 2871 } 2872 2873 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2874 &MappedOps[0])); 2875 return; 2876 } 2877 } 2878 2879 // We can't use either concat vectors or extract subvectors so fall back to 2880 // replacing the shuffle with extract and build vector. 2881 // to insert and build vector. 2882 EVT EltVT = VT.getVectorElementType(); 2883 EVT PtrVT = TLI.getPointerTy(); 2884 SmallVector<SDValue,8> Ops; 2885 for (unsigned i = 0; i != MaskNumElts; ++i) { 2886 if (Mask[i] < 0) { 2887 Ops.push_back(DAG.getUNDEF(EltVT)); 2888 } else { 2889 int Idx = Mask[i]; 2890 SDValue Res; 2891 2892 if (Idx < (int)SrcNumElts) 2893 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2894 EltVT, Src1, DAG.getConstant(Idx, PtrVT)); 2895 else 2896 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2897 EltVT, Src2, 2898 DAG.getConstant(Idx - SrcNumElts, PtrVT)); 2899 2900 Ops.push_back(Res); 2901 } 2902 } 2903 2904 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 2905 VT, &Ops[0], Ops.size())); 2906} 2907 2908void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 2909 const Value *Op0 = I.getOperand(0); 2910 const Value *Op1 = I.getOperand(1); 2911 Type *AggTy = I.getType(); 2912 Type *ValTy = Op1->getType(); 2913 bool IntoUndef = isa<UndefValue>(Op0); 2914 bool FromUndef = isa<UndefValue>(Op1); 2915 2916 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices()); 2917 2918 SmallVector<EVT, 4> AggValueVTs; 2919 ComputeValueVTs(TLI, AggTy, AggValueVTs); 2920 SmallVector<EVT, 4> ValValueVTs; 2921 ComputeValueVTs(TLI, ValTy, ValValueVTs); 2922 2923 unsigned NumAggValues = AggValueVTs.size(); 2924 unsigned NumValValues = ValValueVTs.size(); 2925 SmallVector<SDValue, 4> Values(NumAggValues); 2926 2927 SDValue Agg = getValue(Op0); 2928 unsigned i = 0; 2929 // Copy the beginning value(s) from the original aggregate. 2930 for (; i != LinearIndex; ++i) 2931 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2932 SDValue(Agg.getNode(), Agg.getResNo() + i); 2933 // Copy values from the inserted value(s). 2934 if (NumValValues) { 2935 SDValue Val = getValue(Op1); 2936 for (; i != LinearIndex + NumValValues; ++i) 2937 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2938 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 2939 } 2940 // Copy remaining value(s) from the original aggregate. 2941 for (; i != NumAggValues; ++i) 2942 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2943 SDValue(Agg.getNode(), Agg.getResNo() + i); 2944 2945 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2946 DAG.getVTList(&AggValueVTs[0], NumAggValues), 2947 &Values[0], NumAggValues)); 2948} 2949 2950void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 2951 const Value *Op0 = I.getOperand(0); 2952 Type *AggTy = Op0->getType(); 2953 Type *ValTy = I.getType(); 2954 bool OutOfUndef = isa<UndefValue>(Op0); 2955 2956 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices()); 2957 2958 SmallVector<EVT, 4> ValValueVTs; 2959 ComputeValueVTs(TLI, ValTy, ValValueVTs); 2960 2961 unsigned NumValValues = ValValueVTs.size(); 2962 2963 // Ignore a extractvalue that produces an empty object 2964 if (!NumValValues) { 2965 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 2966 return; 2967 } 2968 2969 SmallVector<SDValue, 4> Values(NumValValues); 2970 2971 SDValue Agg = getValue(Op0); 2972 // Copy out the selected value(s). 2973 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 2974 Values[i - LinearIndex] = 2975 OutOfUndef ? 2976 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 2977 SDValue(Agg.getNode(), Agg.getResNo() + i); 2978 2979 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2980 DAG.getVTList(&ValValueVTs[0], NumValValues), 2981 &Values[0], NumValValues)); 2982} 2983 2984void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 2985 SDValue N = getValue(I.getOperand(0)); 2986 Type *Ty = I.getOperand(0)->getType(); 2987 2988 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end(); 2989 OI != E; ++OI) { 2990 const Value *Idx = *OI; 2991 if (StructType *StTy = dyn_cast<StructType>(Ty)) { 2992 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue(); 2993 if (Field) { 2994 // N = N + Offset 2995 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field); 2996 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N, 2997 DAG.getIntPtrConstant(Offset)); 2998 } 2999 3000 Ty = StTy->getElementType(Field); 3001 } else { 3002 Ty = cast<SequentialType>(Ty)->getElementType(); 3003 3004 // If this is a constant subscript, handle it quickly. 3005 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 3006 if (CI->isZero()) continue; 3007 uint64_t Offs = 3008 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue(); 3009 SDValue OffsVal; 3010 EVT PTy = TLI.getPointerTy(); 3011 unsigned PtrBits = PTy.getSizeInBits(); 3012 if (PtrBits < 64) 3013 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 3014 TLI.getPointerTy(), 3015 DAG.getConstant(Offs, MVT::i64)); 3016 else 3017 OffsVal = DAG.getIntPtrConstant(Offs); 3018 3019 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N, 3020 OffsVal); 3021 continue; 3022 } 3023 3024 // N = N + Idx * ElementSize; 3025 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(), 3026 TD->getTypeAllocSize(Ty)); 3027 SDValue IdxN = getValue(Idx); 3028 3029 // If the index is smaller or larger than intptr_t, truncate or extend 3030 // it. 3031 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType()); 3032 3033 // If this is a multiply by a power of two, turn it into a shl 3034 // immediately. This is a very common case. 3035 if (ElementSize != 1) { 3036 if (ElementSize.isPowerOf2()) { 3037 unsigned Amt = ElementSize.logBase2(); 3038 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(), 3039 N.getValueType(), IdxN, 3040 DAG.getConstant(Amt, TLI.getPointerTy())); 3041 } else { 3042 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy()); 3043 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(), 3044 N.getValueType(), IdxN, Scale); 3045 } 3046 } 3047 3048 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), 3049 N.getValueType(), N, IdxN); 3050 } 3051 } 3052 3053 setValue(&I, N); 3054} 3055 3056void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3057 // If this is a fixed sized alloca in the entry block of the function, 3058 // allocate it statically on the stack. 3059 if (FuncInfo.StaticAllocaMap.count(&I)) 3060 return; // getValue will auto-populate this. 3061 3062 Type *Ty = I.getAllocatedType(); 3063 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); 3064 unsigned Align = 3065 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), 3066 I.getAlignment()); 3067 3068 SDValue AllocSize = getValue(I.getArraySize()); 3069 3070 EVT IntPtr = TLI.getPointerTy(); 3071 if (AllocSize.getValueType() != IntPtr) 3072 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr); 3073 3074 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr, 3075 AllocSize, 3076 DAG.getConstant(TySize, IntPtr)); 3077 3078 // Handle alignment. If the requested alignment is less than or equal to 3079 // the stack alignment, ignore it. If the size is greater than or equal to 3080 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3081 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment(); 3082 if (Align <= StackAlign) 3083 Align = 0; 3084 3085 // Round the size of the allocation up to the stack alignment size 3086 // by add SA-1 to the size. 3087 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(), 3088 AllocSize.getValueType(), AllocSize, 3089 DAG.getIntPtrConstant(StackAlign-1)); 3090 3091 // Mask out the low bits for alignment purposes. 3092 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(), 3093 AllocSize.getValueType(), AllocSize, 3094 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1))); 3095 3096 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) }; 3097 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3098 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(), 3099 VTs, Ops, 3); 3100 setValue(&I, DSA); 3101 DAG.setRoot(DSA.getValue(1)); 3102 3103 // Inform the Frame Information that we have just allocated a variable-sized 3104 // object. 3105 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1); 3106} 3107 3108void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3109 const Value *SV = I.getOperand(0); 3110 SDValue Ptr = getValue(SV); 3111 3112 Type *Ty = I.getType(); 3113 3114 bool isVolatile = I.isVolatile(); 3115 bool isNonTemporal = I.getMetadata("nontemporal") != 0; 3116 unsigned Alignment = I.getAlignment(); 3117 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa); 3118 3119 SmallVector<EVT, 4> ValueVTs; 3120 SmallVector<uint64_t, 4> Offsets; 3121 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets); 3122 unsigned NumValues = ValueVTs.size(); 3123 if (NumValues == 0) 3124 return; 3125 3126 SDValue Root; 3127 bool ConstantMemory = false; 3128 if (I.isVolatile() || NumValues > MaxParallelChains) 3129 // Serialize volatile loads with other side effects. 3130 Root = getRoot(); 3131 else if (AA->pointsToConstantMemory( 3132 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) { 3133 // Do not serialize (non-volatile) loads of constant memory with anything. 3134 Root = DAG.getEntryNode(); 3135 ConstantMemory = true; 3136 } else { 3137 // Do not serialize non-volatile loads against each other. 3138 Root = DAG.getRoot(); 3139 } 3140 3141 SmallVector<SDValue, 4> Values(NumValues); 3142 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains), 3143 NumValues)); 3144 EVT PtrVT = Ptr.getValueType(); 3145 unsigned ChainI = 0; 3146 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3147 // Serializing loads here may result in excessive register pressure, and 3148 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3149 // could recover a bit by hoisting nodes upward in the chain by recognizing 3150 // they are side-effect free or do not alias. The optimizer should really 3151 // avoid this case by converting large object/array copies to llvm.memcpy 3152 // (MaxParallelChains should always remain as failsafe). 3153 if (ChainI == MaxParallelChains) { 3154 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3155 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 3156 MVT::Other, &Chains[0], ChainI); 3157 Root = Chain; 3158 ChainI = 0; 3159 } 3160 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(), 3161 PtrVT, Ptr, 3162 DAG.getConstant(Offsets[i], PtrVT)); 3163 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root, 3164 A, MachinePointerInfo(SV, Offsets[i]), isVolatile, 3165 isNonTemporal, Alignment, TBAAInfo); 3166 3167 Values[i] = L; 3168 Chains[ChainI] = L.getValue(1); 3169 } 3170 3171 if (!ConstantMemory) { 3172 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 3173 MVT::Other, &Chains[0], ChainI); 3174 if (isVolatile) 3175 DAG.setRoot(Chain); 3176 else 3177 PendingLoads.push_back(Chain); 3178 } 3179 3180 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 3181 DAG.getVTList(&ValueVTs[0], NumValues), 3182 &Values[0], NumValues)); 3183} 3184 3185void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3186 const Value *SrcV = I.getOperand(0); 3187 const Value *PtrV = I.getOperand(1); 3188 3189 SmallVector<EVT, 4> ValueVTs; 3190 SmallVector<uint64_t, 4> Offsets; 3191 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets); 3192 unsigned NumValues = ValueVTs.size(); 3193 if (NumValues == 0) 3194 return; 3195 3196 // Get the lowered operands. Note that we do this after 3197 // checking if NumResults is zero, because with zero results 3198 // the operands won't have values in the map. 3199 SDValue Src = getValue(SrcV); 3200 SDValue Ptr = getValue(PtrV); 3201 3202 SDValue Root = getRoot(); 3203 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains), 3204 NumValues)); 3205 EVT PtrVT = Ptr.getValueType(); 3206 bool isVolatile = I.isVolatile(); 3207 bool isNonTemporal = I.getMetadata("nontemporal") != 0; 3208 unsigned Alignment = I.getAlignment(); 3209 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa); 3210 3211 unsigned ChainI = 0; 3212 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3213 // See visitLoad comments. 3214 if (ChainI == MaxParallelChains) { 3215 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 3216 MVT::Other, &Chains[0], ChainI); 3217 Root = Chain; 3218 ChainI = 0; 3219 } 3220 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr, 3221 DAG.getConstant(Offsets[i], PtrVT)); 3222 SDValue St = DAG.getStore(Root, getCurDebugLoc(), 3223 SDValue(Src.getNode(), Src.getResNo() + i), 3224 Add, MachinePointerInfo(PtrV, Offsets[i]), 3225 isVolatile, isNonTemporal, Alignment, TBAAInfo); 3226 Chains[ChainI] = St; 3227 } 3228 3229 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 3230 MVT::Other, &Chains[0], ChainI); 3231 ++SDNodeOrder; 3232 AssignOrderingToNode(StoreNode.getNode()); 3233 DAG.setRoot(StoreNode); 3234} 3235 3236void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 3237 SDValue Root = getRoot(); 3238 SDValue L = 3239 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(), 3240 getValue(I.getCompareOperand()).getValueType().getSimpleVT(), 3241 Root, 3242 getValue(I.getPointerOperand()), 3243 getValue(I.getCompareOperand()), 3244 getValue(I.getNewValOperand()), 3245 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */, 3246 I.getOrdering(), I.getSynchScope()); 3247 setValue(&I, L); 3248 DAG.setRoot(L.getValue(1)); 3249} 3250 3251void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 3252 ISD::NodeType NT; 3253 switch (I.getOperation()) { 3254 default: llvm_unreachable("Unknown atomicrmw operation"); return; 3255 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 3256 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 3257 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 3258 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 3259 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 3260 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 3261 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 3262 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 3263 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 3264 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 3265 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 3266 } 3267 SDValue L = 3268 DAG.getAtomic(NT, getCurDebugLoc(), 3269 getValue(I.getValOperand()).getValueType().getSimpleVT(), 3270 getRoot(), 3271 getValue(I.getPointerOperand()), 3272 getValue(I.getValOperand()), 3273 I.getPointerOperand(), 0 /* Alignment */, 3274 I.getOrdering(), I.getSynchScope()); 3275 setValue(&I, L); 3276 DAG.setRoot(L.getValue(1)); 3277} 3278 3279void SelectionDAGBuilder::visitFence(const FenceInst &I) { 3280 DebugLoc dl = getCurDebugLoc(); 3281 SDValue Ops[3]; 3282 Ops[0] = getRoot(); 3283 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy()); 3284 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy()); 3285 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3)); 3286} 3287 3288/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 3289/// node. 3290void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 3291 unsigned Intrinsic) { 3292 bool HasChain = !I.doesNotAccessMemory(); 3293 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 3294 3295 // Build the operand list. 3296 SmallVector<SDValue, 8> Ops; 3297 if (HasChain) { // If this intrinsic has side-effects, chainify it. 3298 if (OnlyLoad) { 3299 // We don't need to serialize loads against other loads. 3300 Ops.push_back(DAG.getRoot()); 3301 } else { 3302 Ops.push_back(getRoot()); 3303 } 3304 } 3305 3306 // Info is set by getTgtMemInstrinsic 3307 TargetLowering::IntrinsicInfo Info; 3308 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic); 3309 3310 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 3311 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 3312 Info.opc == ISD::INTRINSIC_W_CHAIN) 3313 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy())); 3314 3315 // Add all operands of the call to the operand list. 3316 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 3317 SDValue Op = getValue(I.getArgOperand(i)); 3318 assert(TLI.isTypeLegal(Op.getValueType()) && 3319 "Intrinsic uses a non-legal type?"); 3320 Ops.push_back(Op); 3321 } 3322 3323 SmallVector<EVT, 4> ValueVTs; 3324 ComputeValueVTs(TLI, I.getType(), ValueVTs); 3325#ifndef NDEBUG 3326 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) { 3327 assert(TLI.isTypeLegal(ValueVTs[Val]) && 3328 "Intrinsic uses a non-legal type?"); 3329 } 3330#endif // NDEBUG 3331 3332 if (HasChain) 3333 ValueVTs.push_back(MVT::Other); 3334 3335 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size()); 3336 3337 // Create the node. 3338 SDValue Result; 3339 if (IsTgtIntrinsic) { 3340 // This is target intrinsic that touches memory 3341 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(), 3342 VTs, &Ops[0], Ops.size(), 3343 Info.memVT, 3344 MachinePointerInfo(Info.ptrVal, Info.offset), 3345 Info.align, Info.vol, 3346 Info.readMem, Info.writeMem); 3347 } else if (!HasChain) { 3348 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(), 3349 VTs, &Ops[0], Ops.size()); 3350 } else if (!I.getType()->isVoidTy()) { 3351 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(), 3352 VTs, &Ops[0], Ops.size()); 3353 } else { 3354 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(), 3355 VTs, &Ops[0], Ops.size()); 3356 } 3357 3358 if (HasChain) { 3359 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 3360 if (OnlyLoad) 3361 PendingLoads.push_back(Chain); 3362 else 3363 DAG.setRoot(Chain); 3364 } 3365 3366 if (!I.getType()->isVoidTy()) { 3367 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 3368 EVT VT = TLI.getValueType(PTy); 3369 Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result); 3370 } 3371 3372 setValue(&I, Result); 3373 } 3374} 3375 3376/// GetSignificand - Get the significand and build it into a floating-point 3377/// number with exponent of 1: 3378/// 3379/// Op = (Op & 0x007fffff) | 0x3f800000; 3380/// 3381/// where Op is the hexidecimal representation of floating point value. 3382static SDValue 3383GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) { 3384 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3385 DAG.getConstant(0x007fffff, MVT::i32)); 3386 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 3387 DAG.getConstant(0x3f800000, MVT::i32)); 3388 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 3389} 3390 3391/// GetExponent - Get the exponent: 3392/// 3393/// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 3394/// 3395/// where Op is the hexidecimal representation of floating point value. 3396static SDValue 3397GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, 3398 DebugLoc dl) { 3399 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3400 DAG.getConstant(0x7f800000, MVT::i32)); 3401 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0, 3402 DAG.getConstant(23, TLI.getPointerTy())); 3403 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 3404 DAG.getConstant(127, MVT::i32)); 3405 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 3406} 3407 3408/// getF32Constant - Get 32-bit floating point constant. 3409static SDValue 3410getF32Constant(SelectionDAG &DAG, unsigned Flt) { 3411 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32); 3412} 3413 3414/// Inlined utility function to implement binary input atomic intrinsics for 3415/// visitIntrinsicCall: I is a call instruction 3416/// Op is the associated NodeType for I 3417const char * 3418SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I, 3419 ISD::NodeType Op) { 3420 SDValue Root = getRoot(); 3421 SDValue L = 3422 DAG.getAtomic(Op, getCurDebugLoc(), 3423 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(), 3424 Root, 3425 getValue(I.getArgOperand(0)), 3426 getValue(I.getArgOperand(1)), 3427 I.getArgOperand(0), 0 /* Alignment */, 3428 Monotonic, CrossThread); 3429 setValue(&I, L); 3430 DAG.setRoot(L.getValue(1)); 3431 return 0; 3432} 3433 3434// implVisitAluOverflow - Lower arithmetic overflow instrinsics. 3435const char * 3436SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) { 3437 SDValue Op1 = getValue(I.getArgOperand(0)); 3438 SDValue Op2 = getValue(I.getArgOperand(1)); 3439 3440 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 3441 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2)); 3442 return 0; 3443} 3444 3445/// visitExp - Lower an exp intrinsic. Handles the special sequences for 3446/// limited-precision mode. 3447void 3448SelectionDAGBuilder::visitExp(const CallInst &I) { 3449 SDValue result; 3450 DebugLoc dl = getCurDebugLoc(); 3451 3452 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 && 3453 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3454 SDValue Op = getValue(I.getArgOperand(0)); 3455 3456 // Put the exponent in the right bit position for later addition to the 3457 // final result: 3458 // 3459 // #define LOG2OFe 1.4426950f 3460 // IntegerPartOfX = ((int32_t)(X * LOG2OFe)); 3461 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3462 getF32Constant(DAG, 0x3fb8aa3b)); 3463 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3464 3465 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX; 3466 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3467 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3468 3469 // IntegerPartOfX <<= 23; 3470 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3471 DAG.getConstant(23, TLI.getPointerTy())); 3472 3473 if (LimitFloatPrecision <= 6) { 3474 // For floating-point precision of 6: 3475 // 3476 // TwoToFractionalPartOfX = 3477 // 0.997535578f + 3478 // (0.735607626f + 0.252464424f * x) * x; 3479 // 3480 // error 0.0144103317, which is 6 bits 3481 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3482 getF32Constant(DAG, 0x3e814304)); 3483 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3484 getF32Constant(DAG, 0x3f3c50c8)); 3485 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3486 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3487 getF32Constant(DAG, 0x3f7f5e7e)); 3488 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5); 3489 3490 // Add the exponent into the result in integer domain. 3491 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3492 TwoToFracPartOfX, IntegerPartOfX); 3493 3494 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6); 3495 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3496 // For floating-point precision of 12: 3497 // 3498 // TwoToFractionalPartOfX = 3499 // 0.999892986f + 3500 // (0.696457318f + 3501 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3502 // 3503 // 0.000107046256 error, which is 13 to 14 bits 3504 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3505 getF32Constant(DAG, 0x3da235e3)); 3506 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3507 getF32Constant(DAG, 0x3e65b8f3)); 3508 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3509 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3510 getF32Constant(DAG, 0x3f324b07)); 3511 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3512 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3513 getF32Constant(DAG, 0x3f7ff8fd)); 3514 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7); 3515 3516 // Add the exponent into the result in integer domain. 3517 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3518 TwoToFracPartOfX, IntegerPartOfX); 3519 3520 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8); 3521 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3522 // For floating-point precision of 18: 3523 // 3524 // TwoToFractionalPartOfX = 3525 // 0.999999982f + 3526 // (0.693148872f + 3527 // (0.240227044f + 3528 // (0.554906021e-1f + 3529 // (0.961591928e-2f + 3530 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3531 // 3532 // error 2.47208000*10^(-7), which is better than 18 bits 3533 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3534 getF32Constant(DAG, 0x3924b03e)); 3535 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3536 getF32Constant(DAG, 0x3ab24b87)); 3537 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3538 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3539 getF32Constant(DAG, 0x3c1d8c17)); 3540 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3541 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3542 getF32Constant(DAG, 0x3d634a1d)); 3543 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3544 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3545 getF32Constant(DAG, 0x3e75fe14)); 3546 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3547 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3548 getF32Constant(DAG, 0x3f317234)); 3549 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3550 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3551 getF32Constant(DAG, 0x3f800000)); 3552 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl, 3553 MVT::i32, t13); 3554 3555 // Add the exponent into the result in integer domain. 3556 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3557 TwoToFracPartOfX, IntegerPartOfX); 3558 3559 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14); 3560 } 3561 } else { 3562 // No special expansion. 3563 result = DAG.getNode(ISD::FEXP, dl, 3564 getValue(I.getArgOperand(0)).getValueType(), 3565 getValue(I.getArgOperand(0))); 3566 } 3567 3568 setValue(&I, result); 3569} 3570 3571/// visitLog - Lower a log intrinsic. Handles the special sequences for 3572/// limited-precision mode. 3573void 3574SelectionDAGBuilder::visitLog(const CallInst &I) { 3575 SDValue result; 3576 DebugLoc dl = getCurDebugLoc(); 3577 3578 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 && 3579 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3580 SDValue Op = getValue(I.getArgOperand(0)); 3581 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3582 3583 // Scale the exponent by log(2) [0.69314718f]. 3584 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3585 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3586 getF32Constant(DAG, 0x3f317218)); 3587 3588 // Get the significand and build it into a floating-point number with 3589 // exponent of 1. 3590 SDValue X = GetSignificand(DAG, Op1, dl); 3591 3592 if (LimitFloatPrecision <= 6) { 3593 // For floating-point precision of 6: 3594 // 3595 // LogofMantissa = 3596 // -1.1609546f + 3597 // (1.4034025f - 0.23903021f * x) * x; 3598 // 3599 // error 0.0034276066, which is better than 8 bits 3600 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3601 getF32Constant(DAG, 0xbe74c456)); 3602 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3603 getF32Constant(DAG, 0x3fb3a2b1)); 3604 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3605 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3606 getF32Constant(DAG, 0x3f949a29)); 3607 3608 result = DAG.getNode(ISD::FADD, dl, 3609 MVT::f32, LogOfExponent, LogOfMantissa); 3610 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3611 // For floating-point precision of 12: 3612 // 3613 // LogOfMantissa = 3614 // -1.7417939f + 3615 // (2.8212026f + 3616 // (-1.4699568f + 3617 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 3618 // 3619 // error 0.000061011436, which is 14 bits 3620 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3621 getF32Constant(DAG, 0xbd67b6d6)); 3622 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3623 getF32Constant(DAG, 0x3ee4f4b8)); 3624 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3625 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3626 getF32Constant(DAG, 0x3fbc278b)); 3627 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3628 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3629 getF32Constant(DAG, 0x40348e95)); 3630 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3631 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3632 getF32Constant(DAG, 0x3fdef31a)); 3633 3634 result = DAG.getNode(ISD::FADD, dl, 3635 MVT::f32, LogOfExponent, LogOfMantissa); 3636 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3637 // For floating-point precision of 18: 3638 // 3639 // LogOfMantissa = 3640 // -2.1072184f + 3641 // (4.2372794f + 3642 // (-3.7029485f + 3643 // (2.2781945f + 3644 // (-0.87823314f + 3645 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 3646 // 3647 // error 0.0000023660568, which is better than 18 bits 3648 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3649 getF32Constant(DAG, 0xbc91e5ac)); 3650 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3651 getF32Constant(DAG, 0x3e4350aa)); 3652 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3653 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3654 getF32Constant(DAG, 0x3f60d3e3)); 3655 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3656 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3657 getF32Constant(DAG, 0x4011cdf0)); 3658 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3659 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3660 getF32Constant(DAG, 0x406cfd1c)); 3661 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3662 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3663 getF32Constant(DAG, 0x408797cb)); 3664 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3665 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3666 getF32Constant(DAG, 0x4006dcab)); 3667 3668 result = DAG.getNode(ISD::FADD, dl, 3669 MVT::f32, LogOfExponent, LogOfMantissa); 3670 } 3671 } else { 3672 // No special expansion. 3673 result = DAG.getNode(ISD::FLOG, dl, 3674 getValue(I.getArgOperand(0)).getValueType(), 3675 getValue(I.getArgOperand(0))); 3676 } 3677 3678 setValue(&I, result); 3679} 3680 3681/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for 3682/// limited-precision mode. 3683void 3684SelectionDAGBuilder::visitLog2(const CallInst &I) { 3685 SDValue result; 3686 DebugLoc dl = getCurDebugLoc(); 3687 3688 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 && 3689 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3690 SDValue Op = getValue(I.getArgOperand(0)); 3691 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3692 3693 // Get the exponent. 3694 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 3695 3696 // Get the significand and build it into a floating-point number with 3697 // exponent of 1. 3698 SDValue X = GetSignificand(DAG, Op1, dl); 3699 3700 // Different possible minimax approximations of significand in 3701 // floating-point for various degrees of accuracy over [1,2]. 3702 if (LimitFloatPrecision <= 6) { 3703 // For floating-point precision of 6: 3704 // 3705 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 3706 // 3707 // error 0.0049451742, which is more than 7 bits 3708 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3709 getF32Constant(DAG, 0xbeb08fe0)); 3710 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3711 getF32Constant(DAG, 0x40019463)); 3712 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3713 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3714 getF32Constant(DAG, 0x3fd6633d)); 3715 3716 result = DAG.getNode(ISD::FADD, dl, 3717 MVT::f32, LogOfExponent, Log2ofMantissa); 3718 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3719 // For floating-point precision of 12: 3720 // 3721 // Log2ofMantissa = 3722 // -2.51285454f + 3723 // (4.07009056f + 3724 // (-2.12067489f + 3725 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 3726 // 3727 // error 0.0000876136000, which is better than 13 bits 3728 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3729 getF32Constant(DAG, 0xbda7262e)); 3730 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3731 getF32Constant(DAG, 0x3f25280b)); 3732 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3733 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3734 getF32Constant(DAG, 0x4007b923)); 3735 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3736 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3737 getF32Constant(DAG, 0x40823e2f)); 3738 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3739 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3740 getF32Constant(DAG, 0x4020d29c)); 3741 3742 result = DAG.getNode(ISD::FADD, dl, 3743 MVT::f32, LogOfExponent, Log2ofMantissa); 3744 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3745 // For floating-point precision of 18: 3746 // 3747 // Log2ofMantissa = 3748 // -3.0400495f + 3749 // (6.1129976f + 3750 // (-5.3420409f + 3751 // (3.2865683f + 3752 // (-1.2669343f + 3753 // (0.27515199f - 3754 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 3755 // 3756 // error 0.0000018516, which is better than 18 bits 3757 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3758 getF32Constant(DAG, 0xbcd2769e)); 3759 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3760 getF32Constant(DAG, 0x3e8ce0b9)); 3761 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3762 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3763 getF32Constant(DAG, 0x3fa22ae7)); 3764 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3765 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3766 getF32Constant(DAG, 0x40525723)); 3767 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3768 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3769 getF32Constant(DAG, 0x40aaf200)); 3770 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3771 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3772 getF32Constant(DAG, 0x40c39dad)); 3773 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3774 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3775 getF32Constant(DAG, 0x4042902c)); 3776 3777 result = DAG.getNode(ISD::FADD, dl, 3778 MVT::f32, LogOfExponent, Log2ofMantissa); 3779 } 3780 } else { 3781 // No special expansion. 3782 result = DAG.getNode(ISD::FLOG2, dl, 3783 getValue(I.getArgOperand(0)).getValueType(), 3784 getValue(I.getArgOperand(0))); 3785 } 3786 3787 setValue(&I, result); 3788} 3789 3790/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for 3791/// limited-precision mode. 3792void 3793SelectionDAGBuilder::visitLog10(const CallInst &I) { 3794 SDValue result; 3795 DebugLoc dl = getCurDebugLoc(); 3796 3797 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 && 3798 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3799 SDValue Op = getValue(I.getArgOperand(0)); 3800 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3801 3802 // Scale the exponent by log10(2) [0.30102999f]. 3803 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3804 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3805 getF32Constant(DAG, 0x3e9a209a)); 3806 3807 // Get the significand and build it into a floating-point number with 3808 // exponent of 1. 3809 SDValue X = GetSignificand(DAG, Op1, dl); 3810 3811 if (LimitFloatPrecision <= 6) { 3812 // For floating-point precision of 6: 3813 // 3814 // Log10ofMantissa = 3815 // -0.50419619f + 3816 // (0.60948995f - 0.10380950f * x) * x; 3817 // 3818 // error 0.0014886165, which is 6 bits 3819 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3820 getF32Constant(DAG, 0xbdd49a13)); 3821 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3822 getF32Constant(DAG, 0x3f1c0789)); 3823 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3824 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3825 getF32Constant(DAG, 0x3f011300)); 3826 3827 result = DAG.getNode(ISD::FADD, dl, 3828 MVT::f32, LogOfExponent, Log10ofMantissa); 3829 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3830 // For floating-point precision of 12: 3831 // 3832 // Log10ofMantissa = 3833 // -0.64831180f + 3834 // (0.91751397f + 3835 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 3836 // 3837 // error 0.00019228036, which is better than 12 bits 3838 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3839 getF32Constant(DAG, 0x3d431f31)); 3840 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3841 getF32Constant(DAG, 0x3ea21fb2)); 3842 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3843 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3844 getF32Constant(DAG, 0x3f6ae232)); 3845 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3846 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3847 getF32Constant(DAG, 0x3f25f7c3)); 3848 3849 result = DAG.getNode(ISD::FADD, dl, 3850 MVT::f32, LogOfExponent, Log10ofMantissa); 3851 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3852 // For floating-point precision of 18: 3853 // 3854 // Log10ofMantissa = 3855 // -0.84299375f + 3856 // (1.5327582f + 3857 // (-1.0688956f + 3858 // (0.49102474f + 3859 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 3860 // 3861 // error 0.0000037995730, which is better than 18 bits 3862 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3863 getF32Constant(DAG, 0x3c5d51ce)); 3864 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3865 getF32Constant(DAG, 0x3e00685a)); 3866 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3867 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3868 getF32Constant(DAG, 0x3efb6798)); 3869 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3870 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3871 getF32Constant(DAG, 0x3f88d192)); 3872 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3873 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3874 getF32Constant(DAG, 0x3fc4316c)); 3875 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3876 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 3877 getF32Constant(DAG, 0x3f57ce70)); 3878 3879 result = DAG.getNode(ISD::FADD, dl, 3880 MVT::f32, LogOfExponent, Log10ofMantissa); 3881 } 3882 } else { 3883 // No special expansion. 3884 result = DAG.getNode(ISD::FLOG10, dl, 3885 getValue(I.getArgOperand(0)).getValueType(), 3886 getValue(I.getArgOperand(0))); 3887 } 3888 3889 setValue(&I, result); 3890} 3891 3892/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for 3893/// limited-precision mode. 3894void 3895SelectionDAGBuilder::visitExp2(const CallInst &I) { 3896 SDValue result; 3897 DebugLoc dl = getCurDebugLoc(); 3898 3899 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 && 3900 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3901 SDValue Op = getValue(I.getArgOperand(0)); 3902 3903 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op); 3904 3905 // FractionalPartOfX = x - (float)IntegerPartOfX; 3906 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3907 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1); 3908 3909 // IntegerPartOfX <<= 23; 3910 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3911 DAG.getConstant(23, TLI.getPointerTy())); 3912 3913 if (LimitFloatPrecision <= 6) { 3914 // For floating-point precision of 6: 3915 // 3916 // TwoToFractionalPartOfX = 3917 // 0.997535578f + 3918 // (0.735607626f + 0.252464424f * x) * x; 3919 // 3920 // error 0.0144103317, which is 6 bits 3921 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3922 getF32Constant(DAG, 0x3e814304)); 3923 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3924 getF32Constant(DAG, 0x3f3c50c8)); 3925 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3926 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3927 getF32Constant(DAG, 0x3f7f5e7e)); 3928 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5); 3929 SDValue TwoToFractionalPartOfX = 3930 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX); 3931 3932 result = DAG.getNode(ISD::BITCAST, dl, 3933 MVT::f32, TwoToFractionalPartOfX); 3934 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3935 // For floating-point precision of 12: 3936 // 3937 // TwoToFractionalPartOfX = 3938 // 0.999892986f + 3939 // (0.696457318f + 3940 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3941 // 3942 // error 0.000107046256, which is 13 to 14 bits 3943 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3944 getF32Constant(DAG, 0x3da235e3)); 3945 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3946 getF32Constant(DAG, 0x3e65b8f3)); 3947 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3948 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3949 getF32Constant(DAG, 0x3f324b07)); 3950 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3951 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3952 getF32Constant(DAG, 0x3f7ff8fd)); 3953 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7); 3954 SDValue TwoToFractionalPartOfX = 3955 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX); 3956 3957 result = DAG.getNode(ISD::BITCAST, dl, 3958 MVT::f32, TwoToFractionalPartOfX); 3959 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3960 // For floating-point precision of 18: 3961 // 3962 // TwoToFractionalPartOfX = 3963 // 0.999999982f + 3964 // (0.693148872f + 3965 // (0.240227044f + 3966 // (0.554906021e-1f + 3967 // (0.961591928e-2f + 3968 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3969 // error 2.47208000*10^(-7), which is better than 18 bits 3970 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3971 getF32Constant(DAG, 0x3924b03e)); 3972 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3973 getF32Constant(DAG, 0x3ab24b87)); 3974 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3975 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3976 getF32Constant(DAG, 0x3c1d8c17)); 3977 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3978 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3979 getF32Constant(DAG, 0x3d634a1d)); 3980 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3981 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3982 getF32Constant(DAG, 0x3e75fe14)); 3983 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3984 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3985 getF32Constant(DAG, 0x3f317234)); 3986 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3987 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3988 getF32Constant(DAG, 0x3f800000)); 3989 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13); 3990 SDValue TwoToFractionalPartOfX = 3991 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX); 3992 3993 result = DAG.getNode(ISD::BITCAST, dl, 3994 MVT::f32, TwoToFractionalPartOfX); 3995 } 3996 } else { 3997 // No special expansion. 3998 result = DAG.getNode(ISD::FEXP2, dl, 3999 getValue(I.getArgOperand(0)).getValueType(), 4000 getValue(I.getArgOperand(0))); 4001 } 4002 4003 setValue(&I, result); 4004} 4005 4006/// visitPow - Lower a pow intrinsic. Handles the special sequences for 4007/// limited-precision mode with x == 10.0f. 4008void 4009SelectionDAGBuilder::visitPow(const CallInst &I) { 4010 SDValue result; 4011 const Value *Val = I.getArgOperand(0); 4012 DebugLoc dl = getCurDebugLoc(); 4013 bool IsExp10 = false; 4014 4015 if (getValue(Val).getValueType() == MVT::f32 && 4016 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 && 4017 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4018 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) { 4019 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 4020 APFloat Ten(10.0f); 4021 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten); 4022 } 4023 } 4024 } 4025 4026 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4027 SDValue Op = getValue(I.getArgOperand(1)); 4028 4029 // Put the exponent in the right bit position for later addition to the 4030 // final result: 4031 // 4032 // #define LOG2OF10 3.3219281f 4033 // IntegerPartOfX = (int32_t)(x * LOG2OF10); 4034 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4035 getF32Constant(DAG, 0x40549a78)); 4036 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4037 4038 // FractionalPartOfX = x - (float)IntegerPartOfX; 4039 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4040 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4041 4042 // IntegerPartOfX <<= 23; 4043 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4044 DAG.getConstant(23, TLI.getPointerTy())); 4045 4046 if (LimitFloatPrecision <= 6) { 4047 // For floating-point precision of 6: 4048 // 4049 // twoToFractionalPartOfX = 4050 // 0.997535578f + 4051 // (0.735607626f + 0.252464424f * x) * x; 4052 // 4053 // error 0.0144103317, which is 6 bits 4054 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4055 getF32Constant(DAG, 0x3e814304)); 4056 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4057 getF32Constant(DAG, 0x3f3c50c8)); 4058 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4059 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4060 getF32Constant(DAG, 0x3f7f5e7e)); 4061 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5); 4062 SDValue TwoToFractionalPartOfX = 4063 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX); 4064 4065 result = DAG.getNode(ISD::BITCAST, dl, 4066 MVT::f32, TwoToFractionalPartOfX); 4067 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 4068 // For floating-point precision of 12: 4069 // 4070 // TwoToFractionalPartOfX = 4071 // 0.999892986f + 4072 // (0.696457318f + 4073 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4074 // 4075 // error 0.000107046256, which is 13 to 14 bits 4076 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4077 getF32Constant(DAG, 0x3da235e3)); 4078 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4079 getF32Constant(DAG, 0x3e65b8f3)); 4080 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4081 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4082 getF32Constant(DAG, 0x3f324b07)); 4083 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4084 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4085 getF32Constant(DAG, 0x3f7ff8fd)); 4086 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7); 4087 SDValue TwoToFractionalPartOfX = 4088 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX); 4089 4090 result = DAG.getNode(ISD::BITCAST, dl, 4091 MVT::f32, TwoToFractionalPartOfX); 4092 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 4093 // For floating-point precision of 18: 4094 // 4095 // TwoToFractionalPartOfX = 4096 // 0.999999982f + 4097 // (0.693148872f + 4098 // (0.240227044f + 4099 // (0.554906021e-1f + 4100 // (0.961591928e-2f + 4101 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4102 // error 2.47208000*10^(-7), which is better than 18 bits 4103 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4104 getF32Constant(DAG, 0x3924b03e)); 4105 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4106 getF32Constant(DAG, 0x3ab24b87)); 4107 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4108 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4109 getF32Constant(DAG, 0x3c1d8c17)); 4110 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4111 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4112 getF32Constant(DAG, 0x3d634a1d)); 4113 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4114 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4115 getF32Constant(DAG, 0x3e75fe14)); 4116 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4117 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4118 getF32Constant(DAG, 0x3f317234)); 4119 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4120 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4121 getF32Constant(DAG, 0x3f800000)); 4122 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13); 4123 SDValue TwoToFractionalPartOfX = 4124 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX); 4125 4126 result = DAG.getNode(ISD::BITCAST, dl, 4127 MVT::f32, TwoToFractionalPartOfX); 4128 } 4129 } else { 4130 // No special expansion. 4131 result = DAG.getNode(ISD::FPOW, dl, 4132 getValue(I.getArgOperand(0)).getValueType(), 4133 getValue(I.getArgOperand(0)), 4134 getValue(I.getArgOperand(1))); 4135 } 4136 4137 setValue(&I, result); 4138} 4139 4140 4141/// ExpandPowI - Expand a llvm.powi intrinsic. 4142static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS, 4143 SelectionDAG &DAG) { 4144 // If RHS is a constant, we can expand this out to a multiplication tree, 4145 // otherwise we end up lowering to a call to __powidf2 (for example). When 4146 // optimizing for size, we only want to do this if the expansion would produce 4147 // a small number of multiplies, otherwise we do the full expansion. 4148 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4149 // Get the exponent as a positive value. 4150 unsigned Val = RHSC->getSExtValue(); 4151 if ((int)Val < 0) Val = -Val; 4152 4153 // powi(x, 0) -> 1.0 4154 if (Val == 0) 4155 return DAG.getConstantFP(1.0, LHS.getValueType()); 4156 4157 const Function *F = DAG.getMachineFunction().getFunction(); 4158 if (!F->hasFnAttr(Attribute::OptimizeForSize) || 4159 // If optimizing for size, don't insert too many multiplies. This 4160 // inserts up to 5 multiplies. 4161 CountPopulation_32(Val)+Log2_32(Val) < 7) { 4162 // We use the simple binary decomposition method to generate the multiply 4163 // sequence. There are more optimal ways to do this (for example, 4164 // powi(x,15) generates one more multiply than it should), but this has 4165 // the benefit of being both really simple and much better than a libcall. 4166 SDValue Res; // Logically starts equal to 1.0 4167 SDValue CurSquare = LHS; 4168 while (Val) { 4169 if (Val & 1) { 4170 if (Res.getNode()) 4171 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4172 else 4173 Res = CurSquare; // 1.0*CurSquare. 4174 } 4175 4176 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4177 CurSquare, CurSquare); 4178 Val >>= 1; 4179 } 4180 4181 // If the original was negative, invert the result, producing 1/(x*x*x). 4182 if (RHSC->getSExtValue() < 0) 4183 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4184 DAG.getConstantFP(1.0, LHS.getValueType()), Res); 4185 return Res; 4186 } 4187 } 4188 4189 // Otherwise, expand to a libcall. 4190 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4191} 4192 4193// getTruncatedArgReg - Find underlying register used for an truncated 4194// argument. 4195static unsigned getTruncatedArgReg(const SDValue &N) { 4196 if (N.getOpcode() != ISD::TRUNCATE) 4197 return 0; 4198 4199 const SDValue &Ext = N.getOperand(0); 4200 if (Ext.getOpcode() == ISD::AssertZext || Ext.getOpcode() == ISD::AssertSext){ 4201 const SDValue &CFR = Ext.getOperand(0); 4202 if (CFR.getOpcode() == ISD::CopyFromReg) 4203 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg(); 4204 else 4205 if (CFR.getOpcode() == ISD::TRUNCATE) 4206 return getTruncatedArgReg(CFR); 4207 } 4208 return 0; 4209} 4210 4211/// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function 4212/// argument, create the corresponding DBG_VALUE machine instruction for it now. 4213/// At the end of instruction selection, they will be inserted to the entry BB. 4214bool 4215SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable, 4216 int64_t Offset, 4217 const SDValue &N) { 4218 const Argument *Arg = dyn_cast<Argument>(V); 4219 if (!Arg) 4220 return false; 4221 4222 MachineFunction &MF = DAG.getMachineFunction(); 4223 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo(); 4224 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 4225 4226 // Ignore inlined function arguments here. 4227 DIVariable DV(Variable); 4228 if (DV.isInlinedFnArgument(MF.getFunction())) 4229 return false; 4230 4231 unsigned Reg = 0; 4232 if (Arg->hasByValAttr()) { 4233 // Byval arguments' frame index is recorded during argument lowering. 4234 // Use this info directly. 4235 Reg = TRI->getFrameRegister(MF); 4236 Offset = FuncInfo.getByValArgumentFrameIndex(Arg); 4237 // If byval argument ofset is not recorded then ignore this. 4238 if (!Offset) 4239 Reg = 0; 4240 } 4241 4242 if (N.getNode()) { 4243 if (N.getOpcode() == ISD::CopyFromReg) 4244 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4245 else 4246 Reg = getTruncatedArgReg(N); 4247 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4248 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4249 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4250 if (PR) 4251 Reg = PR; 4252 } 4253 } 4254 4255 if (!Reg) { 4256 // Check if ValueMap has reg number. 4257 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4258 if (VMI != FuncInfo.ValueMap.end()) 4259 Reg = VMI->second; 4260 } 4261 4262 if (!Reg && N.getNode()) { 4263 // Check if frame index is available. 4264 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4265 if (FrameIndexSDNode *FINode = 4266 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) { 4267 Reg = TRI->getFrameRegister(MF); 4268 Offset = FINode->getIndex(); 4269 } 4270 } 4271 4272 if (!Reg) 4273 return false; 4274 4275 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(), 4276 TII->get(TargetOpcode::DBG_VALUE)) 4277 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable); 4278 FuncInfo.ArgDbgValues.push_back(&*MIB); 4279 return true; 4280} 4281 4282// VisualStudio defines setjmp as _setjmp 4283#if defined(_MSC_VER) && defined(setjmp) && \ 4284 !defined(setjmp_undefined_for_msvc) 4285# pragma push_macro("setjmp") 4286# undef setjmp 4287# define setjmp_undefined_for_msvc 4288#endif 4289 4290/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 4291/// we want to emit this as a call to a named external function, return the name 4292/// otherwise lower it and return null. 4293const char * 4294SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 4295 DebugLoc dl = getCurDebugLoc(); 4296 SDValue Res; 4297 4298 switch (Intrinsic) { 4299 default: 4300 // By default, turn this into a target intrinsic node. 4301 visitTargetIntrinsic(I, Intrinsic); 4302 return 0; 4303 case Intrinsic::vastart: visitVAStart(I); return 0; 4304 case Intrinsic::vaend: visitVAEnd(I); return 0; 4305 case Intrinsic::vacopy: visitVACopy(I); return 0; 4306 case Intrinsic::returnaddress: 4307 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(), 4308 getValue(I.getArgOperand(0)))); 4309 return 0; 4310 case Intrinsic::frameaddress: 4311 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(), 4312 getValue(I.getArgOperand(0)))); 4313 return 0; 4314 case Intrinsic::setjmp: 4315 return "_setjmp"+!TLI.usesUnderscoreSetJmp(); 4316 case Intrinsic::longjmp: 4317 return "_longjmp"+!TLI.usesUnderscoreLongJmp(); 4318 case Intrinsic::memcpy: { 4319 // Assert for address < 256 since we support only user defined address 4320 // spaces. 4321 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4322 < 256 && 4323 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace() 4324 < 256 && 4325 "Unknown address space"); 4326 SDValue Op1 = getValue(I.getArgOperand(0)); 4327 SDValue Op2 = getValue(I.getArgOperand(1)); 4328 SDValue Op3 = getValue(I.getArgOperand(2)); 4329 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4330 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4331 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false, 4332 MachinePointerInfo(I.getArgOperand(0)), 4333 MachinePointerInfo(I.getArgOperand(1)))); 4334 return 0; 4335 } 4336 case Intrinsic::memset: { 4337 // Assert for address < 256 since we support only user defined address 4338 // spaces. 4339 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4340 < 256 && 4341 "Unknown address space"); 4342 SDValue Op1 = getValue(I.getArgOperand(0)); 4343 SDValue Op2 = getValue(I.getArgOperand(1)); 4344 SDValue Op3 = getValue(I.getArgOperand(2)); 4345 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4346 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4347 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol, 4348 MachinePointerInfo(I.getArgOperand(0)))); 4349 return 0; 4350 } 4351 case Intrinsic::memmove: { 4352 // Assert for address < 256 since we support only user defined address 4353 // spaces. 4354 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4355 < 256 && 4356 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace() 4357 < 256 && 4358 "Unknown address space"); 4359 SDValue Op1 = getValue(I.getArgOperand(0)); 4360 SDValue Op2 = getValue(I.getArgOperand(1)); 4361 SDValue Op3 = getValue(I.getArgOperand(2)); 4362 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4363 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4364 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol, 4365 MachinePointerInfo(I.getArgOperand(0)), 4366 MachinePointerInfo(I.getArgOperand(1)))); 4367 return 0; 4368 } 4369 case Intrinsic::dbg_declare: { 4370 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 4371 MDNode *Variable = DI.getVariable(); 4372 const Value *Address = DI.getAddress(); 4373 if (!Address || !DIVariable(DI.getVariable()).Verify()) 4374 return 0; 4375 4376 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder 4377 // but do not always have a corresponding SDNode built. The SDNodeOrder 4378 // absolute, but not relative, values are different depending on whether 4379 // debug info exists. 4380 ++SDNodeOrder; 4381 4382 // Check if address has undef value. 4383 if (isa<UndefValue>(Address) || 4384 (Address->use_empty() && !isa<Argument>(Address))) { 4385 DEBUG(dbgs() << "Dropping debug info for " << DI); 4386 return 0; 4387 } 4388 4389 SDValue &N = NodeMap[Address]; 4390 if (!N.getNode() && isa<Argument>(Address)) 4391 // Check unused arguments map. 4392 N = UnusedArgNodeMap[Address]; 4393 SDDbgValue *SDV; 4394 if (N.getNode()) { 4395 // Parameters are handled specially. 4396 bool isParameter = 4397 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable; 4398 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 4399 Address = BCI->getOperand(0); 4400 const AllocaInst *AI = dyn_cast<AllocaInst>(Address); 4401 4402 if (isParameter && !AI) { 4403 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 4404 if (FINode) 4405 // Byval parameter. We have a frame index at this point. 4406 SDV = DAG.getDbgValue(Variable, FINode->getIndex(), 4407 0, dl, SDNodeOrder); 4408 else { 4409 // Address is an argument, so try to emit its dbg value using 4410 // virtual register info from the FuncInfo.ValueMap. 4411 EmitFuncArgumentDbgValue(Address, Variable, 0, N); 4412 return 0; 4413 } 4414 } else if (AI) 4415 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(), 4416 0, dl, SDNodeOrder); 4417 else { 4418 // Can't do anything with other non-AI cases yet. 4419 DEBUG(dbgs() << "Dropping debug info for " << DI); 4420 return 0; 4421 } 4422 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 4423 } else { 4424 // If Address is an argument then try to emit its dbg value using 4425 // virtual register info from the FuncInfo.ValueMap. 4426 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) { 4427 // If variable is pinned by a alloca in dominating bb then 4428 // use StaticAllocaMap. 4429 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) { 4430 if (AI->getParent() != DI.getParent()) { 4431 DenseMap<const AllocaInst*, int>::iterator SI = 4432 FuncInfo.StaticAllocaMap.find(AI); 4433 if (SI != FuncInfo.StaticAllocaMap.end()) { 4434 SDV = DAG.getDbgValue(Variable, SI->second, 4435 0, dl, SDNodeOrder); 4436 DAG.AddDbgValue(SDV, 0, false); 4437 return 0; 4438 } 4439 } 4440 } 4441 DEBUG(dbgs() << "Dropping debug info for " << DI); 4442 } 4443 } 4444 return 0; 4445 } 4446 case Intrinsic::dbg_value: { 4447 const DbgValueInst &DI = cast<DbgValueInst>(I); 4448 if (!DIVariable(DI.getVariable()).Verify()) 4449 return 0; 4450 4451 MDNode *Variable = DI.getVariable(); 4452 uint64_t Offset = DI.getOffset(); 4453 const Value *V = DI.getValue(); 4454 if (!V) 4455 return 0; 4456 4457 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder 4458 // but do not always have a corresponding SDNode built. The SDNodeOrder 4459 // absolute, but not relative, values are different depending on whether 4460 // debug info exists. 4461 ++SDNodeOrder; 4462 SDDbgValue *SDV; 4463 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) { 4464 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder); 4465 DAG.AddDbgValue(SDV, 0, false); 4466 } else { 4467 // Do not use getValue() in here; we don't want to generate code at 4468 // this point if it hasn't been done yet. 4469 SDValue N = NodeMap[V]; 4470 if (!N.getNode() && isa<Argument>(V)) 4471 // Check unused arguments map. 4472 N = UnusedArgNodeMap[V]; 4473 if (N.getNode()) { 4474 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) { 4475 SDV = DAG.getDbgValue(Variable, N.getNode(), 4476 N.getResNo(), Offset, dl, SDNodeOrder); 4477 DAG.AddDbgValue(SDV, N.getNode(), false); 4478 } 4479 } else if (!V->use_empty() ) { 4480 // Do not call getValue(V) yet, as we don't want to generate code. 4481 // Remember it for later. 4482 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder); 4483 DanglingDebugInfoMap[V] = DDI; 4484 } else { 4485 // We may expand this to cover more cases. One case where we have no 4486 // data available is an unreferenced parameter. 4487 DEBUG(dbgs() << "Dropping debug info for " << DI); 4488 } 4489 } 4490 4491 // Build a debug info table entry. 4492 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 4493 V = BCI->getOperand(0); 4494 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 4495 // Don't handle byval struct arguments or VLAs, for example. 4496 if (!AI) 4497 return 0; 4498 DenseMap<const AllocaInst*, int>::iterator SI = 4499 FuncInfo.StaticAllocaMap.find(AI); 4500 if (SI == FuncInfo.StaticAllocaMap.end()) 4501 return 0; // VLAs. 4502 int FI = SI->second; 4503 4504 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4505 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo()) 4506 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc()); 4507 return 0; 4508 } 4509 case Intrinsic::eh_exception: { 4510 // Insert the EXCEPTIONADDR instruction. 4511 assert(FuncInfo.MBB->isLandingPad() && 4512 "Call to eh.exception not in landing pad!"); 4513 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 4514 SDValue Ops[1]; 4515 Ops[0] = DAG.getRoot(); 4516 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1); 4517 setValue(&I, Op); 4518 DAG.setRoot(Op.getValue(1)); 4519 return 0; 4520 } 4521 4522 case Intrinsic::eh_selector: { 4523 MachineBasicBlock *CallMBB = FuncInfo.MBB; 4524 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4525 if (CallMBB->isLandingPad()) 4526 AddCatchInfo(I, &MMI, CallMBB); 4527 else { 4528#ifndef NDEBUG 4529 FuncInfo.CatchInfoLost.insert(&I); 4530#endif 4531 // FIXME: Mark exception selector register as live in. Hack for PR1508. 4532 unsigned Reg = TLI.getExceptionSelectorRegister(); 4533 if (Reg) FuncInfo.MBB->addLiveIn(Reg); 4534 } 4535 4536 // Insert the EHSELECTION instruction. 4537 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 4538 SDValue Ops[2]; 4539 Ops[0] = getValue(I.getArgOperand(0)); 4540 Ops[1] = getRoot(); 4541 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2); 4542 DAG.setRoot(Op.getValue(1)); 4543 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32)); 4544 return 0; 4545 } 4546 4547 case Intrinsic::eh_typeid_for: { 4548 // Find the type id for the given typeinfo. 4549 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0)); 4550 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV); 4551 Res = DAG.getConstant(TypeID, MVT::i32); 4552 setValue(&I, Res); 4553 return 0; 4554 } 4555 4556 case Intrinsic::eh_return_i32: 4557 case Intrinsic::eh_return_i64: 4558 DAG.getMachineFunction().getMMI().setCallsEHReturn(true); 4559 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl, 4560 MVT::Other, 4561 getControlRoot(), 4562 getValue(I.getArgOperand(0)), 4563 getValue(I.getArgOperand(1)))); 4564 return 0; 4565 case Intrinsic::eh_unwind_init: 4566 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true); 4567 return 0; 4568 case Intrinsic::eh_dwarf_cfa: { 4569 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl, 4570 TLI.getPointerTy()); 4571 SDValue Offset = DAG.getNode(ISD::ADD, dl, 4572 TLI.getPointerTy(), 4573 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl, 4574 TLI.getPointerTy()), 4575 CfaArg); 4576 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl, 4577 TLI.getPointerTy(), 4578 DAG.getConstant(0, TLI.getPointerTy())); 4579 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 4580 FA, Offset)); 4581 return 0; 4582 } 4583 case Intrinsic::eh_sjlj_callsite: { 4584 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4585 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 4586 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 4587 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 4588 4589 MMI.setCurrentCallSite(CI->getZExtValue()); 4590 return 0; 4591 } 4592 case Intrinsic::eh_sjlj_setjmp: { 4593 setValue(&I, DAG.getNode(ISD::EH_SJLJ_SETJMP, dl, MVT::i32, getRoot(), 4594 getValue(I.getArgOperand(0)))); 4595 return 0; 4596 } 4597 case Intrinsic::eh_sjlj_longjmp: { 4598 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other, 4599 getRoot(), getValue(I.getArgOperand(0)))); 4600 return 0; 4601 } 4602 case Intrinsic::eh_sjlj_dispatch_setup: { 4603 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other, 4604 getRoot(), getValue(I.getArgOperand(0)))); 4605 return 0; 4606 } 4607 4608 case Intrinsic::x86_mmx_pslli_w: 4609 case Intrinsic::x86_mmx_pslli_d: 4610 case Intrinsic::x86_mmx_pslli_q: 4611 case Intrinsic::x86_mmx_psrli_w: 4612 case Intrinsic::x86_mmx_psrli_d: 4613 case Intrinsic::x86_mmx_psrli_q: 4614 case Intrinsic::x86_mmx_psrai_w: 4615 case Intrinsic::x86_mmx_psrai_d: { 4616 SDValue ShAmt = getValue(I.getArgOperand(1)); 4617 if (isa<ConstantSDNode>(ShAmt)) { 4618 visitTargetIntrinsic(I, Intrinsic); 4619 return 0; 4620 } 4621 unsigned NewIntrinsic = 0; 4622 EVT ShAmtVT = MVT::v2i32; 4623 switch (Intrinsic) { 4624 case Intrinsic::x86_mmx_pslli_w: 4625 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 4626 break; 4627 case Intrinsic::x86_mmx_pslli_d: 4628 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 4629 break; 4630 case Intrinsic::x86_mmx_pslli_q: 4631 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 4632 break; 4633 case Intrinsic::x86_mmx_psrli_w: 4634 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 4635 break; 4636 case Intrinsic::x86_mmx_psrli_d: 4637 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 4638 break; 4639 case Intrinsic::x86_mmx_psrli_q: 4640 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 4641 break; 4642 case Intrinsic::x86_mmx_psrai_w: 4643 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 4644 break; 4645 case Intrinsic::x86_mmx_psrai_d: 4646 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 4647 break; 4648 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4649 } 4650 4651 // The vector shift intrinsics with scalars uses 32b shift amounts but 4652 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 4653 // to be zero. 4654 // We must do this early because v2i32 is not a legal type. 4655 DebugLoc dl = getCurDebugLoc(); 4656 SDValue ShOps[2]; 4657 ShOps[0] = ShAmt; 4658 ShOps[1] = DAG.getConstant(0, MVT::i32); 4659 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2); 4660 EVT DestVT = TLI.getValueType(I.getType()); 4661 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt); 4662 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 4663 DAG.getConstant(NewIntrinsic, MVT::i32), 4664 getValue(I.getArgOperand(0)), ShAmt); 4665 setValue(&I, Res); 4666 return 0; 4667 } 4668 case Intrinsic::convertff: 4669 case Intrinsic::convertfsi: 4670 case Intrinsic::convertfui: 4671 case Intrinsic::convertsif: 4672 case Intrinsic::convertuif: 4673 case Intrinsic::convertss: 4674 case Intrinsic::convertsu: 4675 case Intrinsic::convertus: 4676 case Intrinsic::convertuu: { 4677 ISD::CvtCode Code = ISD::CVT_INVALID; 4678 switch (Intrinsic) { 4679 case Intrinsic::convertff: Code = ISD::CVT_FF; break; 4680 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break; 4681 case Intrinsic::convertfui: Code = ISD::CVT_FU; break; 4682 case Intrinsic::convertsif: Code = ISD::CVT_SF; break; 4683 case Intrinsic::convertuif: Code = ISD::CVT_UF; break; 4684 case Intrinsic::convertss: Code = ISD::CVT_SS; break; 4685 case Intrinsic::convertsu: Code = ISD::CVT_SU; break; 4686 case Intrinsic::convertus: Code = ISD::CVT_US; break; 4687 case Intrinsic::convertuu: Code = ISD::CVT_UU; break; 4688 } 4689 EVT DestVT = TLI.getValueType(I.getType()); 4690 const Value *Op1 = I.getArgOperand(0); 4691 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1), 4692 DAG.getValueType(DestVT), 4693 DAG.getValueType(getValue(Op1).getValueType()), 4694 getValue(I.getArgOperand(1)), 4695 getValue(I.getArgOperand(2)), 4696 Code); 4697 setValue(&I, Res); 4698 return 0; 4699 } 4700 case Intrinsic::sqrt: 4701 setValue(&I, DAG.getNode(ISD::FSQRT, dl, 4702 getValue(I.getArgOperand(0)).getValueType(), 4703 getValue(I.getArgOperand(0)))); 4704 return 0; 4705 case Intrinsic::powi: 4706 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)), 4707 getValue(I.getArgOperand(1)), DAG)); 4708 return 0; 4709 case Intrinsic::sin: 4710 setValue(&I, DAG.getNode(ISD::FSIN, dl, 4711 getValue(I.getArgOperand(0)).getValueType(), 4712 getValue(I.getArgOperand(0)))); 4713 return 0; 4714 case Intrinsic::cos: 4715 setValue(&I, DAG.getNode(ISD::FCOS, dl, 4716 getValue(I.getArgOperand(0)).getValueType(), 4717 getValue(I.getArgOperand(0)))); 4718 return 0; 4719 case Intrinsic::log: 4720 visitLog(I); 4721 return 0; 4722 case Intrinsic::log2: 4723 visitLog2(I); 4724 return 0; 4725 case Intrinsic::log10: 4726 visitLog10(I); 4727 return 0; 4728 case Intrinsic::exp: 4729 visitExp(I); 4730 return 0; 4731 case Intrinsic::exp2: 4732 visitExp2(I); 4733 return 0; 4734 case Intrinsic::pow: 4735 visitPow(I); 4736 return 0; 4737 case Intrinsic::fma: 4738 setValue(&I, DAG.getNode(ISD::FMA, dl, 4739 getValue(I.getArgOperand(0)).getValueType(), 4740 getValue(I.getArgOperand(0)), 4741 getValue(I.getArgOperand(1)), 4742 getValue(I.getArgOperand(2)))); 4743 return 0; 4744 case Intrinsic::convert_to_fp16: 4745 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl, 4746 MVT::i16, getValue(I.getArgOperand(0)))); 4747 return 0; 4748 case Intrinsic::convert_from_fp16: 4749 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl, 4750 MVT::f32, getValue(I.getArgOperand(0)))); 4751 return 0; 4752 case Intrinsic::pcmarker: { 4753 SDValue Tmp = getValue(I.getArgOperand(0)); 4754 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp)); 4755 return 0; 4756 } 4757 case Intrinsic::readcyclecounter: { 4758 SDValue Op = getRoot(); 4759 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl, 4760 DAG.getVTList(MVT::i64, MVT::Other), 4761 &Op, 1); 4762 setValue(&I, Res); 4763 DAG.setRoot(Res.getValue(1)); 4764 return 0; 4765 } 4766 case Intrinsic::bswap: 4767 setValue(&I, DAG.getNode(ISD::BSWAP, dl, 4768 getValue(I.getArgOperand(0)).getValueType(), 4769 getValue(I.getArgOperand(0)))); 4770 return 0; 4771 case Intrinsic::cttz: { 4772 SDValue Arg = getValue(I.getArgOperand(0)); 4773 EVT Ty = Arg.getValueType(); 4774 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg)); 4775 return 0; 4776 } 4777 case Intrinsic::ctlz: { 4778 SDValue Arg = getValue(I.getArgOperand(0)); 4779 EVT Ty = Arg.getValueType(); 4780 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg)); 4781 return 0; 4782 } 4783 case Intrinsic::ctpop: { 4784 SDValue Arg = getValue(I.getArgOperand(0)); 4785 EVT Ty = Arg.getValueType(); 4786 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg)); 4787 return 0; 4788 } 4789 case Intrinsic::stacksave: { 4790 SDValue Op = getRoot(); 4791 Res = DAG.getNode(ISD::STACKSAVE, dl, 4792 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1); 4793 setValue(&I, Res); 4794 DAG.setRoot(Res.getValue(1)); 4795 return 0; 4796 } 4797 case Intrinsic::stackrestore: { 4798 Res = getValue(I.getArgOperand(0)); 4799 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res)); 4800 return 0; 4801 } 4802 case Intrinsic::stackprotector: { 4803 // Emit code into the DAG to store the stack guard onto the stack. 4804 MachineFunction &MF = DAG.getMachineFunction(); 4805 MachineFrameInfo *MFI = MF.getFrameInfo(); 4806 EVT PtrTy = TLI.getPointerTy(); 4807 4808 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value. 4809 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 4810 4811 int FI = FuncInfo.StaticAllocaMap[Slot]; 4812 MFI->setStackProtectorIndex(FI); 4813 4814 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 4815 4816 // Store the stack protector onto the stack. 4817 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN, 4818 MachinePointerInfo::getFixedStack(FI), 4819 true, false, 0); 4820 setValue(&I, Res); 4821 DAG.setRoot(Res); 4822 return 0; 4823 } 4824 case Intrinsic::objectsize: { 4825 // If we don't know by now, we're never going to know. 4826 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 4827 4828 assert(CI && "Non-constant type in __builtin_object_size?"); 4829 4830 SDValue Arg = getValue(I.getCalledValue()); 4831 EVT Ty = Arg.getValueType(); 4832 4833 if (CI->isZero()) 4834 Res = DAG.getConstant(-1ULL, Ty); 4835 else 4836 Res = DAG.getConstant(0, Ty); 4837 4838 setValue(&I, Res); 4839 return 0; 4840 } 4841 case Intrinsic::var_annotation: 4842 // Discard annotate attributes 4843 return 0; 4844 4845 case Intrinsic::init_trampoline: { 4846 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 4847 4848 SDValue Ops[6]; 4849 Ops[0] = getRoot(); 4850 Ops[1] = getValue(I.getArgOperand(0)); 4851 Ops[2] = getValue(I.getArgOperand(1)); 4852 Ops[3] = getValue(I.getArgOperand(2)); 4853 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 4854 Ops[5] = DAG.getSrcValue(F); 4855 4856 Res = DAG.getNode(ISD::TRAMPOLINE, dl, 4857 DAG.getVTList(TLI.getPointerTy(), MVT::Other), 4858 Ops, 6); 4859 4860 setValue(&I, Res); 4861 DAG.setRoot(Res.getValue(1)); 4862 return 0; 4863 } 4864 case Intrinsic::gcroot: 4865 if (GFI) { 4866 const Value *Alloca = I.getArgOperand(0); 4867 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 4868 4869 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 4870 GFI->addStackRoot(FI->getIndex(), TypeMap); 4871 } 4872 return 0; 4873 case Intrinsic::gcread: 4874 case Intrinsic::gcwrite: 4875 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 4876 return 0; 4877 case Intrinsic::flt_rounds: 4878 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32)); 4879 return 0; 4880 4881 case Intrinsic::expect: { 4882 // Just replace __builtin_expect(exp, c) with EXP. 4883 setValue(&I, getValue(I.getArgOperand(0))); 4884 return 0; 4885 } 4886 4887 case Intrinsic::trap: { 4888 StringRef TrapFuncName = getTrapFunctionName(); 4889 if (TrapFuncName.empty()) { 4890 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot())); 4891 return 0; 4892 } 4893 TargetLowering::ArgListTy Args; 4894 std::pair<SDValue, SDValue> Result = 4895 TLI.LowerCallTo(getRoot(), I.getType(), 4896 false, false, false, false, 0, CallingConv::C, 4897 /*isTailCall=*/false, /*isReturnValueUsed=*/true, 4898 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()), 4899 Args, DAG, getCurDebugLoc()); 4900 DAG.setRoot(Result.second); 4901 return 0; 4902 } 4903 case Intrinsic::uadd_with_overflow: 4904 return implVisitAluOverflow(I, ISD::UADDO); 4905 case Intrinsic::sadd_with_overflow: 4906 return implVisitAluOverflow(I, ISD::SADDO); 4907 case Intrinsic::usub_with_overflow: 4908 return implVisitAluOverflow(I, ISD::USUBO); 4909 case Intrinsic::ssub_with_overflow: 4910 return implVisitAluOverflow(I, ISD::SSUBO); 4911 case Intrinsic::umul_with_overflow: 4912 return implVisitAluOverflow(I, ISD::UMULO); 4913 case Intrinsic::smul_with_overflow: 4914 return implVisitAluOverflow(I, ISD::SMULO); 4915 4916 case Intrinsic::prefetch: { 4917 SDValue Ops[5]; 4918 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4919 Ops[0] = getRoot(); 4920 Ops[1] = getValue(I.getArgOperand(0)); 4921 Ops[2] = getValue(I.getArgOperand(1)); 4922 Ops[3] = getValue(I.getArgOperand(2)); 4923 Ops[4] = getValue(I.getArgOperand(3)); 4924 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl, 4925 DAG.getVTList(MVT::Other), 4926 &Ops[0], 5, 4927 EVT::getIntegerVT(*Context, 8), 4928 MachinePointerInfo(I.getArgOperand(0)), 4929 0, /* align */ 4930 false, /* volatile */ 4931 rw==0, /* read */ 4932 rw==1)); /* write */ 4933 return 0; 4934 } 4935 case Intrinsic::memory_barrier: { 4936 SDValue Ops[6]; 4937 Ops[0] = getRoot(); 4938 for (int x = 1; x < 6; ++x) 4939 Ops[x] = getValue(I.getArgOperand(x - 1)); 4940 4941 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6)); 4942 return 0; 4943 } 4944 case Intrinsic::atomic_cmp_swap: { 4945 SDValue Root = getRoot(); 4946 SDValue L = 4947 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(), 4948 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(), 4949 Root, 4950 getValue(I.getArgOperand(0)), 4951 getValue(I.getArgOperand(1)), 4952 getValue(I.getArgOperand(2)), 4953 MachinePointerInfo(I.getArgOperand(0)), 0 /* Alignment */, 4954 Monotonic, CrossThread); 4955 setValue(&I, L); 4956 DAG.setRoot(L.getValue(1)); 4957 return 0; 4958 } 4959 case Intrinsic::atomic_load_add: 4960 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD); 4961 case Intrinsic::atomic_load_sub: 4962 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB); 4963 case Intrinsic::atomic_load_or: 4964 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR); 4965 case Intrinsic::atomic_load_xor: 4966 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR); 4967 case Intrinsic::atomic_load_and: 4968 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND); 4969 case Intrinsic::atomic_load_nand: 4970 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND); 4971 case Intrinsic::atomic_load_max: 4972 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX); 4973 case Intrinsic::atomic_load_min: 4974 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN); 4975 case Intrinsic::atomic_load_umin: 4976 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN); 4977 case Intrinsic::atomic_load_umax: 4978 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX); 4979 case Intrinsic::atomic_swap: 4980 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP); 4981 4982 case Intrinsic::invariant_start: 4983 case Intrinsic::lifetime_start: 4984 // Discard region information. 4985 setValue(&I, DAG.getUNDEF(TLI.getPointerTy())); 4986 return 0; 4987 case Intrinsic::invariant_end: 4988 case Intrinsic::lifetime_end: 4989 // Discard region information. 4990 return 0; 4991 } 4992} 4993 4994void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 4995 bool isTailCall, 4996 MachineBasicBlock *LandingPad) { 4997 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 4998 FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 4999 Type *RetTy = FTy->getReturnType(); 5000 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5001 MCSymbol *BeginLabel = 0; 5002 5003 TargetLowering::ArgListTy Args; 5004 TargetLowering::ArgListEntry Entry; 5005 Args.reserve(CS.arg_size()); 5006 5007 // Check whether the function can return without sret-demotion. 5008 SmallVector<ISD::OutputArg, 4> Outs; 5009 SmallVector<uint64_t, 4> Offsets; 5010 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(), 5011 Outs, TLI, &Offsets); 5012 5013 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(), 5014 DAG.getMachineFunction(), 5015 FTy->isVarArg(), Outs, 5016 FTy->getContext()); 5017 5018 SDValue DemoteStackSlot; 5019 int DemoteStackIdx = -100; 5020 5021 if (!CanLowerReturn) { 5022 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize( 5023 FTy->getReturnType()); 5024 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment( 5025 FTy->getReturnType()); 5026 MachineFunction &MF = DAG.getMachineFunction(); 5027 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 5028 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType()); 5029 5030 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy()); 5031 Entry.Node = DemoteStackSlot; 5032 Entry.Ty = StackSlotPtrType; 5033 Entry.isSExt = false; 5034 Entry.isZExt = false; 5035 Entry.isInReg = false; 5036 Entry.isSRet = true; 5037 Entry.isNest = false; 5038 Entry.isByVal = false; 5039 Entry.Alignment = Align; 5040 Args.push_back(Entry); 5041 RetTy = Type::getVoidTy(FTy->getContext()); 5042 } 5043 5044 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 5045 i != e; ++i) { 5046 const Value *V = *i; 5047 5048 // Skip empty types 5049 if (V->getType()->isEmptyTy()) 5050 continue; 5051 5052 SDValue ArgNode = getValue(V); 5053 Entry.Node = ArgNode; Entry.Ty = V->getType(); 5054 5055 unsigned attrInd = i - CS.arg_begin() + 1; 5056 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt); 5057 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt); 5058 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg); 5059 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet); 5060 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest); 5061 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal); 5062 Entry.Alignment = CS.getParamAlignment(attrInd); 5063 Args.push_back(Entry); 5064 } 5065 5066 if (LandingPad) { 5067 // Insert a label before the invoke call to mark the try range. This can be 5068 // used to detect deletion of the invoke via the MachineModuleInfo. 5069 BeginLabel = MMI.getContext().CreateTempSymbol(); 5070 5071 // For SjLj, keep track of which landing pads go with which invokes 5072 // so as to maintain the ordering of pads in the LSDA. 5073 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 5074 if (CallSiteIndex) { 5075 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 5076 // Now that the call site is handled, stop tracking it. 5077 MMI.setCurrentCallSite(0); 5078 } 5079 5080 // Both PendingLoads and PendingExports must be flushed here; 5081 // this call might not return. 5082 (void)getRoot(); 5083 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel)); 5084 } 5085 5086 // Check if target-independent constraints permit a tail call here. 5087 // Target-dependent constraints are checked within TLI.LowerCallTo. 5088 if (isTailCall && 5089 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI)) 5090 isTailCall = false; 5091 5092 // If there's a possibility that fast-isel has already selected some amount 5093 // of the current basic block, don't emit a tail call. 5094 if (isTailCall && EnableFastISel) 5095 isTailCall = false; 5096 5097 std::pair<SDValue,SDValue> Result = 5098 TLI.LowerCallTo(getRoot(), RetTy, 5099 CS.paramHasAttr(0, Attribute::SExt), 5100 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(), 5101 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(), 5102 CS.getCallingConv(), 5103 isTailCall, 5104 !CS.getInstruction()->use_empty(), 5105 Callee, Args, DAG, getCurDebugLoc()); 5106 assert((isTailCall || Result.second.getNode()) && 5107 "Non-null chain expected with non-tail call!"); 5108 assert((Result.second.getNode() || !Result.first.getNode()) && 5109 "Null value expected with tail call!"); 5110 if (Result.first.getNode()) { 5111 setValue(CS.getInstruction(), Result.first); 5112 } else if (!CanLowerReturn && Result.second.getNode()) { 5113 // The instruction result is the result of loading from the 5114 // hidden sret parameter. 5115 SmallVector<EVT, 1> PVTs; 5116 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType()); 5117 5118 ComputeValueVTs(TLI, PtrRetTy, PVTs); 5119 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 5120 EVT PtrVT = PVTs[0]; 5121 unsigned NumValues = Outs.size(); 5122 SmallVector<SDValue, 4> Values(NumValues); 5123 SmallVector<SDValue, 4> Chains(NumValues); 5124 5125 for (unsigned i = 0; i < NumValues; ++i) { 5126 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, 5127 DemoteStackSlot, 5128 DAG.getConstant(Offsets[i], PtrVT)); 5129 SDValue L = DAG.getLoad(Outs[i].VT, getCurDebugLoc(), Result.second, 5130 Add, 5131 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), 5132 false, false, 1); 5133 Values[i] = L; 5134 Chains[i] = L.getValue(1); 5135 } 5136 5137 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 5138 MVT::Other, &Chains[0], NumValues); 5139 PendingLoads.push_back(Chain); 5140 5141 // Collect the legal value parts into potentially illegal values 5142 // that correspond to the original function's return values. 5143 SmallVector<EVT, 4> RetTys; 5144 RetTy = FTy->getReturnType(); 5145 ComputeValueVTs(TLI, RetTy, RetTys); 5146 ISD::NodeType AssertOp = ISD::DELETED_NODE; 5147 SmallVector<SDValue, 4> ReturnValues; 5148 unsigned CurReg = 0; 5149 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 5150 EVT VT = RetTys[I]; 5151 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT); 5152 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT); 5153 5154 SDValue ReturnValue = 5155 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs, 5156 RegisterVT, VT, AssertOp); 5157 ReturnValues.push_back(ReturnValue); 5158 CurReg += NumRegs; 5159 } 5160 5161 setValue(CS.getInstruction(), 5162 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 5163 DAG.getVTList(&RetTys[0], RetTys.size()), 5164 &ReturnValues[0], ReturnValues.size())); 5165 } 5166 5167 // Assign order to nodes here. If the call does not produce a result, it won't 5168 // be mapped to a SDNode and visit() will not assign it an order number. 5169 if (!Result.second.getNode()) { 5170 // As a special case, a null chain means that a tail call has been emitted and 5171 // the DAG root is already updated. 5172 HasTailCall = true; 5173 ++SDNodeOrder; 5174 AssignOrderingToNode(DAG.getRoot().getNode()); 5175 } else { 5176 DAG.setRoot(Result.second); 5177 ++SDNodeOrder; 5178 AssignOrderingToNode(Result.second.getNode()); 5179 } 5180 5181 if (LandingPad) { 5182 // Insert a label at the end of the invoke call to mark the try range. This 5183 // can be used to detect deletion of the invoke via the MachineModuleInfo. 5184 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol(); 5185 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel)); 5186 5187 // Inform MachineModuleInfo of range. 5188 MMI.addInvoke(LandingPad, BeginLabel, EndLabel); 5189 } 5190} 5191 5192/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 5193/// value is equal or not-equal to zero. 5194static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) { 5195 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); 5196 UI != E; ++UI) { 5197 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI)) 5198 if (IC->isEquality()) 5199 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 5200 if (C->isNullValue()) 5201 continue; 5202 // Unknown instruction. 5203 return false; 5204 } 5205 return true; 5206} 5207 5208static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 5209 Type *LoadTy, 5210 SelectionDAGBuilder &Builder) { 5211 5212 // Check to see if this load can be trivially constant folded, e.g. if the 5213 // input is from a string literal. 5214 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 5215 // Cast pointer to the type we really want to load. 5216 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 5217 PointerType::getUnqual(LoadTy)); 5218 5219 if (const Constant *LoadCst = 5220 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 5221 Builder.TD)) 5222 return Builder.getValue(LoadCst); 5223 } 5224 5225 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 5226 // still constant memory, the input chain can be the entry node. 5227 SDValue Root; 5228 bool ConstantMemory = false; 5229 5230 // Do not serialize (non-volatile) loads of constant memory with anything. 5231 if (Builder.AA->pointsToConstantMemory(PtrVal)) { 5232 Root = Builder.DAG.getEntryNode(); 5233 ConstantMemory = true; 5234 } else { 5235 // Do not serialize non-volatile loads against each other. 5236 Root = Builder.DAG.getRoot(); 5237 } 5238 5239 SDValue Ptr = Builder.getValue(PtrVal); 5240 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root, 5241 Ptr, MachinePointerInfo(PtrVal), 5242 false /*volatile*/, 5243 false /*nontemporal*/, 1 /* align=1 */); 5244 5245 if (!ConstantMemory) 5246 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 5247 return LoadVal; 5248} 5249 5250 5251/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form. 5252/// If so, return true and lower it, otherwise return false and it will be 5253/// lowered like a normal call. 5254bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 5255 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t) 5256 if (I.getNumArgOperands() != 3) 5257 return false; 5258 5259 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 5260 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() || 5261 !I.getArgOperand(2)->getType()->isIntegerTy() || 5262 !I.getType()->isIntegerTy()) 5263 return false; 5264 5265 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2)); 5266 5267 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 5268 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 5269 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) { 5270 bool ActuallyDoIt = true; 5271 MVT LoadVT; 5272 Type *LoadTy; 5273 switch (Size->getZExtValue()) { 5274 default: 5275 LoadVT = MVT::Other; 5276 LoadTy = 0; 5277 ActuallyDoIt = false; 5278 break; 5279 case 2: 5280 LoadVT = MVT::i16; 5281 LoadTy = Type::getInt16Ty(Size->getContext()); 5282 break; 5283 case 4: 5284 LoadVT = MVT::i32; 5285 LoadTy = Type::getInt32Ty(Size->getContext()); 5286 break; 5287 case 8: 5288 LoadVT = MVT::i64; 5289 LoadTy = Type::getInt64Ty(Size->getContext()); 5290 break; 5291 /* 5292 case 16: 5293 LoadVT = MVT::v4i32; 5294 LoadTy = Type::getInt32Ty(Size->getContext()); 5295 LoadTy = VectorType::get(LoadTy, 4); 5296 break; 5297 */ 5298 } 5299 5300 // This turns into unaligned loads. We only do this if the target natively 5301 // supports the MVT we'll be loading or if it is small enough (<= 4) that 5302 // we'll only produce a small number of byte loads. 5303 5304 // Require that we can find a legal MVT, and only do this if the target 5305 // supports unaligned loads of that type. Expanding into byte loads would 5306 // bloat the code. 5307 if (ActuallyDoIt && Size->getZExtValue() > 4) { 5308 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 5309 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 5310 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT)) 5311 ActuallyDoIt = false; 5312 } 5313 5314 if (ActuallyDoIt) { 5315 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this); 5316 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this); 5317 5318 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal, 5319 ISD::SETNE); 5320 EVT CallVT = TLI.getValueType(I.getType(), true); 5321 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT)); 5322 return true; 5323 } 5324 } 5325 5326 5327 return false; 5328} 5329 5330 5331void SelectionDAGBuilder::visitCall(const CallInst &I) { 5332 // Handle inline assembly differently. 5333 if (isa<InlineAsm>(I.getCalledValue())) { 5334 visitInlineAsm(&I); 5335 return; 5336 } 5337 5338 // See if any floating point values are being passed to this function. This is 5339 // used to emit an undefined reference to fltused on Windows. 5340 FunctionType *FT = 5341 cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0)); 5342 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5343 if (FT->isVarArg() && 5344 !MMI.callsExternalVAFunctionWithFloatingPointArguments()) { 5345 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 5346 Type* T = I.getArgOperand(i)->getType(); 5347 for (po_iterator<Type*> i = po_begin(T), e = po_end(T); 5348 i != e; ++i) { 5349 if (!i->isFloatingPointTy()) continue; 5350 MMI.setCallsExternalVAFunctionWithFloatingPointArguments(true); 5351 break; 5352 } 5353 } 5354 } 5355 5356 const char *RenameFn = 0; 5357 if (Function *F = I.getCalledFunction()) { 5358 if (F->isDeclaration()) { 5359 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) { 5360 if (unsigned IID = II->getIntrinsicID(F)) { 5361 RenameFn = visitIntrinsicCall(I, IID); 5362 if (!RenameFn) 5363 return; 5364 } 5365 } 5366 if (unsigned IID = F->getIntrinsicID()) { 5367 RenameFn = visitIntrinsicCall(I, IID); 5368 if (!RenameFn) 5369 return; 5370 } 5371 } 5372 5373 // Check for well-known libc/libm calls. If the function is internal, it 5374 // can't be a library call. 5375 if (!F->hasLocalLinkage() && F->hasName()) { 5376 StringRef Name = F->getName(); 5377 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") { 5378 if (I.getNumArgOperands() == 2 && // Basic sanity checks. 5379 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5380 I.getType() == I.getArgOperand(0)->getType() && 5381 I.getType() == I.getArgOperand(1)->getType()) { 5382 SDValue LHS = getValue(I.getArgOperand(0)); 5383 SDValue RHS = getValue(I.getArgOperand(1)); 5384 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(), 5385 LHS.getValueType(), LHS, RHS)); 5386 return; 5387 } 5388 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") { 5389 if (I.getNumArgOperands() == 1 && // Basic sanity checks. 5390 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5391 I.getType() == I.getArgOperand(0)->getType()) { 5392 SDValue Tmp = getValue(I.getArgOperand(0)); 5393 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(), 5394 Tmp.getValueType(), Tmp)); 5395 return; 5396 } 5397 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") { 5398 if (I.getNumArgOperands() == 1 && // Basic sanity checks. 5399 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5400 I.getType() == I.getArgOperand(0)->getType() && 5401 I.onlyReadsMemory()) { 5402 SDValue Tmp = getValue(I.getArgOperand(0)); 5403 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(), 5404 Tmp.getValueType(), Tmp)); 5405 return; 5406 } 5407 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") { 5408 if (I.getNumArgOperands() == 1 && // Basic sanity checks. 5409 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5410 I.getType() == I.getArgOperand(0)->getType() && 5411 I.onlyReadsMemory()) { 5412 SDValue Tmp = getValue(I.getArgOperand(0)); 5413 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(), 5414 Tmp.getValueType(), Tmp)); 5415 return; 5416 } 5417 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") { 5418 if (I.getNumArgOperands() == 1 && // Basic sanity checks. 5419 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5420 I.getType() == I.getArgOperand(0)->getType() && 5421 I.onlyReadsMemory()) { 5422 SDValue Tmp = getValue(I.getArgOperand(0)); 5423 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(), 5424 Tmp.getValueType(), Tmp)); 5425 return; 5426 } 5427 } else if (Name == "memcmp") { 5428 if (visitMemCmpCall(I)) 5429 return; 5430 } 5431 } 5432 } 5433 5434 SDValue Callee; 5435 if (!RenameFn) 5436 Callee = getValue(I.getCalledValue()); 5437 else 5438 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy()); 5439 5440 // Check if we can potentially perform a tail call. More detailed checking is 5441 // be done within LowerCallTo, after more information about the call is known. 5442 LowerCallTo(&I, Callee, I.isTailCall()); 5443} 5444 5445namespace { 5446 5447/// AsmOperandInfo - This contains information for each constraint that we are 5448/// lowering. 5449class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 5450public: 5451 /// CallOperand - If this is the result output operand or a clobber 5452 /// this is null, otherwise it is the incoming operand to the CallInst. 5453 /// This gets modified as the asm is processed. 5454 SDValue CallOperand; 5455 5456 /// AssignedRegs - If this is a register or register class operand, this 5457 /// contains the set of register corresponding to the operand. 5458 RegsForValue AssignedRegs; 5459 5460 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 5461 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) { 5462 } 5463 5464 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers 5465 /// busy in OutputRegs/InputRegs. 5466 void MarkAllocatedRegs(bool isOutReg, bool isInReg, 5467 std::set<unsigned> &OutputRegs, 5468 std::set<unsigned> &InputRegs, 5469 const TargetRegisterInfo &TRI) const { 5470 if (isOutReg) { 5471 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 5472 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI); 5473 } 5474 if (isInReg) { 5475 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 5476 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI); 5477 } 5478 } 5479 5480 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 5481 /// corresponds to. If there is no Value* for this operand, it returns 5482 /// MVT::Other. 5483 EVT getCallOperandValEVT(LLVMContext &Context, 5484 const TargetLowering &TLI, 5485 const TargetData *TD) const { 5486 if (CallOperandVal == 0) return MVT::Other; 5487 5488 if (isa<BasicBlock>(CallOperandVal)) 5489 return TLI.getPointerTy(); 5490 5491 llvm::Type *OpTy = CallOperandVal->getType(); 5492 5493 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 5494 // If this is an indirect operand, the operand is a pointer to the 5495 // accessed type. 5496 if (isIndirect) { 5497 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 5498 if (!PtrTy) 5499 report_fatal_error("Indirect operand for inline asm not a pointer!"); 5500 OpTy = PtrTy->getElementType(); 5501 } 5502 5503 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5504 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5505 if (STy->getNumElements() == 1) 5506 OpTy = STy->getElementType(0); 5507 5508 // If OpTy is not a single value, it may be a struct/union that we 5509 // can tile with integers. 5510 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5511 unsigned BitSize = TD->getTypeSizeInBits(OpTy); 5512 switch (BitSize) { 5513 default: break; 5514 case 1: 5515 case 8: 5516 case 16: 5517 case 32: 5518 case 64: 5519 case 128: 5520 OpTy = IntegerType::get(Context, BitSize); 5521 break; 5522 } 5523 } 5524 5525 return TLI.getValueType(OpTy, true); 5526 } 5527 5528private: 5529 /// MarkRegAndAliases - Mark the specified register and all aliases in the 5530 /// specified set. 5531 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs, 5532 const TargetRegisterInfo &TRI) { 5533 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg"); 5534 Regs.insert(Reg); 5535 if (const unsigned *Aliases = TRI.getAliasSet(Reg)) 5536 for (; *Aliases; ++Aliases) 5537 Regs.insert(*Aliases); 5538 } 5539}; 5540 5541typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector; 5542 5543} // end anonymous namespace 5544 5545/// GetRegistersForValue - Assign registers (virtual or physical) for the 5546/// specified operand. We prefer to assign virtual registers, to allow the 5547/// register allocator to handle the assignment process. However, if the asm 5548/// uses features that we can't model on machineinstrs, we have SDISel do the 5549/// allocation. This produces generally horrible, but correct, code. 5550/// 5551/// OpInfo describes the operand. 5552/// Input and OutputRegs are the set of already allocated physical registers. 5553/// 5554static void GetRegistersForValue(SelectionDAG &DAG, 5555 const TargetLowering &TLI, 5556 DebugLoc DL, 5557 SDISelAsmOperandInfo &OpInfo, 5558 std::set<unsigned> &OutputRegs, 5559 std::set<unsigned> &InputRegs) { 5560 LLVMContext &Context = *DAG.getContext(); 5561 5562 // Compute whether this value requires an input register, an output register, 5563 // or both. 5564 bool isOutReg = false; 5565 bool isInReg = false; 5566 switch (OpInfo.Type) { 5567 case InlineAsm::isOutput: 5568 isOutReg = true; 5569 5570 // If there is an input constraint that matches this, we need to reserve 5571 // the input register so no other inputs allocate to it. 5572 isInReg = OpInfo.hasMatchingInput(); 5573 break; 5574 case InlineAsm::isInput: 5575 isInReg = true; 5576 isOutReg = false; 5577 break; 5578 case InlineAsm::isClobber: 5579 isOutReg = true; 5580 isInReg = true; 5581 break; 5582 } 5583 5584 5585 MachineFunction &MF = DAG.getMachineFunction(); 5586 SmallVector<unsigned, 4> Regs; 5587 5588 // If this is a constraint for a single physreg, or a constraint for a 5589 // register class, find it. 5590 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 5591 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 5592 OpInfo.ConstraintVT); 5593 5594 unsigned NumRegs = 1; 5595 if (OpInfo.ConstraintVT != MVT::Other) { 5596 // If this is a FP input in an integer register (or visa versa) insert a bit 5597 // cast of the input value. More generally, handle any case where the input 5598 // value disagrees with the register class we plan to stick this in. 5599 if (OpInfo.Type == InlineAsm::isInput && 5600 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) { 5601 // Try to convert to the first EVT that the reg class contains. If the 5602 // types are identical size, use a bitcast to convert (e.g. two differing 5603 // vector types). 5604 EVT RegVT = *PhysReg.second->vt_begin(); 5605 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 5606 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 5607 RegVT, OpInfo.CallOperand); 5608 OpInfo.ConstraintVT = RegVT; 5609 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 5610 // If the input is a FP value and we want it in FP registers, do a 5611 // bitcast to the corresponding integer type. This turns an f64 value 5612 // into i64, which can be passed with two i32 values on a 32-bit 5613 // machine. 5614 RegVT = EVT::getIntegerVT(Context, 5615 OpInfo.ConstraintVT.getSizeInBits()); 5616 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 5617 RegVT, OpInfo.CallOperand); 5618 OpInfo.ConstraintVT = RegVT; 5619 } 5620 } 5621 5622 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 5623 } 5624 5625 EVT RegVT; 5626 EVT ValueVT = OpInfo.ConstraintVT; 5627 5628 // If this is a constraint for a specific physical register, like {r17}, 5629 // assign it now. 5630 if (unsigned AssignedReg = PhysReg.first) { 5631 const TargetRegisterClass *RC = PhysReg.second; 5632 if (OpInfo.ConstraintVT == MVT::Other) 5633 ValueVT = *RC->vt_begin(); 5634 5635 // Get the actual register value type. This is important, because the user 5636 // may have asked for (e.g.) the AX register in i32 type. We need to 5637 // remember that AX is actually i16 to get the right extension. 5638 RegVT = *RC->vt_begin(); 5639 5640 // This is a explicit reference to a physical register. 5641 Regs.push_back(AssignedReg); 5642 5643 // If this is an expanded reference, add the rest of the regs to Regs. 5644 if (NumRegs != 1) { 5645 TargetRegisterClass::iterator I = RC->begin(); 5646 for (; *I != AssignedReg; ++I) 5647 assert(I != RC->end() && "Didn't find reg!"); 5648 5649 // Already added the first reg. 5650 --NumRegs; ++I; 5651 for (; NumRegs; --NumRegs, ++I) { 5652 assert(I != RC->end() && "Ran out of registers to allocate!"); 5653 Regs.push_back(*I); 5654 } 5655 } 5656 5657 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 5658 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 5659 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 5660 return; 5661 } 5662 5663 // Otherwise, if this was a reference to an LLVM register class, create vregs 5664 // for this reference. 5665 if (const TargetRegisterClass *RC = PhysReg.second) { 5666 RegVT = *RC->vt_begin(); 5667 if (OpInfo.ConstraintVT == MVT::Other) 5668 ValueVT = RegVT; 5669 5670 // Create the appropriate number of virtual registers. 5671 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5672 for (; NumRegs; --NumRegs) 5673 Regs.push_back(RegInfo.createVirtualRegister(RC)); 5674 5675 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 5676 return; 5677 } 5678 5679 // Otherwise, we couldn't allocate enough registers for this. 5680} 5681 5682/// visitInlineAsm - Handle a call to an InlineAsm object. 5683/// 5684void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 5685 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 5686 5687 /// ConstraintOperands - Information about all of the constraints. 5688 SDISelAsmOperandInfoVector ConstraintOperands; 5689 5690 std::set<unsigned> OutputRegs, InputRegs; 5691 5692 TargetLowering::AsmOperandInfoVector 5693 TargetConstraints = TLI.ParseConstraints(CS); 5694 5695 bool hasMemory = false; 5696 5697 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5698 unsigned ResNo = 0; // ResNo - The result number of the next output. 5699 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 5700 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 5701 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 5702 5703 EVT OpVT = MVT::Other; 5704 5705 // Compute the value type for each operand. 5706 switch (OpInfo.Type) { 5707 case InlineAsm::isOutput: 5708 // Indirect outputs just consume an argument. 5709 if (OpInfo.isIndirect) { 5710 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 5711 break; 5712 } 5713 5714 // The return value of the call is this value. As such, there is no 5715 // corresponding argument. 5716 assert(!CS.getType()->isVoidTy() && 5717 "Bad inline asm!"); 5718 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 5719 OpVT = TLI.getValueType(STy->getElementType(ResNo)); 5720 } else { 5721 assert(ResNo == 0 && "Asm only has one result!"); 5722 OpVT = TLI.getValueType(CS.getType()); 5723 } 5724 ++ResNo; 5725 break; 5726 case InlineAsm::isInput: 5727 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 5728 break; 5729 case InlineAsm::isClobber: 5730 // Nothing to do. 5731 break; 5732 } 5733 5734 // If this is an input or an indirect output, process the call argument. 5735 // BasicBlocks are labels, currently appearing only in asm's. 5736 if (OpInfo.CallOperandVal) { 5737 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 5738 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 5739 } else { 5740 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 5741 } 5742 5743 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD); 5744 } 5745 5746 OpInfo.ConstraintVT = OpVT; 5747 5748 // Indirect operand accesses access memory. 5749 if (OpInfo.isIndirect) 5750 hasMemory = true; 5751 else { 5752 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) { 5753 TargetLowering::ConstraintType 5754 CType = TLI.getConstraintType(OpInfo.Codes[j]); 5755 if (CType == TargetLowering::C_Memory) { 5756 hasMemory = true; 5757 break; 5758 } 5759 } 5760 } 5761 } 5762 5763 SDValue Chain, Flag; 5764 5765 // We won't need to flush pending loads if this asm doesn't touch 5766 // memory and is nonvolatile. 5767 if (hasMemory || IA->hasSideEffects()) 5768 Chain = getRoot(); 5769 else 5770 Chain = DAG.getRoot(); 5771 5772 // Second pass over the constraints: compute which constraint option to use 5773 // and assign registers to constraints that want a specific physreg. 5774 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5775 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5776 5777 // If this is an output operand with a matching input operand, look up the 5778 // matching input. If their types mismatch, e.g. one is an integer, the 5779 // other is floating point, or their sizes are different, flag it as an 5780 // error. 5781 if (OpInfo.hasMatchingInput()) { 5782 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5783 5784 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5785 std::pair<unsigned, const TargetRegisterClass*> MatchRC = 5786 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, OpInfo.ConstraintVT); 5787 std::pair<unsigned, const TargetRegisterClass*> InputRC = 5788 TLI.getRegForInlineAsmConstraint(Input.ConstraintCode, Input.ConstraintVT); 5789 if ((OpInfo.ConstraintVT.isInteger() != 5790 Input.ConstraintVT.isInteger()) || 5791 (MatchRC.second != InputRC.second)) { 5792 report_fatal_error("Unsupported asm: input constraint" 5793 " with a matching output constraint of" 5794 " incompatible type!"); 5795 } 5796 Input.ConstraintVT = OpInfo.ConstraintVT; 5797 } 5798 } 5799 5800 // Compute the constraint code and ConstraintType to use. 5801 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 5802 5803 // If this is a memory input, and if the operand is not indirect, do what we 5804 // need to to provide an address for the memory input. 5805 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 5806 !OpInfo.isIndirect) { 5807 assert((OpInfo.isMultipleAlternative || 5808 (OpInfo.Type == InlineAsm::isInput)) && 5809 "Can only indirectify direct input operands!"); 5810 5811 // Memory operands really want the address of the value. If we don't have 5812 // an indirect input, put it in the constpool if we can, otherwise spill 5813 // it to a stack slot. 5814 // TODO: This isn't quite right. We need to handle these according to 5815 // the addressing mode that the constraint wants. Also, this may take 5816 // an additional register for the computation and we don't want that 5817 // either. 5818 5819 // If the operand is a float, integer, or vector constant, spill to a 5820 // constant pool entry to get its address. 5821 const Value *OpVal = OpInfo.CallOperandVal; 5822 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 5823 isa<ConstantVector>(OpVal)) { 5824 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal), 5825 TLI.getPointerTy()); 5826 } else { 5827 // Otherwise, create a stack slot and emit a store to it before the 5828 // asm. 5829 Type *Ty = OpVal->getType(); 5830 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); 5831 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty); 5832 MachineFunction &MF = DAG.getMachineFunction(); 5833 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 5834 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy()); 5835 Chain = DAG.getStore(Chain, getCurDebugLoc(), 5836 OpInfo.CallOperand, StackSlot, 5837 MachinePointerInfo::getFixedStack(SSFI), 5838 false, false, 0); 5839 OpInfo.CallOperand = StackSlot; 5840 } 5841 5842 // There is no longer a Value* corresponding to this operand. 5843 OpInfo.CallOperandVal = 0; 5844 5845 // It is now an indirect operand. 5846 OpInfo.isIndirect = true; 5847 } 5848 5849 // If this constraint is for a specific register, allocate it before 5850 // anything else. 5851 if (OpInfo.ConstraintType == TargetLowering::C_Register) 5852 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs, 5853 InputRegs); 5854 } 5855 5856 // Second pass - Loop over all of the operands, assigning virtual or physregs 5857 // to register class operands. 5858 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5859 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5860 5861 // C_Register operands have already been allocated, Other/Memory don't need 5862 // to be. 5863 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 5864 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs, 5865 InputRegs); 5866 } 5867 5868 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 5869 std::vector<SDValue> AsmNodeOperands; 5870 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 5871 AsmNodeOperands.push_back( 5872 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), 5873 TLI.getPointerTy())); 5874 5875 // If we have a !srcloc metadata node associated with it, we want to attach 5876 // this to the ultimately generated inline asm machineinstr. To do this, we 5877 // pass in the third operand as this (potentially null) inline asm MDNode. 5878 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 5879 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 5880 5881 // Remember the HasSideEffect and AlignStack bits as operand 3. 5882 unsigned ExtraInfo = 0; 5883 if (IA->hasSideEffects()) 5884 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 5885 if (IA->isAlignStack()) 5886 ExtraInfo |= InlineAsm::Extra_IsAlignStack; 5887 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo, 5888 TLI.getPointerTy())); 5889 5890 // Loop over all of the inputs, copying the operand values into the 5891 // appropriate registers and processing the output regs. 5892 RegsForValue RetValRegs; 5893 5894 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 5895 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 5896 5897 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5898 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5899 5900 switch (OpInfo.Type) { 5901 case InlineAsm::isOutput: { 5902 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 5903 OpInfo.ConstraintType != TargetLowering::C_Register) { 5904 // Memory output, or 'other' output (e.g. 'X' constraint). 5905 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 5906 5907 // Add information to the INLINEASM node to know about this output. 5908 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 5909 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, 5910 TLI.getPointerTy())); 5911 AsmNodeOperands.push_back(OpInfo.CallOperand); 5912 break; 5913 } 5914 5915 // Otherwise, this is a register or register class output. 5916 5917 // Copy the output from the appropriate register. Find a register that 5918 // we can use. 5919 if (OpInfo.AssignedRegs.Regs.empty()) 5920 report_fatal_error("Couldn't allocate output reg for constraint '" + 5921 Twine(OpInfo.ConstraintCode) + "'!"); 5922 5923 // If this is an indirect operand, store through the pointer after the 5924 // asm. 5925 if (OpInfo.isIndirect) { 5926 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 5927 OpInfo.CallOperandVal)); 5928 } else { 5929 // This is the result value of the call. 5930 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 5931 // Concatenate this output onto the outputs list. 5932 RetValRegs.append(OpInfo.AssignedRegs); 5933 } 5934 5935 // Add information to the INLINEASM node to know that this register is 5936 // set. 5937 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ? 5938 InlineAsm::Kind_RegDefEarlyClobber : 5939 InlineAsm::Kind_RegDef, 5940 false, 5941 0, 5942 DAG, 5943 AsmNodeOperands); 5944 break; 5945 } 5946 case InlineAsm::isInput: { 5947 SDValue InOperandVal = OpInfo.CallOperand; 5948 5949 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint? 5950 // If this is required to match an output register we have already set, 5951 // just use its register. 5952 unsigned OperandNo = OpInfo.getMatchedOperand(); 5953 5954 // Scan until we find the definition we already emitted of this operand. 5955 // When we find it, create a RegsForValue operand. 5956 unsigned CurOp = InlineAsm::Op_FirstOperand; 5957 for (; OperandNo; --OperandNo) { 5958 // Advance to the next operand. 5959 unsigned OpFlag = 5960 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 5961 assert((InlineAsm::isRegDefKind(OpFlag) || 5962 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 5963 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"); 5964 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1; 5965 } 5966 5967 unsigned OpFlag = 5968 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 5969 if (InlineAsm::isRegDefKind(OpFlag) || 5970 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 5971 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 5972 if (OpInfo.isIndirect) { 5973 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 5974 LLVMContext &Ctx = *DAG.getContext(); 5975 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:" 5976 " don't know how to handle tied " 5977 "indirect register inputs"); 5978 } 5979 5980 RegsForValue MatchedRegs; 5981 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType()); 5982 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType(); 5983 MatchedRegs.RegVTs.push_back(RegVT); 5984 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 5985 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag); 5986 i != e; ++i) 5987 MatchedRegs.Regs.push_back 5988 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT))); 5989 5990 // Use the produced MatchedRegs object to 5991 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), 5992 Chain, &Flag); 5993 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 5994 true, OpInfo.getMatchedOperand(), 5995 DAG, AsmNodeOperands); 5996 break; 5997 } 5998 5999 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 6000 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 6001 "Unexpected number of operands"); 6002 // Add information to the INLINEASM node to know about this input. 6003 // See InlineAsm.h isUseOperandTiedToDef. 6004 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 6005 OpInfo.getMatchedOperand()); 6006 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag, 6007 TLI.getPointerTy())); 6008 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 6009 break; 6010 } 6011 6012 // Treat indirect 'X' constraint as memory. 6013 if (OpInfo.ConstraintType == TargetLowering::C_Other && 6014 OpInfo.isIndirect) 6015 OpInfo.ConstraintType = TargetLowering::C_Memory; 6016 6017 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 6018 std::vector<SDValue> Ops; 6019 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 6020 Ops, DAG); 6021 if (Ops.empty()) 6022 report_fatal_error("Invalid operand for inline asm constraint '" + 6023 Twine(OpInfo.ConstraintCode) + "'!"); 6024 6025 // Add information to the INLINEASM node to know about this input. 6026 unsigned ResOpType = 6027 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 6028 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 6029 TLI.getPointerTy())); 6030 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 6031 break; 6032 } 6033 6034 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 6035 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 6036 assert(InOperandVal.getValueType() == TLI.getPointerTy() && 6037 "Memory operands expect pointer values"); 6038 6039 // Add information to the INLINEASM node to know about this input. 6040 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 6041 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 6042 TLI.getPointerTy())); 6043 AsmNodeOperands.push_back(InOperandVal); 6044 break; 6045 } 6046 6047 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 6048 OpInfo.ConstraintType == TargetLowering::C_Register) && 6049 "Unknown constraint type!"); 6050 assert(!OpInfo.isIndirect && 6051 "Don't know how to handle indirect register inputs yet!"); 6052 6053 // Copy the input into the appropriate registers. 6054 if (OpInfo.AssignedRegs.Regs.empty()) 6055 report_fatal_error("Couldn't allocate input reg for constraint '" + 6056 Twine(OpInfo.ConstraintCode) + "'!"); 6057 6058 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), 6059 Chain, &Flag); 6060 6061 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 6062 DAG, AsmNodeOperands); 6063 break; 6064 } 6065 case InlineAsm::isClobber: { 6066 // Add the clobbered value to the operand list, so that the register 6067 // allocator is aware that the physreg got clobbered. 6068 if (!OpInfo.AssignedRegs.Regs.empty()) 6069 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 6070 false, 0, DAG, 6071 AsmNodeOperands); 6072 break; 6073 } 6074 } 6075 } 6076 6077 // Finish up input operands. Set the input chain and add the flag last. 6078 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 6079 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 6080 6081 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(), 6082 DAG.getVTList(MVT::Other, MVT::Glue), 6083 &AsmNodeOperands[0], AsmNodeOperands.size()); 6084 Flag = Chain.getValue(1); 6085 6086 // If this asm returns a register value, copy the result from that register 6087 // and set it as the value of the call. 6088 if (!RetValRegs.Regs.empty()) { 6089 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), 6090 Chain, &Flag); 6091 6092 // FIXME: Why don't we do this for inline asms with MRVs? 6093 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 6094 EVT ResultType = TLI.getValueType(CS.getType()); 6095 6096 // If any of the results of the inline asm is a vector, it may have the 6097 // wrong width/num elts. This can happen for register classes that can 6098 // contain multiple different value types. The preg or vreg allocated may 6099 // not have the same VT as was expected. Convert it to the right type 6100 // with bit_convert. 6101 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 6102 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), 6103 ResultType, Val); 6104 6105 } else if (ResultType != Val.getValueType() && 6106 ResultType.isInteger() && Val.getValueType().isInteger()) { 6107 // If a result value was tied to an input value, the computed result may 6108 // have a wider width than the expected result. Extract the relevant 6109 // portion. 6110 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val); 6111 } 6112 6113 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 6114 } 6115 6116 setValue(CS.getInstruction(), Val); 6117 // Don't need to use this as a chain in this case. 6118 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 6119 return; 6120 } 6121 6122 std::vector<std::pair<SDValue, const Value *> > StoresToEmit; 6123 6124 // Process indirect outputs, first output all of the flagged copies out of 6125 // physregs. 6126 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 6127 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 6128 const Value *Ptr = IndirectStoresToEmit[i].second; 6129 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), 6130 Chain, &Flag); 6131 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 6132 } 6133 6134 // Emit the non-flagged stores from the physregs. 6135 SmallVector<SDValue, 8> OutChains; 6136 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 6137 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(), 6138 StoresToEmit[i].first, 6139 getValue(StoresToEmit[i].second), 6140 MachinePointerInfo(StoresToEmit[i].second), 6141 false, false, 0); 6142 OutChains.push_back(Val); 6143 } 6144 6145 if (!OutChains.empty()) 6146 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 6147 &OutChains[0], OutChains.size()); 6148 6149 DAG.setRoot(Chain); 6150} 6151 6152void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 6153 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(), 6154 MVT::Other, getRoot(), 6155 getValue(I.getArgOperand(0)), 6156 DAG.getSrcValue(I.getArgOperand(0)))); 6157} 6158 6159void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 6160 const TargetData &TD = *TLI.getTargetData(); 6161 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(), 6162 getRoot(), getValue(I.getOperand(0)), 6163 DAG.getSrcValue(I.getOperand(0)), 6164 TD.getABITypeAlignment(I.getType())); 6165 setValue(&I, V); 6166 DAG.setRoot(V.getValue(1)); 6167} 6168 6169void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 6170 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(), 6171 MVT::Other, getRoot(), 6172 getValue(I.getArgOperand(0)), 6173 DAG.getSrcValue(I.getArgOperand(0)))); 6174} 6175 6176void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 6177 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(), 6178 MVT::Other, getRoot(), 6179 getValue(I.getArgOperand(0)), 6180 getValue(I.getArgOperand(1)), 6181 DAG.getSrcValue(I.getArgOperand(0)), 6182 DAG.getSrcValue(I.getArgOperand(1)))); 6183} 6184 6185/// TargetLowering::LowerCallTo - This is the default LowerCallTo 6186/// implementation, which just calls LowerCall. 6187/// FIXME: When all targets are 6188/// migrated to using LowerCall, this hook should be integrated into SDISel. 6189std::pair<SDValue, SDValue> 6190TargetLowering::LowerCallTo(SDValue Chain, Type *RetTy, 6191 bool RetSExt, bool RetZExt, bool isVarArg, 6192 bool isInreg, unsigned NumFixedArgs, 6193 CallingConv::ID CallConv, bool isTailCall, 6194 bool isReturnValueUsed, 6195 SDValue Callee, 6196 ArgListTy &Args, SelectionDAG &DAG, 6197 DebugLoc dl) const { 6198 // Handle all of the outgoing arguments. 6199 SmallVector<ISD::OutputArg, 32> Outs; 6200 SmallVector<SDValue, 32> OutVals; 6201 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 6202 SmallVector<EVT, 4> ValueVTs; 6203 ComputeValueVTs(*this, Args[i].Ty, ValueVTs); 6204 for (unsigned Value = 0, NumValues = ValueVTs.size(); 6205 Value != NumValues; ++Value) { 6206 EVT VT = ValueVTs[Value]; 6207 Type *ArgTy = VT.getTypeForEVT(RetTy->getContext()); 6208 SDValue Op = SDValue(Args[i].Node.getNode(), 6209 Args[i].Node.getResNo() + Value); 6210 ISD::ArgFlagsTy Flags; 6211 unsigned OriginalAlignment = 6212 getTargetData()->getABITypeAlignment(ArgTy); 6213 6214 if (Args[i].isZExt) 6215 Flags.setZExt(); 6216 if (Args[i].isSExt) 6217 Flags.setSExt(); 6218 if (Args[i].isInReg) 6219 Flags.setInReg(); 6220 if (Args[i].isSRet) 6221 Flags.setSRet(); 6222 if (Args[i].isByVal) { 6223 Flags.setByVal(); 6224 PointerType *Ty = cast<PointerType>(Args[i].Ty); 6225 Type *ElementTy = Ty->getElementType(); 6226 Flags.setByValSize(getTargetData()->getTypeAllocSize(ElementTy)); 6227 // For ByVal, alignment should come from FE. BE will guess if this 6228 // info is not there but there are cases it cannot get right. 6229 unsigned FrameAlign; 6230 if (Args[i].Alignment) 6231 FrameAlign = Args[i].Alignment; 6232 else 6233 FrameAlign = getByValTypeAlignment(ElementTy); 6234 Flags.setByValAlign(FrameAlign); 6235 } 6236 if (Args[i].isNest) 6237 Flags.setNest(); 6238 Flags.setOrigAlign(OriginalAlignment); 6239 6240 EVT PartVT = getRegisterType(RetTy->getContext(), VT); 6241 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT); 6242 SmallVector<SDValue, 4> Parts(NumParts); 6243 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 6244 6245 if (Args[i].isSExt) 6246 ExtendKind = ISD::SIGN_EXTEND; 6247 else if (Args[i].isZExt) 6248 ExtendKind = ISD::ZERO_EXTEND; 6249 6250 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, 6251 PartVT, ExtendKind); 6252 6253 for (unsigned j = 0; j != NumParts; ++j) { 6254 // if it isn't first piece, alignment must be 1 6255 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), 6256 i < NumFixedArgs); 6257 if (NumParts > 1 && j == 0) 6258 MyFlags.Flags.setSplit(); 6259 else if (j != 0) 6260 MyFlags.Flags.setOrigAlign(1); 6261 6262 Outs.push_back(MyFlags); 6263 OutVals.push_back(Parts[j]); 6264 } 6265 } 6266 } 6267 6268 // Handle the incoming return values from the call. 6269 SmallVector<ISD::InputArg, 32> Ins; 6270 SmallVector<EVT, 4> RetTys; 6271 ComputeValueVTs(*this, RetTy, RetTys); 6272 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 6273 EVT VT = RetTys[I]; 6274 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT); 6275 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT); 6276 for (unsigned i = 0; i != NumRegs; ++i) { 6277 ISD::InputArg MyFlags; 6278 MyFlags.VT = RegisterVT.getSimpleVT(); 6279 MyFlags.Used = isReturnValueUsed; 6280 if (RetSExt) 6281 MyFlags.Flags.setSExt(); 6282 if (RetZExt) 6283 MyFlags.Flags.setZExt(); 6284 if (isInreg) 6285 MyFlags.Flags.setInReg(); 6286 Ins.push_back(MyFlags); 6287 } 6288 } 6289 6290 SmallVector<SDValue, 4> InVals; 6291 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall, 6292 Outs, OutVals, Ins, dl, DAG, InVals); 6293 6294 // Verify that the target's LowerCall behaved as expected. 6295 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 6296 "LowerCall didn't return a valid chain!"); 6297 assert((!isTailCall || InVals.empty()) && 6298 "LowerCall emitted a return value for a tail call!"); 6299 assert((isTailCall || InVals.size() == Ins.size()) && 6300 "LowerCall didn't emit the correct number of values!"); 6301 6302 // For a tail call, the return value is merely live-out and there aren't 6303 // any nodes in the DAG representing it. Return a special value to 6304 // indicate that a tail call has been emitted and no more Instructions 6305 // should be processed in the current block. 6306 if (isTailCall) { 6307 DAG.setRoot(Chain); 6308 return std::make_pair(SDValue(), SDValue()); 6309 } 6310 6311 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 6312 assert(InVals[i].getNode() && 6313 "LowerCall emitted a null value!"); 6314 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 6315 "LowerCall emitted a value with the wrong type!"); 6316 }); 6317 6318 // Collect the legal value parts into potentially illegal values 6319 // that correspond to the original function's return values. 6320 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6321 if (RetSExt) 6322 AssertOp = ISD::AssertSext; 6323 else if (RetZExt) 6324 AssertOp = ISD::AssertZext; 6325 SmallVector<SDValue, 4> ReturnValues; 6326 unsigned CurReg = 0; 6327 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 6328 EVT VT = RetTys[I]; 6329 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT); 6330 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT); 6331 6332 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg], 6333 NumRegs, RegisterVT, VT, 6334 AssertOp)); 6335 CurReg += NumRegs; 6336 } 6337 6338 // For a function returning void, there is no return value. We can't create 6339 // such a node, so we just return a null return value in that case. In 6340 // that case, nothing will actually look at the value. 6341 if (ReturnValues.empty()) 6342 return std::make_pair(SDValue(), Chain); 6343 6344 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 6345 DAG.getVTList(&RetTys[0], RetTys.size()), 6346 &ReturnValues[0], ReturnValues.size()); 6347 return std::make_pair(Res, Chain); 6348} 6349 6350void TargetLowering::LowerOperationWrapper(SDNode *N, 6351 SmallVectorImpl<SDValue> &Results, 6352 SelectionDAG &DAG) const { 6353 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 6354 if (Res.getNode()) 6355 Results.push_back(Res); 6356} 6357 6358SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6359 llvm_unreachable("LowerOperation not implemented for this target!"); 6360 return SDValue(); 6361} 6362 6363void 6364SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 6365 SDValue Op = getNonRegisterValue(V); 6366 assert((Op.getOpcode() != ISD::CopyFromReg || 6367 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 6368 "Copy from a reg to the same reg!"); 6369 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 6370 6371 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType()); 6372 SDValue Chain = DAG.getEntryNode(); 6373 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0); 6374 PendingExports.push_back(Chain); 6375} 6376 6377#include "llvm/CodeGen/SelectionDAGISel.h" 6378 6379/// isOnlyUsedInEntryBlock - If the specified argument is only used in the 6380/// entry block, return true. This includes arguments used by switches, since 6381/// the switch may expand into multiple basic blocks. 6382static bool isOnlyUsedInEntryBlock(const Argument *A) { 6383 // With FastISel active, we may be splitting blocks, so force creation 6384 // of virtual registers for all non-dead arguments. 6385 if (EnableFastISel) 6386 return A->use_empty(); 6387 6388 const BasicBlock *Entry = A->getParent()->begin(); 6389 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end(); 6390 UI != E; ++UI) { 6391 const User *U = *UI; 6392 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U)) 6393 return false; // Use not in entry block. 6394 } 6395 return true; 6396} 6397 6398void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) { 6399 // If this is the entry block, emit arguments. 6400 const Function &F = *LLVMBB->getParent(); 6401 SelectionDAG &DAG = SDB->DAG; 6402 DebugLoc dl = SDB->getCurDebugLoc(); 6403 const TargetData *TD = TLI.getTargetData(); 6404 SmallVector<ISD::InputArg, 16> Ins; 6405 6406 // Check whether the function can return without sret-demotion. 6407 SmallVector<ISD::OutputArg, 4> Outs; 6408 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(), 6409 Outs, TLI); 6410 6411 if (!FuncInfo->CanLowerReturn) { 6412 // Put in an sret pointer parameter before all the other parameters. 6413 SmallVector<EVT, 1> ValueVTs; 6414 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 6415 6416 // NOTE: Assuming that a pointer will never break down to more than one VT 6417 // or one register. 6418 ISD::ArgFlagsTy Flags; 6419 Flags.setSRet(); 6420 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]); 6421 ISD::InputArg RetArg(Flags, RegisterVT, true); 6422 Ins.push_back(RetArg); 6423 } 6424 6425 // Set up the incoming argument description vector. 6426 unsigned Idx = 1; 6427 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); 6428 I != E; ++I, ++Idx) { 6429 SmallVector<EVT, 4> ValueVTs; 6430 ComputeValueVTs(TLI, I->getType(), ValueVTs); 6431 bool isArgValueUsed = !I->use_empty(); 6432 for (unsigned Value = 0, NumValues = ValueVTs.size(); 6433 Value != NumValues; ++Value) { 6434 EVT VT = ValueVTs[Value]; 6435 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 6436 ISD::ArgFlagsTy Flags; 6437 unsigned OriginalAlignment = 6438 TD->getABITypeAlignment(ArgTy); 6439 6440 if (F.paramHasAttr(Idx, Attribute::ZExt)) 6441 Flags.setZExt(); 6442 if (F.paramHasAttr(Idx, Attribute::SExt)) 6443 Flags.setSExt(); 6444 if (F.paramHasAttr(Idx, Attribute::InReg)) 6445 Flags.setInReg(); 6446 if (F.paramHasAttr(Idx, Attribute::StructRet)) 6447 Flags.setSRet(); 6448 if (F.paramHasAttr(Idx, Attribute::ByVal)) { 6449 Flags.setByVal(); 6450 PointerType *Ty = cast<PointerType>(I->getType()); 6451 Type *ElementTy = Ty->getElementType(); 6452 Flags.setByValSize(TD->getTypeAllocSize(ElementTy)); 6453 // For ByVal, alignment should be passed from FE. BE will guess if 6454 // this info is not there but there are cases it cannot get right. 6455 unsigned FrameAlign; 6456 if (F.getParamAlignment(Idx)) 6457 FrameAlign = F.getParamAlignment(Idx); 6458 else 6459 FrameAlign = TLI.getByValTypeAlignment(ElementTy); 6460 Flags.setByValAlign(FrameAlign); 6461 } 6462 if (F.paramHasAttr(Idx, Attribute::Nest)) 6463 Flags.setNest(); 6464 Flags.setOrigAlign(OriginalAlignment); 6465 6466 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6467 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT); 6468 for (unsigned i = 0; i != NumRegs; ++i) { 6469 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed); 6470 if (NumRegs > 1 && i == 0) 6471 MyFlags.Flags.setSplit(); 6472 // if it isn't first piece, alignment must be 1 6473 else if (i > 0) 6474 MyFlags.Flags.setOrigAlign(1); 6475 Ins.push_back(MyFlags); 6476 } 6477 } 6478 } 6479 6480 // Call the target to set up the argument values. 6481 SmallVector<SDValue, 8> InVals; 6482 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(), 6483 F.isVarArg(), Ins, 6484 dl, DAG, InVals); 6485 6486 // Verify that the target's LowerFormalArguments behaved as expected. 6487 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 6488 "LowerFormalArguments didn't return a valid chain!"); 6489 assert(InVals.size() == Ins.size() && 6490 "LowerFormalArguments didn't emit the correct number of values!"); 6491 DEBUG({ 6492 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 6493 assert(InVals[i].getNode() && 6494 "LowerFormalArguments emitted a null value!"); 6495 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 6496 "LowerFormalArguments emitted a value with the wrong type!"); 6497 } 6498 }); 6499 6500 // Update the DAG with the new chain value resulting from argument lowering. 6501 DAG.setRoot(NewRoot); 6502 6503 // Set up the argument values. 6504 unsigned i = 0; 6505 Idx = 1; 6506 if (!FuncInfo->CanLowerReturn) { 6507 // Create a virtual register for the sret pointer, and put in a copy 6508 // from the sret argument into it. 6509 SmallVector<EVT, 1> ValueVTs; 6510 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 6511 EVT VT = ValueVTs[0]; 6512 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6513 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6514 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 6515 RegVT, VT, AssertOp); 6516 6517 MachineFunction& MF = SDB->DAG.getMachineFunction(); 6518 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 6519 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)); 6520 FuncInfo->DemoteRegister = SRetReg; 6521 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), 6522 SRetReg, ArgValue); 6523 DAG.setRoot(NewRoot); 6524 6525 // i indexes lowered arguments. Bump it past the hidden sret argument. 6526 // Idx indexes LLVM arguments. Don't touch it. 6527 ++i; 6528 } 6529 6530 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 6531 ++I, ++Idx) { 6532 SmallVector<SDValue, 4> ArgValues; 6533 SmallVector<EVT, 4> ValueVTs; 6534 ComputeValueVTs(TLI, I->getType(), ValueVTs); 6535 unsigned NumValues = ValueVTs.size(); 6536 6537 // If this argument is unused then remember its value. It is used to generate 6538 // debugging information. 6539 if (I->use_empty() && NumValues) 6540 SDB->setUnusedArgValue(I, InVals[i]); 6541 6542 for (unsigned Val = 0; Val != NumValues; ++Val) { 6543 EVT VT = ValueVTs[Val]; 6544 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6545 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT); 6546 6547 if (!I->use_empty()) { 6548 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6549 if (F.paramHasAttr(Idx, Attribute::SExt)) 6550 AssertOp = ISD::AssertSext; 6551 else if (F.paramHasAttr(Idx, Attribute::ZExt)) 6552 AssertOp = ISD::AssertZext; 6553 6554 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], 6555 NumParts, PartVT, VT, 6556 AssertOp)); 6557 } 6558 6559 i += NumParts; 6560 } 6561 6562 // We don't need to do anything else for unused arguments. 6563 if (ArgValues.empty()) 6564 continue; 6565 6566 // Note down frame index for byval arguments. 6567 if (I->hasByValAttr()) 6568 if (FrameIndexSDNode *FI = 6569 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 6570 FuncInfo->setByValArgumentFrameIndex(I, FI->getIndex()); 6571 6572 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues, 6573 SDB->getCurDebugLoc()); 6574 SDB->setValue(I, Res); 6575 6576 // If this argument is live outside of the entry block, insert a copy from 6577 // wherever we got it to the vreg that other BB's will reference it as. 6578 if (!EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 6579 // If we can, though, try to skip creating an unnecessary vreg. 6580 // FIXME: This isn't very clean... it would be nice to make this more 6581 // general. It's also subtly incompatible with the hacks FastISel 6582 // uses with vregs. 6583 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 6584 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 6585 FuncInfo->ValueMap[I] = Reg; 6586 continue; 6587 } 6588 } 6589 if (!isOnlyUsedInEntryBlock(I)) { 6590 FuncInfo->InitializeRegForValue(I); 6591 SDB->CopyToExportRegsIfNeeded(I); 6592 } 6593 } 6594 6595 assert(i == InVals.size() && "Argument register count mismatch!"); 6596 6597 // Finally, if the target has anything special to do, allow it to do so. 6598 // FIXME: this should insert code into the DAG! 6599 EmitFunctionEntryCode(); 6600} 6601 6602/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 6603/// ensure constants are generated when needed. Remember the virtual registers 6604/// that need to be added to the Machine PHI nodes as input. We cannot just 6605/// directly add them, because expansion might result in multiple MBB's for one 6606/// BB. As such, the start of the BB might correspond to a different MBB than 6607/// the end. 6608/// 6609void 6610SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 6611 const TerminatorInst *TI = LLVMBB->getTerminator(); 6612 6613 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 6614 6615 // Check successor nodes' PHI nodes that expect a constant to be available 6616 // from this block. 6617 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 6618 const BasicBlock *SuccBB = TI->getSuccessor(succ); 6619 if (!isa<PHINode>(SuccBB->begin())) continue; 6620 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 6621 6622 // If this terminator has multiple identical successors (common for 6623 // switches), only handle each succ once. 6624 if (!SuccsHandled.insert(SuccMBB)) continue; 6625 6626 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 6627 6628 // At this point we know that there is a 1-1 correspondence between LLVM PHI 6629 // nodes and Machine PHI nodes, but the incoming operands have not been 6630 // emitted yet. 6631 for (BasicBlock::const_iterator I = SuccBB->begin(); 6632 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 6633 // Ignore dead phi's. 6634 if (PN->use_empty()) continue; 6635 6636 // Skip empty types 6637 if (PN->getType()->isEmptyTy()) 6638 continue; 6639 6640 unsigned Reg; 6641 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 6642 6643 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 6644 unsigned &RegOut = ConstantsOut[C]; 6645 if (RegOut == 0) { 6646 RegOut = FuncInfo.CreateRegs(C->getType()); 6647 CopyValueToVirtualRegister(C, RegOut); 6648 } 6649 Reg = RegOut; 6650 } else { 6651 DenseMap<const Value *, unsigned>::iterator I = 6652 FuncInfo.ValueMap.find(PHIOp); 6653 if (I != FuncInfo.ValueMap.end()) 6654 Reg = I->second; 6655 else { 6656 assert(isa<AllocaInst>(PHIOp) && 6657 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 6658 "Didn't codegen value into a register!??"); 6659 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 6660 CopyValueToVirtualRegister(PHIOp, Reg); 6661 } 6662 } 6663 6664 // Remember that this register needs to added to the machine PHI node as 6665 // the input for this MBB. 6666 SmallVector<EVT, 4> ValueVTs; 6667 ComputeValueVTs(TLI, PN->getType(), ValueVTs); 6668 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 6669 EVT VT = ValueVTs[vti]; 6670 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 6671 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 6672 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 6673 Reg += NumRegisters; 6674 } 6675 } 6676 } 6677 ConstantsOut.clear(); 6678} 6679