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