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