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