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 JTEncoding = TLI.getJumpTableEncoding(); 1761 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding) 1762 ->getJumpTableIndex(DestBBs); 1763 1764 // Set the jump table information so that we can codegen it as a second 1765 // MachineBasicBlock 1766 JumpTable JT(-1U, JTI, JumpTableBB, Default); 1767 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB)); 1768 if (CR.CaseBB == CurMBB) 1769 visitJumpTableHeader(JT, JTH); 1770 1771 JTCases.push_back(JumpTableBlock(JTH, JT)); 1772 1773 return true; 1774 } 1775 1776 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into 1777 /// 2 subtrees. 1778 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR, 1779 CaseRecVector& WorkList, 1780 Value* SV, 1781 MachineBasicBlock* Default) { 1782 // Get the MachineFunction which holds the current MBB. This is used when 1783 // inserting any additional MBBs necessary to represent the switch. 1784 MachineFunction *CurMF = FuncInfo.MF; 1785 1786 // Figure out which block is immediately after the current one. 1787 MachineFunction::iterator BBI = CR.CaseBB; 1788 ++BBI; 1789 1790 Case& FrontCase = *CR.Range.first; 1791 Case& BackCase = *(CR.Range.second-1); 1792 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1793 1794 // Size is the number of Cases represented by this range. 1795 unsigned Size = CR.Range.second - CR.Range.first; 1796 1797 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 1798 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 1799 double FMetric = 0; 1800 CaseItr Pivot = CR.Range.first + Size/2; 1801 1802 // Select optimal pivot, maximizing sum density of LHS and RHS. This will 1803 // (heuristically) allow us to emit JumpTable's later. 1804 APInt TSize(First.getBitWidth(), 0); 1805 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1806 I!=E; ++I) 1807 TSize += I->size(); 1808 1809 APInt LSize = FrontCase.size(); 1810 APInt RSize = TSize-LSize; 1811 DEBUG(dbgs() << "Selecting best pivot: \n" 1812 << "First: " << First << ", Last: " << Last <<'\n' 1813 << "LSize: " << LSize << ", RSize: " << RSize << '\n'); 1814 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second; 1815 J!=E; ++I, ++J) { 1816 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue(); 1817 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue(); 1818 APInt Range = ComputeRange(LEnd, RBegin); 1819 assert((Range - 2ULL).isNonNegative() && 1820 "Invalid case distance"); 1821 double LDensity = (double)LSize.roundToDouble() / 1822 (LEnd - First + 1ULL).roundToDouble(); 1823 double RDensity = (double)RSize.roundToDouble() / 1824 (Last - RBegin + 1ULL).roundToDouble(); 1825 double Metric = Range.logBase2()*(LDensity+RDensity); 1826 // Should always split in some non-trivial place 1827 DEBUG(dbgs() <<"=>Step\n" 1828 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n' 1829 << "LDensity: " << LDensity 1830 << ", RDensity: " << RDensity << '\n' 1831 << "Metric: " << Metric << '\n'); 1832 if (FMetric < Metric) { 1833 Pivot = J; 1834 FMetric = Metric; 1835 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n'); 1836 } 1837 1838 LSize += J->size(); 1839 RSize -= J->size(); 1840 } 1841 if (areJTsAllowed(TLI)) { 1842 // If our case is dense we *really* should handle it earlier! 1843 assert((FMetric > 0) && "Should handle dense range earlier!"); 1844 } else { 1845 Pivot = CR.Range.first + Size/2; 1846 } 1847 1848 CaseRange LHSR(CR.Range.first, Pivot); 1849 CaseRange RHSR(Pivot, CR.Range.second); 1850 Constant *C = Pivot->Low; 1851 MachineBasicBlock *FalseBB = 0, *TrueBB = 0; 1852 1853 // We know that we branch to the LHS if the Value being switched on is 1854 // less than the Pivot value, C. We use this to optimize our binary 1855 // tree a bit, by recognizing that if SV is greater than or equal to the 1856 // LHS's Case Value, and that Case Value is exactly one less than the 1857 // Pivot's Value, then we can branch directly to the LHS's Target, 1858 // rather than creating a leaf node for it. 1859 if ((LHSR.second - LHSR.first) == 1 && 1860 LHSR.first->High == CR.GE && 1861 cast<ConstantInt>(C)->getValue() == 1862 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) { 1863 TrueBB = LHSR.first->BB; 1864 } else { 1865 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1866 CurMF->insert(BBI, TrueBB); 1867 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR)); 1868 1869 // Put SV in a virtual register to make it available from the new blocks. 1870 ExportFromCurrentBlock(SV); 1871 } 1872 1873 // Similar to the optimization above, if the Value being switched on is 1874 // known to be less than the Constant CR.LT, and the current Case Value 1875 // is CR.LT - 1, then we can branch directly to the target block for 1876 // the current Case Value, rather than emitting a RHS leaf node for it. 1877 if ((RHSR.second - RHSR.first) == 1 && CR.LT && 1878 cast<ConstantInt>(RHSR.first->Low)->getValue() == 1879 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) { 1880 FalseBB = RHSR.first->BB; 1881 } else { 1882 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1883 CurMF->insert(BBI, FalseBB); 1884 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR)); 1885 1886 // Put SV in a virtual register to make it available from the new blocks. 1887 ExportFromCurrentBlock(SV); 1888 } 1889 1890 // Create a CaseBlock record representing a conditional branch to 1891 // the LHS node if the value being switched on SV is less than C. 1892 // Otherwise, branch to LHS. 1893 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB); 1894 1895 if (CR.CaseBB == CurMBB) 1896 visitSwitchCase(CB); 1897 else 1898 SwitchCases.push_back(CB); 1899 1900 return true; 1901 } 1902 1903 /// handleBitTestsSwitchCase - if current case range has few destination and 1904 /// range span less, than machine word bitwidth, encode case range into series 1905 /// of masks and emit bit tests with these masks. 1906 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR, 1907 CaseRecVector& WorkList, 1908 Value* SV, 1909 MachineBasicBlock* Default){ 1910 EVT PTy = TLI.getPointerTy(); 1911 unsigned IntPtrBits = PTy.getSizeInBits(); 1912 1913 Case& FrontCase = *CR.Range.first; 1914 Case& BackCase = *(CR.Range.second-1); 1915 1916 // Get the MachineFunction which holds the current MBB. This is used when 1917 // inserting any additional MBBs necessary to represent the switch. 1918 MachineFunction *CurMF = FuncInfo.MF; 1919 1920 // If target does not have legal shift left, do not emit bit tests at all. 1921 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy())) 1922 return false; 1923 1924 size_t numCmps = 0; 1925 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1926 I!=E; ++I) { 1927 // Single case counts one, case range - two. 1928 numCmps += (I->Low == I->High ? 1 : 2); 1929 } 1930 1931 // Count unique destinations 1932 SmallSet<MachineBasicBlock*, 4> Dests; 1933 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 1934 Dests.insert(I->BB); 1935 if (Dests.size() > 3) 1936 // Don't bother the code below, if there are too much unique destinations 1937 return false; 1938 } 1939 DEBUG(dbgs() << "Total number of unique destinations: " 1940 << Dests.size() << '\n' 1941 << "Total number of comparisons: " << numCmps << '\n'); 1942 1943 // Compute span of values. 1944 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue(); 1945 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue(); 1946 APInt cmpRange = maxValue - minValue; 1947 1948 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n' 1949 << "Low bound: " << minValue << '\n' 1950 << "High bound: " << maxValue << '\n'); 1951 1952 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) || 1953 (!(Dests.size() == 1 && numCmps >= 3) && 1954 !(Dests.size() == 2 && numCmps >= 5) && 1955 !(Dests.size() >= 3 && numCmps >= 6))) 1956 return false; 1957 1958 DEBUG(dbgs() << "Emitting bit tests\n"); 1959 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth()); 1960 1961 // Optimize the case where all the case values fit in a 1962 // word without having to subtract minValue. In this case, 1963 // we can optimize away the subtraction. 1964 if (minValue.isNonNegative() && 1965 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) { 1966 cmpRange = maxValue; 1967 } else { 1968 lowBound = minValue; 1969 } 1970 1971 CaseBitsVector CasesBits; 1972 unsigned i, count = 0; 1973 1974 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 1975 MachineBasicBlock* Dest = I->BB; 1976 for (i = 0; i < count; ++i) 1977 if (Dest == CasesBits[i].BB) 1978 break; 1979 1980 if (i == count) { 1981 assert((count < 3) && "Too much destinations to test!"); 1982 CasesBits.push_back(CaseBits(0, Dest, 0)); 1983 count++; 1984 } 1985 1986 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue(); 1987 const APInt& highValue = cast<ConstantInt>(I->High)->getValue(); 1988 1989 uint64_t lo = (lowValue - lowBound).getZExtValue(); 1990 uint64_t hi = (highValue - lowBound).getZExtValue(); 1991 1992 for (uint64_t j = lo; j <= hi; j++) { 1993 CasesBits[i].Mask |= 1ULL << j; 1994 CasesBits[i].Bits++; 1995 } 1996 1997 } 1998 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp()); 1999 2000 BitTestInfo BTC; 2001 2002 // Figure out which block is immediately after the current one. 2003 MachineFunction::iterator BBI = CR.CaseBB; 2004 ++BBI; 2005 2006 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 2007 2008 DEBUG(dbgs() << "Cases:\n"); 2009 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) { 2010 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask 2011 << ", Bits: " << CasesBits[i].Bits 2012 << ", BB: " << CasesBits[i].BB << '\n'); 2013 2014 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2015 CurMF->insert(BBI, CaseBB); 2016 BTC.push_back(BitTestCase(CasesBits[i].Mask, 2017 CaseBB, 2018 CasesBits[i].BB)); 2019 2020 // Put SV in a virtual register to make it available from the new blocks. 2021 ExportFromCurrentBlock(SV); 2022 } 2023 2024 BitTestBlock BTB(lowBound, cmpRange, SV, 2025 -1U, (CR.CaseBB == CurMBB), 2026 CR.CaseBB, Default, BTC); 2027 2028 if (CR.CaseBB == CurMBB) 2029 visitBitTestHeader(BTB); 2030 2031 BitTestCases.push_back(BTB); 2032 2033 return true; 2034 } 2035 2036 /// Clusterify - Transform simple list of Cases into list of CaseRange's 2037 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases, 2038 const SwitchInst& SI) { 2039 size_t numCmps = 0; 2040 2041 // Start with "simple" cases 2042 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) { 2043 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)]; 2044 Cases.push_back(Case(SI.getSuccessorValue(i), 2045 SI.getSuccessorValue(i), 2046 SMBB)); 2047 } 2048 std::sort(Cases.begin(), Cases.end(), CaseCmp()); 2049 2050 // Merge case into clusters 2051 if (Cases.size() >= 2) 2052 // Must recompute end() each iteration because it may be 2053 // invalidated by erase if we hold on to it 2054 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) { 2055 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue(); 2056 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue(); 2057 MachineBasicBlock* nextBB = J->BB; 2058 MachineBasicBlock* currentBB = I->BB; 2059 2060 // If the two neighboring cases go to the same destination, merge them 2061 // into a single case. 2062 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) { 2063 I->High = J->High; 2064 J = Cases.erase(J); 2065 } else { 2066 I = J++; 2067 } 2068 } 2069 2070 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) { 2071 if (I->Low != I->High) 2072 // A range counts double, since it requires two compares. 2073 ++numCmps; 2074 } 2075 2076 return numCmps; 2077 } 2078 2079 void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) { 2080 // Figure out which block is immediately after the current one. 2081 MachineBasicBlock *NextBlock = 0; 2082 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()]; 2083 2084 // If there is only the default destination, branch to it if it is not the 2085 // next basic block. Otherwise, just fall through. 2086 if (SI.getNumOperands() == 2) { 2087 // Update machine-CFG edges. 2088 2089 // If this is not a fall-through branch, emit the branch. 2090 CurMBB->addSuccessor(Default); 2091 if (Default != NextBlock) { 2092 SDValue Res = DAG.getNode(ISD::BR, getCurDebugLoc(), 2093 MVT::Other, getControlRoot(), 2094 DAG.getBasicBlock(Default)); 2095 DAG.setRoot(Res); 2096 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2097 } 2098 2099 return; 2100 } 2101 2102 // If there are any non-default case statements, create a vector of Cases 2103 // representing each one, and sort the vector so that we can efficiently 2104 // create a binary search tree from them. 2105 CaseVector Cases; 2106 size_t numCmps = Clusterify(Cases, SI); 2107 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size() 2108 << ". Total compares: " << numCmps << '\n'); 2109 numCmps = 0; 2110 2111 // Get the Value to be switched on and default basic blocks, which will be 2112 // inserted into CaseBlock records, representing basic blocks in the binary 2113 // search tree. 2114 Value *SV = SI.getOperand(0); 2115 2116 // Push the initial CaseRec onto the worklist 2117 CaseRecVector WorkList; 2118 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end()))); 2119 2120 while (!WorkList.empty()) { 2121 // Grab a record representing a case range to process off the worklist 2122 CaseRec CR = WorkList.back(); 2123 WorkList.pop_back(); 2124 2125 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default)) 2126 continue; 2127 2128 // If the range has few cases (two or less) emit a series of specific 2129 // tests. 2130 if (handleSmallSwitchRange(CR, WorkList, SV, Default)) 2131 continue; 2132 2133 // If the switch has more than 5 blocks, and at least 40% dense, and the 2134 // target supports indirect branches, then emit a jump table rather than 2135 // lowering the switch to a binary tree of conditional branches. 2136 if (handleJTSwitchCase(CR, WorkList, SV, Default)) 2137 continue; 2138 2139 // Emit binary tree. We need to pick a pivot, and push left and right ranges 2140 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call. 2141 handleBTSplitSwitchCase(CR, WorkList, SV, Default); 2142 } 2143 } 2144 2145 void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) { 2146 // Update machine-CFG edges. 2147 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) 2148 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]); 2149 2150 SDValue Res = DAG.getNode(ISD::BRIND, getCurDebugLoc(), 2151 MVT::Other, getControlRoot(), 2152 getValue(I.getAddress())); 2153 DAG.setRoot(Res); 2154 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2155 } 2156 2157 void SelectionDAGBuilder::visitFSub(User &I) { 2158 // -0.0 - X --> fneg 2159 const Type *Ty = I.getType(); 2160 if (isa<VectorType>(Ty)) { 2161 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) { 2162 const VectorType *DestTy = cast<VectorType>(I.getType()); 2163 const Type *ElTy = DestTy->getElementType(); 2164 unsigned VL = DestTy->getNumElements(); 2165 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy)); 2166 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size()); 2167 if (CV == CNZ) { 2168 SDValue Op2 = getValue(I.getOperand(1)); 2169 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(), 2170 Op2.getValueType(), Op2); 2171 setValue(&I, Res); 2172 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2173 return; 2174 } 2175 } 2176 } 2177 2178 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) 2179 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) { 2180 SDValue Op2 = getValue(I.getOperand(1)); 2181 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(), 2182 Op2.getValueType(), Op2); 2183 setValue(&I, Res); 2184 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2185 return; 2186 } 2187 2188 visitBinary(I, ISD::FSUB); 2189 } 2190 2191 void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) { 2192 SDValue Op1 = getValue(I.getOperand(0)); 2193 SDValue Op2 = getValue(I.getOperand(1)); 2194 SDValue Res = DAG.getNode(OpCode, getCurDebugLoc(), 2195 Op1.getValueType(), Op1, Op2); 2196 setValue(&I, Res); 2197 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2198 } 2199 2200 void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) { 2201 SDValue Op1 = getValue(I.getOperand(0)); 2202 SDValue Op2 = getValue(I.getOperand(1)); 2203 if (!isa<VectorType>(I.getType()) && 2204 Op2.getValueType() != TLI.getShiftAmountTy()) { 2205 // If the operand is smaller than the shift count type, promote it. 2206 EVT PTy = TLI.getPointerTy(); 2207 EVT STy = TLI.getShiftAmountTy(); 2208 if (STy.bitsGT(Op2.getValueType())) 2209 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(), 2210 TLI.getShiftAmountTy(), Op2); 2211 // If the operand is larger than the shift count type but the shift 2212 // count type has enough bits to represent any shift value, truncate 2213 // it now. This is a common case and it exposes the truncate to 2214 // optimization early. 2215 else if (STy.getSizeInBits() >= 2216 Log2_32_Ceil(Op2.getValueType().getSizeInBits())) 2217 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2218 TLI.getShiftAmountTy(), Op2); 2219 // Otherwise we'll need to temporarily settle for some other 2220 // convenient type; type legalization will make adjustments as 2221 // needed. 2222 else if (PTy.bitsLT(Op2.getValueType())) 2223 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2224 TLI.getPointerTy(), Op2); 2225 else if (PTy.bitsGT(Op2.getValueType())) 2226 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(), 2227 TLI.getPointerTy(), Op2); 2228 } 2229 2230 SDValue Res = DAG.getNode(Opcode, getCurDebugLoc(), 2231 Op1.getValueType(), Op1, Op2); 2232 setValue(&I, Res); 2233 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder); 2234 DAG.AssignOrdering(Op2.getNode(), SDNodeOrder); 2235 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2236 } 2237 2238 void SelectionDAGBuilder::visitICmp(User &I) { 2239 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2240 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2241 predicate = IC->getPredicate(); 2242 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2243 predicate = ICmpInst::Predicate(IC->getPredicate()); 2244 SDValue Op1 = getValue(I.getOperand(0)); 2245 SDValue Op2 = getValue(I.getOperand(1)); 2246 ISD::CondCode Opcode = getICmpCondCode(predicate); 2247 2248 EVT DestVT = TLI.getValueType(I.getType()); 2249 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode); 2250 setValue(&I, Res); 2251 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2252 } 2253 2254 void SelectionDAGBuilder::visitFCmp(User &I) { 2255 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2256 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2257 predicate = FC->getPredicate(); 2258 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2259 predicate = FCmpInst::Predicate(FC->getPredicate()); 2260 SDValue Op1 = getValue(I.getOperand(0)); 2261 SDValue Op2 = getValue(I.getOperand(1)); 2262 ISD::CondCode Condition = getFCmpCondCode(predicate); 2263 EVT DestVT = TLI.getValueType(I.getType()); 2264 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition); 2265 setValue(&I, Res); 2266 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2267 } 2268 2269 void SelectionDAGBuilder::visitSelect(User &I) { 2270 SmallVector<EVT, 4> ValueVTs; 2271 ComputeValueVTs(TLI, I.getType(), ValueVTs); 2272 unsigned NumValues = ValueVTs.size(); 2273 if (NumValues == 0) return; 2274 2275 SmallVector<SDValue, 4> Values(NumValues); 2276 SDValue Cond = getValue(I.getOperand(0)); 2277 SDValue TrueVal = getValue(I.getOperand(1)); 2278 SDValue FalseVal = getValue(I.getOperand(2)); 2279 2280 for (unsigned i = 0; i != NumValues; ++i) { 2281 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(), 2282 TrueVal.getNode()->getValueType(i), Cond, 2283 SDValue(TrueVal.getNode(), 2284 TrueVal.getResNo() + i), 2285 SDValue(FalseVal.getNode(), 2286 FalseVal.getResNo() + i)); 2287 2288 DAG.AssignOrdering(Values[i].getNode(), SDNodeOrder); 2289 } 2290 2291 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2292 DAG.getVTList(&ValueVTs[0], NumValues), 2293 &Values[0], NumValues); 2294 setValue(&I, Res); 2295 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2296 } 2297 2298 void SelectionDAGBuilder::visitTrunc(User &I) { 2299 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2300 SDValue N = getValue(I.getOperand(0)); 2301 EVT DestVT = TLI.getValueType(I.getType()); 2302 SDValue Res = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N); 2303 setValue(&I, Res); 2304 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2305 } 2306 2307 void SelectionDAGBuilder::visitZExt(User &I) { 2308 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2309 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2310 SDValue N = getValue(I.getOperand(0)); 2311 EVT DestVT = TLI.getValueType(I.getType()); 2312 SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N); 2313 setValue(&I, Res); 2314 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2315 } 2316 2317 void SelectionDAGBuilder::visitSExt(User &I) { 2318 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2319 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2320 SDValue N = getValue(I.getOperand(0)); 2321 EVT DestVT = TLI.getValueType(I.getType()); 2322 SDValue Res = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N); 2323 setValue(&I, Res); 2324 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2325 } 2326 2327 void SelectionDAGBuilder::visitFPTrunc(User &I) { 2328 // FPTrunc is never a no-op cast, no need to check 2329 SDValue N = getValue(I.getOperand(0)); 2330 EVT DestVT = TLI.getValueType(I.getType()); 2331 SDValue Res = DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(), 2332 DestVT, N, DAG.getIntPtrConstant(0)); 2333 setValue(&I, Res); 2334 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2335 } 2336 2337 void SelectionDAGBuilder::visitFPExt(User &I){ 2338 // FPTrunc is never a no-op cast, no need to check 2339 SDValue N = getValue(I.getOperand(0)); 2340 EVT DestVT = TLI.getValueType(I.getType()); 2341 SDValue Res = DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N); 2342 setValue(&I, Res); 2343 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2344 } 2345 2346 void SelectionDAGBuilder::visitFPToUI(User &I) { 2347 // FPToUI is never a no-op cast, no need to check 2348 SDValue N = getValue(I.getOperand(0)); 2349 EVT DestVT = TLI.getValueType(I.getType()); 2350 SDValue Res = DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N); 2351 setValue(&I, Res); 2352 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2353 } 2354 2355 void SelectionDAGBuilder::visitFPToSI(User &I) { 2356 // FPToSI is never a no-op cast, no need to check 2357 SDValue N = getValue(I.getOperand(0)); 2358 EVT DestVT = TLI.getValueType(I.getType()); 2359 SDValue Res = DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N); 2360 setValue(&I, Res); 2361 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2362 } 2363 2364 void SelectionDAGBuilder::visitUIToFP(User &I) { 2365 // UIToFP is never a no-op cast, no need to check 2366 SDValue N = getValue(I.getOperand(0)); 2367 EVT DestVT = TLI.getValueType(I.getType()); 2368 SDValue Res = DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N); 2369 setValue(&I, Res); 2370 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2371 } 2372 2373 void SelectionDAGBuilder::visitSIToFP(User &I){ 2374 // SIToFP is never a no-op cast, no need to check 2375 SDValue N = getValue(I.getOperand(0)); 2376 EVT DestVT = TLI.getValueType(I.getType()); 2377 SDValue Res = DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N); 2378 setValue(&I, Res); 2379 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2380 } 2381 2382 void SelectionDAGBuilder::visitPtrToInt(User &I) { 2383 // What to do depends on the size of the integer and the size of the pointer. 2384 // We can either truncate, zero extend, or no-op, accordingly. 2385 SDValue N = getValue(I.getOperand(0)); 2386 EVT SrcVT = N.getValueType(); 2387 EVT DestVT = TLI.getValueType(I.getType()); 2388 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT); 2389 setValue(&I, Res); 2390 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2391 } 2392 2393 void SelectionDAGBuilder::visitIntToPtr(User &I) { 2394 // What to do depends on the size of the integer and the size of the pointer. 2395 // We can either truncate, zero extend, or no-op, accordingly. 2396 SDValue N = getValue(I.getOperand(0)); 2397 EVT SrcVT = N.getValueType(); 2398 EVT DestVT = TLI.getValueType(I.getType()); 2399 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT); 2400 setValue(&I, Res); 2401 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2402 } 2403 2404 void SelectionDAGBuilder::visitBitCast(User &I) { 2405 SDValue N = getValue(I.getOperand(0)); 2406 EVT DestVT = TLI.getValueType(I.getType()); 2407 2408 // BitCast assures us that source and destination are the same size so this is 2409 // either a BIT_CONVERT or a no-op. 2410 if (DestVT != N.getValueType()) { 2411 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 2412 DestVT, N); // convert types. 2413 setValue(&I, Res); 2414 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2415 } else { 2416 setValue(&I, N); // noop cast. 2417 } 2418 } 2419 2420 void SelectionDAGBuilder::visitInsertElement(User &I) { 2421 SDValue InVec = getValue(I.getOperand(0)); 2422 SDValue InVal = getValue(I.getOperand(1)); 2423 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 2424 TLI.getPointerTy(), 2425 getValue(I.getOperand(2))); 2426 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(), 2427 TLI.getValueType(I.getType()), 2428 InVec, InVal, InIdx); 2429 setValue(&I, Res); 2430 2431 DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder); 2432 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2433 } 2434 2435 void SelectionDAGBuilder::visitExtractElement(User &I) { 2436 SDValue InVec = getValue(I.getOperand(0)); 2437 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 2438 TLI.getPointerTy(), 2439 getValue(I.getOperand(1))); 2440 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2441 TLI.getValueType(I.getType()), InVec, InIdx); 2442 setValue(&I, Res); 2443 2444 DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder); 2445 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2446 } 2447 2448 2449 // Utility for visitShuffleVector - Returns true if the mask is mask starting 2450 // from SIndx and increasing to the element length (undefs are allowed). 2451 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) { 2452 unsigned MaskNumElts = Mask.size(); 2453 for (unsigned i = 0; i != MaskNumElts; ++i) 2454 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx))) 2455 return false; 2456 return true; 2457 } 2458 2459 void SelectionDAGBuilder::visitShuffleVector(User &I) { 2460 SmallVector<int, 8> Mask; 2461 SDValue Src1 = getValue(I.getOperand(0)); 2462 SDValue Src2 = getValue(I.getOperand(1)); 2463 2464 // Convert the ConstantVector mask operand into an array of ints, with -1 2465 // representing undef values. 2466 SmallVector<Constant*, 8> MaskElts; 2467 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(), 2468 MaskElts); 2469 unsigned MaskNumElts = MaskElts.size(); 2470 for (unsigned i = 0; i != MaskNumElts; ++i) { 2471 if (isa<UndefValue>(MaskElts[i])) 2472 Mask.push_back(-1); 2473 else 2474 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue()); 2475 } 2476 2477 EVT VT = TLI.getValueType(I.getType()); 2478 EVT SrcVT = Src1.getValueType(); 2479 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 2480 2481 if (SrcNumElts == MaskNumElts) { 2482 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2483 &Mask[0]); 2484 setValue(&I, Res); 2485 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2486 return; 2487 } 2488 2489 // Normalize the shuffle vector since mask and vector length don't match. 2490 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) { 2491 // Mask is longer than the source vectors and is a multiple of the source 2492 // vectors. We can use concatenate vector to make the mask and vectors 2493 // lengths match. 2494 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) { 2495 // The shuffle is concatenating two vectors together. 2496 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(), 2497 VT, Src1, Src2); 2498 setValue(&I, Res); 2499 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2500 return; 2501 } 2502 2503 // Pad both vectors with undefs to make them the same length as the mask. 2504 unsigned NumConcat = MaskNumElts / SrcNumElts; 2505 bool Src1U = Src1.getOpcode() == ISD::UNDEF; 2506 bool Src2U = Src2.getOpcode() == ISD::UNDEF; 2507 SDValue UndefVal = DAG.getUNDEF(SrcVT); 2508 2509 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 2510 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 2511 MOps1[0] = Src1; 2512 MOps2[0] = Src2; 2513 2514 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2515 getCurDebugLoc(), VT, 2516 &MOps1[0], NumConcat); 2517 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2518 getCurDebugLoc(), VT, 2519 &MOps2[0], NumConcat); 2520 2521 // Readjust mask for new input vector length. 2522 SmallVector<int, 8> MappedOps; 2523 for (unsigned i = 0; i != MaskNumElts; ++i) { 2524 int Idx = Mask[i]; 2525 if (Idx < (int)SrcNumElts) 2526 MappedOps.push_back(Idx); 2527 else 2528 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts); 2529 } 2530 2531 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2532 &MappedOps[0]); 2533 setValue(&I, Res); 2534 DAG.AssignOrdering(Src1.getNode(), SDNodeOrder); 2535 DAG.AssignOrdering(Src2.getNode(), SDNodeOrder); 2536 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2537 return; 2538 } 2539 2540 if (SrcNumElts > MaskNumElts) { 2541 // Analyze the access pattern of the vector to see if we can extract 2542 // two subvectors and do the shuffle. The analysis is done by calculating 2543 // the range of elements the mask access on both vectors. 2544 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1}; 2545 int MaxRange[2] = {-1, -1}; 2546 2547 for (unsigned i = 0; i != MaskNumElts; ++i) { 2548 int Idx = Mask[i]; 2549 int Input = 0; 2550 if (Idx < 0) 2551 continue; 2552 2553 if (Idx >= (int)SrcNumElts) { 2554 Input = 1; 2555 Idx -= SrcNumElts; 2556 } 2557 if (Idx > MaxRange[Input]) 2558 MaxRange[Input] = Idx; 2559 if (Idx < MinRange[Input]) 2560 MinRange[Input] = Idx; 2561 } 2562 2563 // Check if the access is smaller than the vector size and can we find 2564 // a reasonable extract index. 2565 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not 2566 // Extract. 2567 int StartIdx[2]; // StartIdx to extract from 2568 for (int Input=0; Input < 2; ++Input) { 2569 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) { 2570 RangeUse[Input] = 0; // Unused 2571 StartIdx[Input] = 0; 2572 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) { 2573 // Fits within range but we should see if we can find a good 2574 // start index that is a multiple of the mask length. 2575 if (MaxRange[Input] < (int)MaskNumElts) { 2576 RangeUse[Input] = 1; // Extract from beginning of the vector 2577 StartIdx[Input] = 0; 2578 } else { 2579 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts; 2580 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts && 2581 StartIdx[Input] + MaskNumElts < SrcNumElts) 2582 RangeUse[Input] = 1; // Extract from a multiple of the mask length. 2583 } 2584 } 2585 } 2586 2587 if (RangeUse[0] == 0 && RangeUse[1] == 0) { 2588 SDValue Res = DAG.getUNDEF(VT); 2589 setValue(&I, Res); // Vectors are not used. 2590 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2591 return; 2592 } 2593 else if (RangeUse[0] < 2 && RangeUse[1] < 2) { 2594 // Extract appropriate subvector and generate a vector shuffle 2595 for (int Input=0; Input < 2; ++Input) { 2596 SDValue &Src = Input == 0 ? Src1 : Src2; 2597 if (RangeUse[Input] == 0) 2598 Src = DAG.getUNDEF(VT); 2599 else 2600 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT, 2601 Src, DAG.getIntPtrConstant(StartIdx[Input])); 2602 2603 DAG.AssignOrdering(Src.getNode(), SDNodeOrder); 2604 } 2605 2606 // Calculate new mask. 2607 SmallVector<int, 8> MappedOps; 2608 for (unsigned i = 0; i != MaskNumElts; ++i) { 2609 int Idx = Mask[i]; 2610 if (Idx < 0) 2611 MappedOps.push_back(Idx); 2612 else if (Idx < (int)SrcNumElts) 2613 MappedOps.push_back(Idx - StartIdx[0]); 2614 else 2615 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts); 2616 } 2617 2618 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2619 &MappedOps[0]); 2620 setValue(&I, Res); 2621 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2622 return; 2623 } 2624 } 2625 2626 // We can't use either concat vectors or extract subvectors so fall back to 2627 // replacing the shuffle with extract and build vector. 2628 // to insert and build vector. 2629 EVT EltVT = VT.getVectorElementType(); 2630 EVT PtrVT = TLI.getPointerTy(); 2631 SmallVector<SDValue,8> Ops; 2632 for (unsigned i = 0; i != MaskNumElts; ++i) { 2633 if (Mask[i] < 0) { 2634 Ops.push_back(DAG.getUNDEF(EltVT)); 2635 } else { 2636 int Idx = Mask[i]; 2637 SDValue Res; 2638 2639 if (Idx < (int)SrcNumElts) 2640 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2641 EltVT, Src1, DAG.getConstant(Idx, PtrVT)); 2642 else 2643 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2644 EltVT, Src2, 2645 DAG.getConstant(Idx - SrcNumElts, PtrVT)); 2646 2647 Ops.push_back(Res); 2648 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2649 } 2650 } 2651 2652 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 2653 VT, &Ops[0], Ops.size()); 2654 setValue(&I, Res); 2655 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2656 } 2657 2658 void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) { 2659 const Value *Op0 = I.getOperand(0); 2660 const Value *Op1 = I.getOperand(1); 2661 const Type *AggTy = I.getType(); 2662 const Type *ValTy = Op1->getType(); 2663 bool IntoUndef = isa<UndefValue>(Op0); 2664 bool FromUndef = isa<UndefValue>(Op1); 2665 2666 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy, 2667 I.idx_begin(), I.idx_end()); 2668 2669 SmallVector<EVT, 4> AggValueVTs; 2670 ComputeValueVTs(TLI, AggTy, AggValueVTs); 2671 SmallVector<EVT, 4> ValValueVTs; 2672 ComputeValueVTs(TLI, ValTy, ValValueVTs); 2673 2674 unsigned NumAggValues = AggValueVTs.size(); 2675 unsigned NumValValues = ValValueVTs.size(); 2676 SmallVector<SDValue, 4> Values(NumAggValues); 2677 2678 SDValue Agg = getValue(Op0); 2679 SDValue Val = getValue(Op1); 2680 unsigned i = 0; 2681 // Copy the beginning value(s) from the original aggregate. 2682 for (; i != LinearIndex; ++i) 2683 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2684 SDValue(Agg.getNode(), Agg.getResNo() + i); 2685 // Copy values from the inserted value(s). 2686 for (; i != LinearIndex + NumValValues; ++i) 2687 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2688 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 2689 // Copy remaining value(s) from the original aggregate. 2690 for (; i != NumAggValues; ++i) 2691 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2692 SDValue(Agg.getNode(), Agg.getResNo() + i); 2693 2694 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2695 DAG.getVTList(&AggValueVTs[0], NumAggValues), 2696 &Values[0], NumAggValues); 2697 setValue(&I, Res); 2698 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2699 } 2700 2701 void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) { 2702 const Value *Op0 = I.getOperand(0); 2703 const Type *AggTy = Op0->getType(); 2704 const Type *ValTy = I.getType(); 2705 bool OutOfUndef = isa<UndefValue>(Op0); 2706 2707 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy, 2708 I.idx_begin(), I.idx_end()); 2709 2710 SmallVector<EVT, 4> ValValueVTs; 2711 ComputeValueVTs(TLI, ValTy, ValValueVTs); 2712 2713 unsigned NumValValues = ValValueVTs.size(); 2714 SmallVector<SDValue, 4> Values(NumValValues); 2715 2716 SDValue Agg = getValue(Op0); 2717 // Copy out the selected value(s). 2718 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 2719 Values[i - LinearIndex] = 2720 OutOfUndef ? 2721 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 2722 SDValue(Agg.getNode(), Agg.getResNo() + i); 2723 2724 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2725 DAG.getVTList(&ValValueVTs[0], NumValValues), 2726 &Values[0], NumValValues); 2727 setValue(&I, Res); 2728 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2729 } 2730 2731 void SelectionDAGBuilder::visitGetElementPtr(User &I) { 2732 SDValue N = getValue(I.getOperand(0)); 2733 const Type *Ty = I.getOperand(0)->getType(); 2734 2735 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end(); 2736 OI != E; ++OI) { 2737 Value *Idx = *OI; 2738 if (const StructType *StTy = dyn_cast<StructType>(Ty)) { 2739 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue(); 2740 if (Field) { 2741 // N = N + Offset 2742 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field); 2743 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N, 2744 DAG.getIntPtrConstant(Offset)); 2745 DAG.AssignOrdering(N.getNode(), SDNodeOrder); 2746 } 2747 2748 Ty = StTy->getElementType(Field); 2749 } else { 2750 Ty = cast<SequentialType>(Ty)->getElementType(); 2751 2752 // If this is a constant subscript, handle it quickly. 2753 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 2754 if (CI->getZExtValue() == 0) continue; 2755 uint64_t Offs = 2756 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue(); 2757 SDValue OffsVal; 2758 EVT PTy = TLI.getPointerTy(); 2759 unsigned PtrBits = PTy.getSizeInBits(); 2760 if (PtrBits < 64) 2761 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2762 TLI.getPointerTy(), 2763 DAG.getConstant(Offs, MVT::i64)); 2764 else 2765 OffsVal = DAG.getIntPtrConstant(Offs); 2766 2767 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N, 2768 OffsVal); 2769 2770 DAG.AssignOrdering(OffsVal.getNode(), SDNodeOrder); 2771 DAG.AssignOrdering(N.getNode(), SDNodeOrder); 2772 continue; 2773 } 2774 2775 // N = N + Idx * ElementSize; 2776 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(), 2777 TD->getTypeAllocSize(Ty)); 2778 SDValue IdxN = getValue(Idx); 2779 2780 // If the index is smaller or larger than intptr_t, truncate or extend 2781 // it. 2782 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType()); 2783 2784 // If this is a multiply by a power of two, turn it into a shl 2785 // immediately. This is a very common case. 2786 if (ElementSize != 1) { 2787 if (ElementSize.isPowerOf2()) { 2788 unsigned Amt = ElementSize.logBase2(); 2789 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(), 2790 N.getValueType(), IdxN, 2791 DAG.getConstant(Amt, TLI.getPointerTy())); 2792 } else { 2793 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy()); 2794 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(), 2795 N.getValueType(), IdxN, Scale); 2796 } 2797 2798 DAG.AssignOrdering(IdxN.getNode(), SDNodeOrder); 2799 } 2800 2801 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), 2802 N.getValueType(), N, IdxN); 2803 DAG.AssignOrdering(N.getNode(), SDNodeOrder); 2804 } 2805 } 2806 2807 setValue(&I, N); 2808 } 2809 2810 void SelectionDAGBuilder::visitAlloca(AllocaInst &I) { 2811 // If this is a fixed sized alloca in the entry block of the function, 2812 // allocate it statically on the stack. 2813 if (FuncInfo.StaticAllocaMap.count(&I)) 2814 return; // getValue will auto-populate this. 2815 2816 const Type *Ty = I.getAllocatedType(); 2817 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); 2818 unsigned Align = 2819 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), 2820 I.getAlignment()); 2821 2822 SDValue AllocSize = getValue(I.getArraySize()); 2823 2824 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(), 2825 AllocSize, 2826 DAG.getConstant(TySize, AllocSize.getValueType())); 2827 2828 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder); 2829 2830 EVT IntPtr = TLI.getPointerTy(); 2831 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr); 2832 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder); 2833 2834 // Handle alignment. If the requested alignment is less than or equal to 2835 // the stack alignment, ignore it. If the size is greater than or equal to 2836 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 2837 unsigned StackAlign = 2838 TLI.getTargetMachine().getFrameInfo()->getStackAlignment(); 2839 if (Align <= StackAlign) 2840 Align = 0; 2841 2842 // Round the size of the allocation up to the stack alignment size 2843 // by add SA-1 to the size. 2844 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(), 2845 AllocSize.getValueType(), AllocSize, 2846 DAG.getIntPtrConstant(StackAlign-1)); 2847 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder); 2848 2849 // Mask out the low bits for alignment purposes. 2850 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(), 2851 AllocSize.getValueType(), AllocSize, 2852 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1))); 2853 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder); 2854 2855 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) }; 2856 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 2857 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(), 2858 VTs, Ops, 3); 2859 setValue(&I, DSA); 2860 DAG.setRoot(DSA.getValue(1)); 2861 DAG.AssignOrdering(DSA.getNode(), SDNodeOrder); 2862 2863 // Inform the Frame Information that we have just allocated a variable-sized 2864 // object. 2865 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(); 2866 } 2867 2868 void SelectionDAGBuilder::visitLoad(LoadInst &I) { 2869 const Value *SV = I.getOperand(0); 2870 SDValue Ptr = getValue(SV); 2871 2872 const Type *Ty = I.getType(); 2873 bool isVolatile = I.isVolatile(); 2874 unsigned Alignment = I.getAlignment(); 2875 2876 SmallVector<EVT, 4> ValueVTs; 2877 SmallVector<uint64_t, 4> Offsets; 2878 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets); 2879 unsigned NumValues = ValueVTs.size(); 2880 if (NumValues == 0) 2881 return; 2882 2883 SDValue Root; 2884 bool ConstantMemory = false; 2885 if (I.isVolatile()) 2886 // Serialize volatile loads with other side effects. 2887 Root = getRoot(); 2888 else if (AA->pointsToConstantMemory(SV)) { 2889 // Do not serialize (non-volatile) loads of constant memory with anything. 2890 Root = DAG.getEntryNode(); 2891 ConstantMemory = true; 2892 } else { 2893 // Do not serialize non-volatile loads against each other. 2894 Root = DAG.getRoot(); 2895 } 2896 2897 SmallVector<SDValue, 4> Values(NumValues); 2898 SmallVector<SDValue, 4> Chains(NumValues); 2899 EVT PtrVT = Ptr.getValueType(); 2900 for (unsigned i = 0; i != NumValues; ++i) { 2901 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(), 2902 PtrVT, Ptr, 2903 DAG.getConstant(Offsets[i], PtrVT)); 2904 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root, 2905 A, SV, Offsets[i], isVolatile, Alignment); 2906 2907 Values[i] = L; 2908 Chains[i] = L.getValue(1); 2909 2910 DAG.AssignOrdering(A.getNode(), SDNodeOrder); 2911 DAG.AssignOrdering(L.getNode(), SDNodeOrder); 2912 } 2913 2914 if (!ConstantMemory) { 2915 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 2916 MVT::Other, &Chains[0], NumValues); 2917 if (isVolatile) 2918 DAG.setRoot(Chain); 2919 else 2920 PendingLoads.push_back(Chain); 2921 2922 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder); 2923 } 2924 2925 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2926 DAG.getVTList(&ValueVTs[0], NumValues), 2927 &Values[0], NumValues); 2928 setValue(&I, Res); 2929 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2930 } 2931 2932 void SelectionDAGBuilder::visitStore(StoreInst &I) { 2933 Value *SrcV = I.getOperand(0); 2934 Value *PtrV = I.getOperand(1); 2935 2936 SmallVector<EVT, 4> ValueVTs; 2937 SmallVector<uint64_t, 4> Offsets; 2938 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets); 2939 unsigned NumValues = ValueVTs.size(); 2940 if (NumValues == 0) 2941 return; 2942 2943 // Get the lowered operands. Note that we do this after 2944 // checking if NumResults is zero, because with zero results 2945 // the operands won't have values in the map. 2946 SDValue Src = getValue(SrcV); 2947 SDValue Ptr = getValue(PtrV); 2948 2949 SDValue Root = getRoot(); 2950 SmallVector<SDValue, 4> Chains(NumValues); 2951 EVT PtrVT = Ptr.getValueType(); 2952 bool isVolatile = I.isVolatile(); 2953 unsigned Alignment = I.getAlignment(); 2954 2955 for (unsigned i = 0; i != NumValues; ++i) { 2956 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr, 2957 DAG.getConstant(Offsets[i], PtrVT)); 2958 Chains[i] = DAG.getStore(Root, getCurDebugLoc(), 2959 SDValue(Src.getNode(), Src.getResNo() + i), 2960 Add, PtrV, Offsets[i], isVolatile, Alignment); 2961 2962 DAG.AssignOrdering(Add.getNode(), SDNodeOrder); 2963 DAG.AssignOrdering(Chains[i].getNode(), SDNodeOrder); 2964 } 2965 2966 SDValue Res = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 2967 MVT::Other, &Chains[0], NumValues); 2968 DAG.setRoot(Res); 2969 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 2970 } 2971 2972 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 2973 /// node. 2974 void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I, 2975 unsigned Intrinsic) { 2976 bool HasChain = !I.doesNotAccessMemory(); 2977 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 2978 2979 // Build the operand list. 2980 SmallVector<SDValue, 8> Ops; 2981 if (HasChain) { // If this intrinsic has side-effects, chainify it. 2982 if (OnlyLoad) { 2983 // We don't need to serialize loads against other loads. 2984 Ops.push_back(DAG.getRoot()); 2985 } else { 2986 Ops.push_back(getRoot()); 2987 } 2988 } 2989 2990 // Info is set by getTgtMemInstrinsic 2991 TargetLowering::IntrinsicInfo Info; 2992 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic); 2993 2994 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 2995 if (!IsTgtIntrinsic) 2996 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy())); 2997 2998 // Add all operands of the call to the operand list. 2999 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 3000 SDValue Op = getValue(I.getOperand(i)); 3001 assert(TLI.isTypeLegal(Op.getValueType()) && 3002 "Intrinsic uses a non-legal type?"); 3003 Ops.push_back(Op); 3004 } 3005 3006 SmallVector<EVT, 4> ValueVTs; 3007 ComputeValueVTs(TLI, I.getType(), ValueVTs); 3008 #ifndef NDEBUG 3009 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) { 3010 assert(TLI.isTypeLegal(ValueVTs[Val]) && 3011 "Intrinsic uses a non-legal type?"); 3012 } 3013 #endif // NDEBUG 3014 3015 if (HasChain) 3016 ValueVTs.push_back(MVT::Other); 3017 3018 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size()); 3019 3020 // Create the node. 3021 SDValue Result; 3022 if (IsTgtIntrinsic) { 3023 // This is target intrinsic that touches memory 3024 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(), 3025 VTs, &Ops[0], Ops.size(), 3026 Info.memVT, Info.ptrVal, Info.offset, 3027 Info.align, Info.vol, 3028 Info.readMem, Info.writeMem); 3029 } else if (!HasChain) { 3030 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(), 3031 VTs, &Ops[0], Ops.size()); 3032 } else if (!I.getType()->isVoidTy()) { 3033 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(), 3034 VTs, &Ops[0], Ops.size()); 3035 } else { 3036 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(), 3037 VTs, &Ops[0], Ops.size()); 3038 } 3039 3040 DAG.AssignOrdering(Result.getNode(), SDNodeOrder); 3041 3042 if (HasChain) { 3043 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 3044 if (OnlyLoad) 3045 PendingLoads.push_back(Chain); 3046 else 3047 DAG.setRoot(Chain); 3048 } 3049 3050 if (!I.getType()->isVoidTy()) { 3051 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 3052 EVT VT = TLI.getValueType(PTy); 3053 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result); 3054 DAG.AssignOrdering(Result.getNode(), SDNodeOrder); 3055 } 3056 3057 setValue(&I, Result); 3058 } 3059 } 3060 3061 /// GetSignificand - Get the significand and build it into a floating-point 3062 /// number with exponent of 1: 3063 /// 3064 /// Op = (Op & 0x007fffff) | 0x3f800000; 3065 /// 3066 /// where Op is the hexidecimal representation of floating point value. 3067 static SDValue 3068 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl, unsigned Order) { 3069 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3070 DAG.getConstant(0x007fffff, MVT::i32)); 3071 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 3072 DAG.getConstant(0x3f800000, MVT::i32)); 3073 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2); 3074 3075 DAG.AssignOrdering(t1.getNode(), Order); 3076 DAG.AssignOrdering(t2.getNode(), Order); 3077 DAG.AssignOrdering(Res.getNode(), Order); 3078 return Res; 3079 } 3080 3081 /// GetExponent - Get the exponent: 3082 /// 3083 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 3084 /// 3085 /// where Op is the hexidecimal representation of floating point value. 3086 static SDValue 3087 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, 3088 DebugLoc dl, unsigned Order) { 3089 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3090 DAG.getConstant(0x7f800000, MVT::i32)); 3091 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0, 3092 DAG.getConstant(23, TLI.getPointerTy())); 3093 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 3094 DAG.getConstant(127, MVT::i32)); 3095 SDValue Res = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 3096 3097 DAG.AssignOrdering(t0.getNode(), Order); 3098 DAG.AssignOrdering(t1.getNode(), Order); 3099 DAG.AssignOrdering(t2.getNode(), Order); 3100 DAG.AssignOrdering(Res.getNode(), Order); 3101 return Res; 3102 } 3103 3104 /// getF32Constant - Get 32-bit floating point constant. 3105 static SDValue 3106 getF32Constant(SelectionDAG &DAG, unsigned Flt) { 3107 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32); 3108 } 3109 3110 /// Inlined utility function to implement binary input atomic intrinsics for 3111 /// visitIntrinsicCall: I is a call instruction 3112 /// Op is the associated NodeType for I 3113 const char * 3114 SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) { 3115 SDValue Root = getRoot(); 3116 SDValue L = 3117 DAG.getAtomic(Op, getCurDebugLoc(), 3118 getValue(I.getOperand(2)).getValueType().getSimpleVT(), 3119 Root, 3120 getValue(I.getOperand(1)), 3121 getValue(I.getOperand(2)), 3122 I.getOperand(1)); 3123 setValue(&I, L); 3124 DAG.setRoot(L.getValue(1)); 3125 DAG.AssignOrdering(L.getNode(), SDNodeOrder); 3126 return 0; 3127 } 3128 3129 // implVisitAluOverflow - Lower arithmetic overflow instrinsics. 3130 const char * 3131 SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) { 3132 SDValue Op1 = getValue(I.getOperand(1)); 3133 SDValue Op2 = getValue(I.getOperand(2)); 3134 3135 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 3136 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2); 3137 3138 setValue(&I, Result); 3139 DAG.AssignOrdering(Result.getNode(), SDNodeOrder); 3140 return 0; 3141 } 3142 3143 /// visitExp - Lower an exp intrinsic. Handles the special sequences for 3144 /// limited-precision mode. 3145 void 3146 SelectionDAGBuilder::visitExp(CallInst &I) { 3147 SDValue result; 3148 DebugLoc dl = getCurDebugLoc(); 3149 3150 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3151 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3152 SDValue Op = getValue(I.getOperand(1)); 3153 3154 // Put the exponent in the right bit position for later addition to the 3155 // final result: 3156 // 3157 // #define LOG2OFe 1.4426950f 3158 // IntegerPartOfX = ((int32_t)(X * LOG2OFe)); 3159 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3160 getF32Constant(DAG, 0x3fb8aa3b)); 3161 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3162 3163 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX; 3164 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3165 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3166 3167 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3168 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder); 3169 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3170 DAG.AssignOrdering(X.getNode(), SDNodeOrder); 3171 3172 // IntegerPartOfX <<= 23; 3173 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3174 DAG.getConstant(23, TLI.getPointerTy())); 3175 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder); 3176 3177 if (LimitFloatPrecision <= 6) { 3178 // For floating-point precision of 6: 3179 // 3180 // TwoToFractionalPartOfX = 3181 // 0.997535578f + 3182 // (0.735607626f + 0.252464424f * x) * x; 3183 // 3184 // error 0.0144103317, which is 6 bits 3185 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3186 getF32Constant(DAG, 0x3e814304)); 3187 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3188 getF32Constant(DAG, 0x3f3c50c8)); 3189 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3190 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3191 getF32Constant(DAG, 0x3f7f5e7e)); 3192 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5); 3193 3194 // Add the exponent into the result in integer domain. 3195 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3196 TwoToFracPartOfX, IntegerPartOfX); 3197 3198 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6); 3199 3200 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3201 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3202 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3203 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3204 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3205 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder); 3206 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3207 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3208 // For floating-point precision of 12: 3209 // 3210 // TwoToFractionalPartOfX = 3211 // 0.999892986f + 3212 // (0.696457318f + 3213 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3214 // 3215 // 0.000107046256 error, which is 13 to 14 bits 3216 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3217 getF32Constant(DAG, 0x3da235e3)); 3218 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3219 getF32Constant(DAG, 0x3e65b8f3)); 3220 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3221 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3222 getF32Constant(DAG, 0x3f324b07)); 3223 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3224 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3225 getF32Constant(DAG, 0x3f7ff8fd)); 3226 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7); 3227 3228 // Add the exponent into the result in integer domain. 3229 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3230 TwoToFracPartOfX, IntegerPartOfX); 3231 3232 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8); 3233 3234 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3235 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3236 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3237 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3238 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3239 DAG.AssignOrdering(t7.getNode(), SDNodeOrder); 3240 DAG.AssignOrdering(t8.getNode(), SDNodeOrder); 3241 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder); 3242 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3243 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3244 // For floating-point precision of 18: 3245 // 3246 // TwoToFractionalPartOfX = 3247 // 0.999999982f + 3248 // (0.693148872f + 3249 // (0.240227044f + 3250 // (0.554906021e-1f + 3251 // (0.961591928e-2f + 3252 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3253 // 3254 // error 2.47208000*10^(-7), which is better than 18 bits 3255 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3256 getF32Constant(DAG, 0x3924b03e)); 3257 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3258 getF32Constant(DAG, 0x3ab24b87)); 3259 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3260 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3261 getF32Constant(DAG, 0x3c1d8c17)); 3262 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3263 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3264 getF32Constant(DAG, 0x3d634a1d)); 3265 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3266 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3267 getF32Constant(DAG, 0x3e75fe14)); 3268 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3269 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3270 getF32Constant(DAG, 0x3f317234)); 3271 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3272 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3273 getF32Constant(DAG, 0x3f800000)); 3274 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl, 3275 MVT::i32, t13); 3276 3277 // Add the exponent into the result in integer domain. 3278 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3279 TwoToFracPartOfX, IntegerPartOfX); 3280 3281 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14); 3282 3283 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3284 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3285 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3286 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3287 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3288 DAG.AssignOrdering(t7.getNode(), SDNodeOrder); 3289 DAG.AssignOrdering(t8.getNode(), SDNodeOrder); 3290 DAG.AssignOrdering(t9.getNode(), SDNodeOrder); 3291 DAG.AssignOrdering(t10.getNode(), SDNodeOrder); 3292 DAG.AssignOrdering(t11.getNode(), SDNodeOrder); 3293 DAG.AssignOrdering(t12.getNode(), SDNodeOrder); 3294 DAG.AssignOrdering(t13.getNode(), SDNodeOrder); 3295 DAG.AssignOrdering(t14.getNode(), SDNodeOrder); 3296 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder); 3297 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3298 } 3299 } else { 3300 // No special expansion. 3301 result = DAG.getNode(ISD::FEXP, dl, 3302 getValue(I.getOperand(1)).getValueType(), 3303 getValue(I.getOperand(1))); 3304 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3305 } 3306 3307 setValue(&I, result); 3308 } 3309 3310 /// visitLog - Lower a log intrinsic. Handles the special sequences for 3311 /// limited-precision mode. 3312 void 3313 SelectionDAGBuilder::visitLog(CallInst &I) { 3314 SDValue result; 3315 DebugLoc dl = getCurDebugLoc(); 3316 3317 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3318 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3319 SDValue Op = getValue(I.getOperand(1)); 3320 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op); 3321 3322 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder); 3323 3324 // Scale the exponent by log(2) [0.69314718f]. 3325 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder); 3326 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3327 getF32Constant(DAG, 0x3f317218)); 3328 3329 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder); 3330 3331 // Get the significand and build it into a floating-point number with 3332 // exponent of 1. 3333 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder); 3334 3335 if (LimitFloatPrecision <= 6) { 3336 // For floating-point precision of 6: 3337 // 3338 // LogofMantissa = 3339 // -1.1609546f + 3340 // (1.4034025f - 0.23903021f * x) * x; 3341 // 3342 // error 0.0034276066, which is better than 8 bits 3343 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3344 getF32Constant(DAG, 0xbe74c456)); 3345 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3346 getF32Constant(DAG, 0x3fb3a2b1)); 3347 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3348 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3349 getF32Constant(DAG, 0x3f949a29)); 3350 3351 result = DAG.getNode(ISD::FADD, dl, 3352 MVT::f32, LogOfExponent, LogOfMantissa); 3353 3354 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3355 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3356 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3357 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder); 3358 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3359 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3360 // For floating-point precision of 12: 3361 // 3362 // LogOfMantissa = 3363 // -1.7417939f + 3364 // (2.8212026f + 3365 // (-1.4699568f + 3366 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 3367 // 3368 // error 0.000061011436, which is 14 bits 3369 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3370 getF32Constant(DAG, 0xbd67b6d6)); 3371 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3372 getF32Constant(DAG, 0x3ee4f4b8)); 3373 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3374 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3375 getF32Constant(DAG, 0x3fbc278b)); 3376 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3377 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3378 getF32Constant(DAG, 0x40348e95)); 3379 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3380 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3381 getF32Constant(DAG, 0x3fdef31a)); 3382 3383 result = DAG.getNode(ISD::FADD, dl, 3384 MVT::f32, LogOfExponent, LogOfMantissa); 3385 3386 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3387 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3388 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3389 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3390 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3391 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3392 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3393 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder); 3394 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3395 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3396 // For floating-point precision of 18: 3397 // 3398 // LogOfMantissa = 3399 // -2.1072184f + 3400 // (4.2372794f + 3401 // (-3.7029485f + 3402 // (2.2781945f + 3403 // (-0.87823314f + 3404 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 3405 // 3406 // error 0.0000023660568, which is better than 18 bits 3407 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3408 getF32Constant(DAG, 0xbc91e5ac)); 3409 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3410 getF32Constant(DAG, 0x3e4350aa)); 3411 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3412 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3413 getF32Constant(DAG, 0x3f60d3e3)); 3414 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3415 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3416 getF32Constant(DAG, 0x4011cdf0)); 3417 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3418 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3419 getF32Constant(DAG, 0x406cfd1c)); 3420 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3421 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3422 getF32Constant(DAG, 0x408797cb)); 3423 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3424 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3425 getF32Constant(DAG, 0x4006dcab)); 3426 3427 result = DAG.getNode(ISD::FADD, dl, 3428 MVT::f32, LogOfExponent, LogOfMantissa); 3429 3430 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3431 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3432 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3433 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3434 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3435 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3436 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3437 DAG.AssignOrdering(t7.getNode(), SDNodeOrder); 3438 DAG.AssignOrdering(t8.getNode(), SDNodeOrder); 3439 DAG.AssignOrdering(t9.getNode(), SDNodeOrder); 3440 DAG.AssignOrdering(t10.getNode(), SDNodeOrder); 3441 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder); 3442 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3443 } 3444 } else { 3445 // No special expansion. 3446 result = DAG.getNode(ISD::FLOG, dl, 3447 getValue(I.getOperand(1)).getValueType(), 3448 getValue(I.getOperand(1))); 3449 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3450 } 3451 3452 setValue(&I, result); 3453 } 3454 3455 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for 3456 /// limited-precision mode. 3457 void 3458 SelectionDAGBuilder::visitLog2(CallInst &I) { 3459 SDValue result; 3460 DebugLoc dl = getCurDebugLoc(); 3461 3462 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3463 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3464 SDValue Op = getValue(I.getOperand(1)); 3465 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op); 3466 3467 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder); 3468 3469 // Get the exponent. 3470 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder); 3471 3472 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder); 3473 3474 // Get the significand and build it into a floating-point number with 3475 // exponent of 1. 3476 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder); 3477 3478 // Different possible minimax approximations of significand in 3479 // floating-point for various degrees of accuracy over [1,2]. 3480 if (LimitFloatPrecision <= 6) { 3481 // For floating-point precision of 6: 3482 // 3483 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 3484 // 3485 // error 0.0049451742, which is more than 7 bits 3486 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3487 getF32Constant(DAG, 0xbeb08fe0)); 3488 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3489 getF32Constant(DAG, 0x40019463)); 3490 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3491 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3492 getF32Constant(DAG, 0x3fd6633d)); 3493 3494 result = DAG.getNode(ISD::FADD, dl, 3495 MVT::f32, LogOfExponent, Log2ofMantissa); 3496 3497 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3498 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3499 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3500 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder); 3501 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3502 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3503 // For floating-point precision of 12: 3504 // 3505 // Log2ofMantissa = 3506 // -2.51285454f + 3507 // (4.07009056f + 3508 // (-2.12067489f + 3509 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 3510 // 3511 // error 0.0000876136000, which is better than 13 bits 3512 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3513 getF32Constant(DAG, 0xbda7262e)); 3514 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3515 getF32Constant(DAG, 0x3f25280b)); 3516 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3517 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3518 getF32Constant(DAG, 0x4007b923)); 3519 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3520 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3521 getF32Constant(DAG, 0x40823e2f)); 3522 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3523 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3524 getF32Constant(DAG, 0x4020d29c)); 3525 3526 result = DAG.getNode(ISD::FADD, dl, 3527 MVT::f32, LogOfExponent, Log2ofMantissa); 3528 3529 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3530 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3531 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3532 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3533 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3534 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3535 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3536 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder); 3537 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3538 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3539 // For floating-point precision of 18: 3540 // 3541 // Log2ofMantissa = 3542 // -3.0400495f + 3543 // (6.1129976f + 3544 // (-5.3420409f + 3545 // (3.2865683f + 3546 // (-1.2669343f + 3547 // (0.27515199f - 3548 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 3549 // 3550 // error 0.0000018516, which is better than 18 bits 3551 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3552 getF32Constant(DAG, 0xbcd2769e)); 3553 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3554 getF32Constant(DAG, 0x3e8ce0b9)); 3555 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3556 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3557 getF32Constant(DAG, 0x3fa22ae7)); 3558 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3559 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3560 getF32Constant(DAG, 0x40525723)); 3561 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3562 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3563 getF32Constant(DAG, 0x40aaf200)); 3564 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3565 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3566 getF32Constant(DAG, 0x40c39dad)); 3567 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3568 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3569 getF32Constant(DAG, 0x4042902c)); 3570 3571 result = DAG.getNode(ISD::FADD, dl, 3572 MVT::f32, LogOfExponent, Log2ofMantissa); 3573 3574 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3575 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3576 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3577 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3578 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3579 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3580 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3581 DAG.AssignOrdering(t7.getNode(), SDNodeOrder); 3582 DAG.AssignOrdering(t8.getNode(), SDNodeOrder); 3583 DAG.AssignOrdering(t9.getNode(), SDNodeOrder); 3584 DAG.AssignOrdering(t10.getNode(), SDNodeOrder); 3585 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder); 3586 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3587 } 3588 } else { 3589 // No special expansion. 3590 result = DAG.getNode(ISD::FLOG2, dl, 3591 getValue(I.getOperand(1)).getValueType(), 3592 getValue(I.getOperand(1))); 3593 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3594 } 3595 3596 setValue(&I, result); 3597 } 3598 3599 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for 3600 /// limited-precision mode. 3601 void 3602 SelectionDAGBuilder::visitLog10(CallInst &I) { 3603 SDValue result; 3604 DebugLoc dl = getCurDebugLoc(); 3605 3606 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3607 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3608 SDValue Op = getValue(I.getOperand(1)); 3609 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op); 3610 3611 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder); 3612 3613 // Scale the exponent by log10(2) [0.30102999f]. 3614 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder); 3615 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3616 getF32Constant(DAG, 0x3e9a209a)); 3617 3618 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder); 3619 3620 // Get the significand and build it into a floating-point number with 3621 // exponent of 1. 3622 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder); 3623 3624 if (LimitFloatPrecision <= 6) { 3625 // For floating-point precision of 6: 3626 // 3627 // Log10ofMantissa = 3628 // -0.50419619f + 3629 // (0.60948995f - 0.10380950f * x) * x; 3630 // 3631 // error 0.0014886165, which is 6 bits 3632 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3633 getF32Constant(DAG, 0xbdd49a13)); 3634 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3635 getF32Constant(DAG, 0x3f1c0789)); 3636 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3637 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3638 getF32Constant(DAG, 0x3f011300)); 3639 3640 result = DAG.getNode(ISD::FADD, dl, 3641 MVT::f32, LogOfExponent, Log10ofMantissa); 3642 3643 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3644 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3645 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3646 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder); 3647 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3648 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3649 // For floating-point precision of 12: 3650 // 3651 // Log10ofMantissa = 3652 // -0.64831180f + 3653 // (0.91751397f + 3654 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 3655 // 3656 // error 0.00019228036, which is better than 12 bits 3657 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3658 getF32Constant(DAG, 0x3d431f31)); 3659 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3660 getF32Constant(DAG, 0x3ea21fb2)); 3661 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3662 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3663 getF32Constant(DAG, 0x3f6ae232)); 3664 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3665 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3666 getF32Constant(DAG, 0x3f25f7c3)); 3667 3668 result = DAG.getNode(ISD::FADD, dl, 3669 MVT::f32, LogOfExponent, Log10ofMantissa); 3670 3671 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3672 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3673 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3674 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3675 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3676 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder); 3677 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3678 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3679 // For floating-point precision of 18: 3680 // 3681 // Log10ofMantissa = 3682 // -0.84299375f + 3683 // (1.5327582f + 3684 // (-1.0688956f + 3685 // (0.49102474f + 3686 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 3687 // 3688 // error 0.0000037995730, which is better than 18 bits 3689 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3690 getF32Constant(DAG, 0x3c5d51ce)); 3691 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3692 getF32Constant(DAG, 0x3e00685a)); 3693 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3694 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3695 getF32Constant(DAG, 0x3efb6798)); 3696 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3697 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3698 getF32Constant(DAG, 0x3f88d192)); 3699 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3700 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3701 getF32Constant(DAG, 0x3fc4316c)); 3702 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3703 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 3704 getF32Constant(DAG, 0x3f57ce70)); 3705 3706 result = DAG.getNode(ISD::FADD, dl, 3707 MVT::f32, LogOfExponent, Log10ofMantissa); 3708 3709 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3710 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3711 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3712 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3713 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3714 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3715 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3716 DAG.AssignOrdering(t7.getNode(), SDNodeOrder); 3717 DAG.AssignOrdering(t8.getNode(), SDNodeOrder); 3718 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder); 3719 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3720 } 3721 } else { 3722 // No special expansion. 3723 result = DAG.getNode(ISD::FLOG10, dl, 3724 getValue(I.getOperand(1)).getValueType(), 3725 getValue(I.getOperand(1))); 3726 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3727 } 3728 3729 setValue(&I, result); 3730 } 3731 3732 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for 3733 /// limited-precision mode. 3734 void 3735 SelectionDAGBuilder::visitExp2(CallInst &I) { 3736 SDValue result; 3737 DebugLoc dl = getCurDebugLoc(); 3738 3739 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3740 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3741 SDValue Op = getValue(I.getOperand(1)); 3742 3743 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op); 3744 3745 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder); 3746 3747 // FractionalPartOfX = x - (float)IntegerPartOfX; 3748 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3749 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1); 3750 3751 // IntegerPartOfX <<= 23; 3752 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3753 DAG.getConstant(23, TLI.getPointerTy())); 3754 3755 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3756 DAG.AssignOrdering(X.getNode(), SDNodeOrder); 3757 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder); 3758 3759 if (LimitFloatPrecision <= 6) { 3760 // For floating-point precision of 6: 3761 // 3762 // TwoToFractionalPartOfX = 3763 // 0.997535578f + 3764 // (0.735607626f + 0.252464424f * x) * x; 3765 // 3766 // error 0.0144103317, which is 6 bits 3767 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3768 getF32Constant(DAG, 0x3e814304)); 3769 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3770 getF32Constant(DAG, 0x3f3c50c8)); 3771 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3772 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3773 getF32Constant(DAG, 0x3f7f5e7e)); 3774 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5); 3775 SDValue TwoToFractionalPartOfX = 3776 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX); 3777 3778 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3779 MVT::f32, TwoToFractionalPartOfX); 3780 3781 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3782 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3783 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3784 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3785 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3786 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder); 3787 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3788 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3789 // For floating-point precision of 12: 3790 // 3791 // TwoToFractionalPartOfX = 3792 // 0.999892986f + 3793 // (0.696457318f + 3794 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3795 // 3796 // error 0.000107046256, which is 13 to 14 bits 3797 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3798 getF32Constant(DAG, 0x3da235e3)); 3799 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3800 getF32Constant(DAG, 0x3e65b8f3)); 3801 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3802 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3803 getF32Constant(DAG, 0x3f324b07)); 3804 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3805 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3806 getF32Constant(DAG, 0x3f7ff8fd)); 3807 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7); 3808 SDValue TwoToFractionalPartOfX = 3809 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX); 3810 3811 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3812 MVT::f32, TwoToFractionalPartOfX); 3813 3814 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3815 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3816 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3817 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3818 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3819 DAG.AssignOrdering(t7.getNode(), SDNodeOrder); 3820 DAG.AssignOrdering(t8.getNode(), SDNodeOrder); 3821 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder); 3822 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3823 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3824 // For floating-point precision of 18: 3825 // 3826 // TwoToFractionalPartOfX = 3827 // 0.999999982f + 3828 // (0.693148872f + 3829 // (0.240227044f + 3830 // (0.554906021e-1f + 3831 // (0.961591928e-2f + 3832 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3833 // error 2.47208000*10^(-7), which is better than 18 bits 3834 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3835 getF32Constant(DAG, 0x3924b03e)); 3836 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3837 getF32Constant(DAG, 0x3ab24b87)); 3838 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3839 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3840 getF32Constant(DAG, 0x3c1d8c17)); 3841 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3842 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3843 getF32Constant(DAG, 0x3d634a1d)); 3844 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3845 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3846 getF32Constant(DAG, 0x3e75fe14)); 3847 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3848 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3849 getF32Constant(DAG, 0x3f317234)); 3850 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3851 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3852 getF32Constant(DAG, 0x3f800000)); 3853 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13); 3854 SDValue TwoToFractionalPartOfX = 3855 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX); 3856 3857 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3858 MVT::f32, TwoToFractionalPartOfX); 3859 3860 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3861 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3862 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3863 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3864 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3865 DAG.AssignOrdering(t7.getNode(), SDNodeOrder); 3866 DAG.AssignOrdering(t8.getNode(), SDNodeOrder); 3867 DAG.AssignOrdering(t9.getNode(), SDNodeOrder); 3868 DAG.AssignOrdering(t10.getNode(), SDNodeOrder); 3869 DAG.AssignOrdering(t11.getNode(), SDNodeOrder); 3870 DAG.AssignOrdering(t12.getNode(), SDNodeOrder); 3871 DAG.AssignOrdering(t13.getNode(), SDNodeOrder); 3872 DAG.AssignOrdering(t14.getNode(), SDNodeOrder); 3873 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder); 3874 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3875 } 3876 } else { 3877 // No special expansion. 3878 result = DAG.getNode(ISD::FEXP2, dl, 3879 getValue(I.getOperand(1)).getValueType(), 3880 getValue(I.getOperand(1))); 3881 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3882 } 3883 3884 setValue(&I, result); 3885 } 3886 3887 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 3888 /// limited-precision mode with x == 10.0f. 3889 void 3890 SelectionDAGBuilder::visitPow(CallInst &I) { 3891 SDValue result; 3892 Value *Val = I.getOperand(1); 3893 DebugLoc dl = getCurDebugLoc(); 3894 bool IsExp10 = false; 3895 3896 if (getValue(Val).getValueType() == MVT::f32 && 3897 getValue(I.getOperand(2)).getValueType() == MVT::f32 && 3898 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3899 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) { 3900 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 3901 APFloat Ten(10.0f); 3902 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten); 3903 } 3904 } 3905 } 3906 3907 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3908 SDValue Op = getValue(I.getOperand(2)); 3909 3910 // Put the exponent in the right bit position for later addition to the 3911 // final result: 3912 // 3913 // #define LOG2OF10 3.3219281f 3914 // IntegerPartOfX = (int32_t)(x * LOG2OF10); 3915 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3916 getF32Constant(DAG, 0x40549a78)); 3917 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3918 3919 // FractionalPartOfX = x - (float)IntegerPartOfX; 3920 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3921 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3922 3923 DAG.AssignOrdering(t0.getNode(), SDNodeOrder); 3924 DAG.AssignOrdering(t1.getNode(), SDNodeOrder); 3925 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder); 3926 DAG.AssignOrdering(X.getNode(), SDNodeOrder); 3927 3928 // IntegerPartOfX <<= 23; 3929 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3930 DAG.getConstant(23, TLI.getPointerTy())); 3931 3932 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder); 3933 3934 if (LimitFloatPrecision <= 6) { 3935 // For floating-point precision of 6: 3936 // 3937 // twoToFractionalPartOfX = 3938 // 0.997535578f + 3939 // (0.735607626f + 0.252464424f * x) * x; 3940 // 3941 // error 0.0144103317, which is 6 bits 3942 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3943 getF32Constant(DAG, 0x3e814304)); 3944 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3945 getF32Constant(DAG, 0x3f3c50c8)); 3946 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3947 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3948 getF32Constant(DAG, 0x3f7f5e7e)); 3949 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5); 3950 SDValue TwoToFractionalPartOfX = 3951 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX); 3952 3953 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3954 MVT::f32, TwoToFractionalPartOfX); 3955 3956 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3957 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3958 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3959 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3960 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3961 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder); 3962 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3963 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3964 // For floating-point precision of 12: 3965 // 3966 // TwoToFractionalPartOfX = 3967 // 0.999892986f + 3968 // (0.696457318f + 3969 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3970 // 3971 // error 0.000107046256, which is 13 to 14 bits 3972 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3973 getF32Constant(DAG, 0x3da235e3)); 3974 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3975 getF32Constant(DAG, 0x3e65b8f3)); 3976 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3977 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3978 getF32Constant(DAG, 0x3f324b07)); 3979 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3980 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3981 getF32Constant(DAG, 0x3f7ff8fd)); 3982 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7); 3983 SDValue TwoToFractionalPartOfX = 3984 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX); 3985 3986 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3987 MVT::f32, TwoToFractionalPartOfX); 3988 3989 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 3990 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 3991 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 3992 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 3993 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 3994 DAG.AssignOrdering(t7.getNode(), SDNodeOrder); 3995 DAG.AssignOrdering(t8.getNode(), SDNodeOrder); 3996 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder); 3997 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 3998 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3999 // For floating-point precision of 18: 4000 // 4001 // TwoToFractionalPartOfX = 4002 // 0.999999982f + 4003 // (0.693148872f + 4004 // (0.240227044f + 4005 // (0.554906021e-1f + 4006 // (0.961591928e-2f + 4007 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4008 // error 2.47208000*10^(-7), which is better than 18 bits 4009 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4010 getF32Constant(DAG, 0x3924b03e)); 4011 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4012 getF32Constant(DAG, 0x3ab24b87)); 4013 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4014 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4015 getF32Constant(DAG, 0x3c1d8c17)); 4016 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4017 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4018 getF32Constant(DAG, 0x3d634a1d)); 4019 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4020 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4021 getF32Constant(DAG, 0x3e75fe14)); 4022 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4023 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4024 getF32Constant(DAG, 0x3f317234)); 4025 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4026 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4027 getF32Constant(DAG, 0x3f800000)); 4028 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13); 4029 SDValue TwoToFractionalPartOfX = 4030 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX); 4031 4032 result = DAG.getNode(ISD::BIT_CONVERT, dl, 4033 MVT::f32, TwoToFractionalPartOfX); 4034 4035 DAG.AssignOrdering(t2.getNode(), SDNodeOrder); 4036 DAG.AssignOrdering(t3.getNode(), SDNodeOrder); 4037 DAG.AssignOrdering(t4.getNode(), SDNodeOrder); 4038 DAG.AssignOrdering(t5.getNode(), SDNodeOrder); 4039 DAG.AssignOrdering(t6.getNode(), SDNodeOrder); 4040 DAG.AssignOrdering(t7.getNode(), SDNodeOrder); 4041 DAG.AssignOrdering(t8.getNode(), SDNodeOrder); 4042 DAG.AssignOrdering(t9.getNode(), SDNodeOrder); 4043 DAG.AssignOrdering(t10.getNode(), SDNodeOrder); 4044 DAG.AssignOrdering(t11.getNode(), SDNodeOrder); 4045 DAG.AssignOrdering(t12.getNode(), SDNodeOrder); 4046 DAG.AssignOrdering(t13.getNode(), SDNodeOrder); 4047 DAG.AssignOrdering(t14.getNode(), SDNodeOrder); 4048 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder); 4049 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 4050 } 4051 } else { 4052 // No special expansion. 4053 result = DAG.getNode(ISD::FPOW, dl, 4054 getValue(I.getOperand(1)).getValueType(), 4055 getValue(I.getOperand(1)), 4056 getValue(I.getOperand(2))); 4057 DAG.AssignOrdering(result.getNode(), SDNodeOrder); 4058 } 4059 4060 setValue(&I, result); 4061 } 4062 4063 4064 /// ExpandPowI - Expand a llvm.powi intrinsic. 4065 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS, 4066 SelectionDAG &DAG) { 4067 // If RHS is a constant, we can expand this out to a multiplication tree, 4068 // otherwise we end up lowering to a call to __powidf2 (for example). When 4069 // optimizing for size, we only want to do this if the expansion would produce 4070 // a small number of multiplies, otherwise we do the full expansion. 4071 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4072 // Get the exponent as a positive value. 4073 unsigned Val = RHSC->getSExtValue(); 4074 if ((int)Val < 0) Val = -Val; 4075 4076 // powi(x, 0) -> 1.0 4077 if (Val == 0) 4078 return DAG.getConstantFP(1.0, LHS.getValueType()); 4079 4080 Function *F = DAG.getMachineFunction().getFunction(); 4081 if (!F->hasFnAttr(Attribute::OptimizeForSize) || 4082 // If optimizing for size, don't insert too many multiplies. This 4083 // inserts up to 5 multiplies. 4084 CountPopulation_32(Val)+Log2_32(Val) < 7) { 4085 // We use the simple binary decomposition method to generate the multiply 4086 // sequence. There are more optimal ways to do this (for example, 4087 // powi(x,15) generates one more multiply than it should), but this has 4088 // the benefit of being both really simple and much better than a libcall. 4089 SDValue Res; // Logically starts equal to 1.0 4090 SDValue CurSquare = LHS; 4091 while (Val) { 4092 if (Val & 1) { 4093 if (Res.getNode()) 4094 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4095 else 4096 Res = CurSquare; // 1.0*CurSquare. 4097 } 4098 4099 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4100 CurSquare, CurSquare); 4101 Val >>= 1; 4102 } 4103 4104 // If the original was negative, invert the result, producing 1/(x*x*x). 4105 if (RHSC->getSExtValue() < 0) 4106 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4107 DAG.getConstantFP(1.0, LHS.getValueType()), Res); 4108 return Res; 4109 } 4110 } 4111 4112 // Otherwise, expand to a libcall. 4113 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4114 } 4115 4116 4117 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 4118 /// we want to emit this as a call to a named external function, return the name 4119 /// otherwise lower it and return null. 4120 const char * 4121 SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) { 4122 DebugLoc dl = getCurDebugLoc(); 4123 SDValue Res; 4124 4125 switch (Intrinsic) { 4126 default: 4127 // By default, turn this into a target intrinsic node. 4128 visitTargetIntrinsic(I, Intrinsic); 4129 return 0; 4130 case Intrinsic::vastart: visitVAStart(I); return 0; 4131 case Intrinsic::vaend: visitVAEnd(I); return 0; 4132 case Intrinsic::vacopy: visitVACopy(I); return 0; 4133 case Intrinsic::returnaddress: 4134 Res = DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(), 4135 getValue(I.getOperand(1))); 4136 setValue(&I, Res); 4137 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4138 return 0; 4139 case Intrinsic::frameaddress: 4140 Res = DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(), 4141 getValue(I.getOperand(1))); 4142 setValue(&I, Res); 4143 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4144 return 0; 4145 case Intrinsic::setjmp: 4146 return "_setjmp"+!TLI.usesUnderscoreSetJmp(); 4147 case Intrinsic::longjmp: 4148 return "_longjmp"+!TLI.usesUnderscoreLongJmp(); 4149 case Intrinsic::memcpy: { 4150 SDValue Op1 = getValue(I.getOperand(1)); 4151 SDValue Op2 = getValue(I.getOperand(2)); 4152 SDValue Op3 = getValue(I.getOperand(3)); 4153 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 4154 Res = DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false, 4155 I.getOperand(1), 0, I.getOperand(2), 0); 4156 DAG.setRoot(Res); 4157 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4158 return 0; 4159 } 4160 case Intrinsic::memset: { 4161 SDValue Op1 = getValue(I.getOperand(1)); 4162 SDValue Op2 = getValue(I.getOperand(2)); 4163 SDValue Op3 = getValue(I.getOperand(3)); 4164 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 4165 Res = DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, 4166 I.getOperand(1), 0); 4167 DAG.setRoot(Res); 4168 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4169 return 0; 4170 } 4171 case Intrinsic::memmove: { 4172 SDValue Op1 = getValue(I.getOperand(1)); 4173 SDValue Op2 = getValue(I.getOperand(2)); 4174 SDValue Op3 = getValue(I.getOperand(3)); 4175 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 4176 4177 // If the source and destination are known to not be aliases, we can 4178 // lower memmove as memcpy. 4179 uint64_t Size = -1ULL; 4180 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3)) 4181 Size = C->getZExtValue(); 4182 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) == 4183 AliasAnalysis::NoAlias) { 4184 Res = DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false, 4185 I.getOperand(1), 0, I.getOperand(2), 0); 4186 DAG.setRoot(Res); 4187 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4188 return 0; 4189 } 4190 4191 Res = DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, 4192 I.getOperand(1), 0, I.getOperand(2), 0); 4193 DAG.setRoot(Res); 4194 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4195 return 0; 4196 } 4197 case Intrinsic::dbg_declare: { 4198 if (OptLevel != CodeGenOpt::None) 4199 // FIXME: Variable debug info is not supported here. 4200 return 0; 4201 DwarfWriter *DW = DAG.getDwarfWriter(); 4202 if (!DW) 4203 return 0; 4204 DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 4205 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None)) 4206 return 0; 4207 4208 MDNode *Variable = DI.getVariable(); 4209 Value *Address = DI.getAddress(); 4210 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 4211 Address = BCI->getOperand(0); 4212 AllocaInst *AI = dyn_cast<AllocaInst>(Address); 4213 // Don't handle byval struct arguments or VLAs, for example. 4214 if (!AI) 4215 return 0; 4216 DenseMap<const AllocaInst*, int>::iterator SI = 4217 FuncInfo.StaticAllocaMap.find(AI); 4218 if (SI == FuncInfo.StaticAllocaMap.end()) 4219 return 0; // VLAs. 4220 int FI = SI->second; 4221 4222 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) 4223 if (MDNode *Dbg = DI.getMetadata("dbg")) 4224 MMI->setVariableDbgInfo(Variable, FI, Dbg); 4225 return 0; 4226 } 4227 case Intrinsic::eh_exception: { 4228 // Insert the EXCEPTIONADDR instruction. 4229 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!"); 4230 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 4231 SDValue Ops[1]; 4232 Ops[0] = DAG.getRoot(); 4233 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1); 4234 setValue(&I, Op); 4235 DAG.setRoot(Op.getValue(1)); 4236 DAG.AssignOrdering(Op.getNode(), SDNodeOrder); 4237 return 0; 4238 } 4239 4240 case Intrinsic::eh_selector: { 4241 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 4242 4243 if (CurMBB->isLandingPad()) 4244 AddCatchInfo(I, MMI, CurMBB); 4245 else { 4246 #ifndef NDEBUG 4247 FuncInfo.CatchInfoLost.insert(&I); 4248 #endif 4249 // FIXME: Mark exception selector register as live in. Hack for PR1508. 4250 unsigned Reg = TLI.getExceptionSelectorRegister(); 4251 if (Reg) CurMBB->addLiveIn(Reg); 4252 } 4253 4254 // Insert the EHSELECTION instruction. 4255 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 4256 SDValue Ops[2]; 4257 Ops[0] = getValue(I.getOperand(1)); 4258 Ops[1] = getRoot(); 4259 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2); 4260 4261 DAG.setRoot(Op.getValue(1)); 4262 4263 Res = DAG.getSExtOrTrunc(Op, dl, MVT::i32); 4264 setValue(&I, Res); 4265 DAG.AssignOrdering(Op.getNode(), SDNodeOrder); 4266 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4267 return 0; 4268 } 4269 4270 case Intrinsic::eh_typeid_for: { 4271 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 4272 4273 if (MMI) { 4274 // Find the type id for the given typeinfo. 4275 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1)); 4276 unsigned TypeID = MMI->getTypeIDFor(GV); 4277 Res = DAG.getConstant(TypeID, MVT::i32); 4278 } else { 4279 // Return something different to eh_selector. 4280 Res = DAG.getConstant(1, MVT::i32); 4281 } 4282 4283 setValue(&I, Res); 4284 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4285 return 0; 4286 } 4287 4288 case Intrinsic::eh_return_i32: 4289 case Intrinsic::eh_return_i64: 4290 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) { 4291 MMI->setCallsEHReturn(true); 4292 Res = DAG.getNode(ISD::EH_RETURN, dl, 4293 MVT::Other, 4294 getControlRoot(), 4295 getValue(I.getOperand(1)), 4296 getValue(I.getOperand(2))); 4297 DAG.setRoot(Res); 4298 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4299 } else { 4300 setValue(&I, DAG.getConstant(0, TLI.getPointerTy())); 4301 } 4302 4303 return 0; 4304 case Intrinsic::eh_unwind_init: 4305 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) { 4306 MMI->setCallsUnwindInit(true); 4307 } 4308 return 0; 4309 case Intrinsic::eh_dwarf_cfa: { 4310 EVT VT = getValue(I.getOperand(1)).getValueType(); 4311 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl, 4312 TLI.getPointerTy()); 4313 SDValue Offset = DAG.getNode(ISD::ADD, dl, 4314 TLI.getPointerTy(), 4315 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl, 4316 TLI.getPointerTy()), 4317 CfaArg); 4318 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl, 4319 TLI.getPointerTy(), 4320 DAG.getConstant(0, TLI.getPointerTy())); 4321 Res = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 4322 FA, Offset); 4323 setValue(&I, Res); 4324 DAG.AssignOrdering(CfaArg.getNode(), SDNodeOrder); 4325 DAG.AssignOrdering(Offset.getNode(), SDNodeOrder); 4326 DAG.AssignOrdering(FA.getNode(), SDNodeOrder); 4327 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4328 return 0; 4329 } 4330 case Intrinsic::eh_sjlj_callsite: { 4331 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 4332 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1)); 4333 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 4334 assert(MMI->getCurrentCallSite() == 0 && "Overlapping call sites!"); 4335 4336 MMI->setCurrentCallSite(CI->getZExtValue()); 4337 return 0; 4338 } 4339 4340 case Intrinsic::convertff: 4341 case Intrinsic::convertfsi: 4342 case Intrinsic::convertfui: 4343 case Intrinsic::convertsif: 4344 case Intrinsic::convertuif: 4345 case Intrinsic::convertss: 4346 case Intrinsic::convertsu: 4347 case Intrinsic::convertus: 4348 case Intrinsic::convertuu: { 4349 ISD::CvtCode Code = ISD::CVT_INVALID; 4350 switch (Intrinsic) { 4351 case Intrinsic::convertff: Code = ISD::CVT_FF; break; 4352 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break; 4353 case Intrinsic::convertfui: Code = ISD::CVT_FU; break; 4354 case Intrinsic::convertsif: Code = ISD::CVT_SF; break; 4355 case Intrinsic::convertuif: Code = ISD::CVT_UF; break; 4356 case Intrinsic::convertss: Code = ISD::CVT_SS; break; 4357 case Intrinsic::convertsu: Code = ISD::CVT_SU; break; 4358 case Intrinsic::convertus: Code = ISD::CVT_US; break; 4359 case Intrinsic::convertuu: Code = ISD::CVT_UU; break; 4360 } 4361 EVT DestVT = TLI.getValueType(I.getType()); 4362 Value *Op1 = I.getOperand(1); 4363 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1), 4364 DAG.getValueType(DestVT), 4365 DAG.getValueType(getValue(Op1).getValueType()), 4366 getValue(I.getOperand(2)), 4367 getValue(I.getOperand(3)), 4368 Code); 4369 setValue(&I, Res); 4370 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4371 return 0; 4372 } 4373 case Intrinsic::sqrt: 4374 Res = DAG.getNode(ISD::FSQRT, dl, 4375 getValue(I.getOperand(1)).getValueType(), 4376 getValue(I.getOperand(1))); 4377 setValue(&I, Res); 4378 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4379 return 0; 4380 case Intrinsic::powi: 4381 Res = ExpandPowI(dl, getValue(I.getOperand(1)), getValue(I.getOperand(2)), 4382 DAG); 4383 setValue(&I, Res); 4384 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4385 return 0; 4386 case Intrinsic::sin: 4387 Res = DAG.getNode(ISD::FSIN, dl, 4388 getValue(I.getOperand(1)).getValueType(), 4389 getValue(I.getOperand(1))); 4390 setValue(&I, Res); 4391 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4392 return 0; 4393 case Intrinsic::cos: 4394 Res = DAG.getNode(ISD::FCOS, dl, 4395 getValue(I.getOperand(1)).getValueType(), 4396 getValue(I.getOperand(1))); 4397 setValue(&I, Res); 4398 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4399 return 0; 4400 case Intrinsic::log: 4401 visitLog(I); 4402 return 0; 4403 case Intrinsic::log2: 4404 visitLog2(I); 4405 return 0; 4406 case Intrinsic::log10: 4407 visitLog10(I); 4408 return 0; 4409 case Intrinsic::exp: 4410 visitExp(I); 4411 return 0; 4412 case Intrinsic::exp2: 4413 visitExp2(I); 4414 return 0; 4415 case Intrinsic::pow: 4416 visitPow(I); 4417 return 0; 4418 case Intrinsic::pcmarker: { 4419 SDValue Tmp = getValue(I.getOperand(1)); 4420 Res = DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp); 4421 DAG.setRoot(Res); 4422 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4423 return 0; 4424 } 4425 case Intrinsic::readcyclecounter: { 4426 SDValue Op = getRoot(); 4427 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl, 4428 DAG.getVTList(MVT::i64, MVT::Other), 4429 &Op, 1); 4430 setValue(&I, Res); 4431 DAG.setRoot(Res.getValue(1)); 4432 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4433 return 0; 4434 } 4435 case Intrinsic::bswap: 4436 Res = DAG.getNode(ISD::BSWAP, dl, 4437 getValue(I.getOperand(1)).getValueType(), 4438 getValue(I.getOperand(1))); 4439 setValue(&I, Res); 4440 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4441 return 0; 4442 case Intrinsic::cttz: { 4443 SDValue Arg = getValue(I.getOperand(1)); 4444 EVT Ty = Arg.getValueType(); 4445 Res = DAG.getNode(ISD::CTTZ, dl, Ty, Arg); 4446 setValue(&I, Res); 4447 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4448 return 0; 4449 } 4450 case Intrinsic::ctlz: { 4451 SDValue Arg = getValue(I.getOperand(1)); 4452 EVT Ty = Arg.getValueType(); 4453 Res = DAG.getNode(ISD::CTLZ, dl, Ty, Arg); 4454 setValue(&I, Res); 4455 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4456 return 0; 4457 } 4458 case Intrinsic::ctpop: { 4459 SDValue Arg = getValue(I.getOperand(1)); 4460 EVT Ty = Arg.getValueType(); 4461 Res = DAG.getNode(ISD::CTPOP, dl, Ty, Arg); 4462 setValue(&I, Res); 4463 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4464 return 0; 4465 } 4466 case Intrinsic::stacksave: { 4467 SDValue Op = getRoot(); 4468 Res = DAG.getNode(ISD::STACKSAVE, dl, 4469 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1); 4470 setValue(&I, Res); 4471 DAG.setRoot(Res.getValue(1)); 4472 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4473 return 0; 4474 } 4475 case Intrinsic::stackrestore: { 4476 Res = getValue(I.getOperand(1)); 4477 Res = DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res); 4478 DAG.setRoot(Res); 4479 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4480 return 0; 4481 } 4482 case Intrinsic::stackprotector: { 4483 // Emit code into the DAG to store the stack guard onto the stack. 4484 MachineFunction &MF = DAG.getMachineFunction(); 4485 MachineFrameInfo *MFI = MF.getFrameInfo(); 4486 EVT PtrTy = TLI.getPointerTy(); 4487 4488 SDValue Src = getValue(I.getOperand(1)); // The guard's value. 4489 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2)); 4490 4491 int FI = FuncInfo.StaticAllocaMap[Slot]; 4492 MFI->setStackProtectorIndex(FI); 4493 4494 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 4495 4496 // Store the stack protector onto the stack. 4497 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN, 4498 PseudoSourceValue::getFixedStack(FI), 4499 0, true); 4500 setValue(&I, Res); 4501 DAG.setRoot(Res); 4502 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4503 return 0; 4504 } 4505 case Intrinsic::objectsize: { 4506 // If we don't know by now, we're never going to know. 4507 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2)); 4508 4509 assert(CI && "Non-constant type in __builtin_object_size?"); 4510 4511 SDValue Arg = getValue(I.getOperand(0)); 4512 EVT Ty = Arg.getValueType(); 4513 4514 if (CI->getZExtValue() == 0) 4515 Res = DAG.getConstant(-1ULL, Ty); 4516 else 4517 Res = DAG.getConstant(0, Ty); 4518 4519 setValue(&I, Res); 4520 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4521 return 0; 4522 } 4523 case Intrinsic::var_annotation: 4524 // Discard annotate attributes 4525 return 0; 4526 4527 case Intrinsic::init_trampoline: { 4528 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts()); 4529 4530 SDValue Ops[6]; 4531 Ops[0] = getRoot(); 4532 Ops[1] = getValue(I.getOperand(1)); 4533 Ops[2] = getValue(I.getOperand(2)); 4534 Ops[3] = getValue(I.getOperand(3)); 4535 Ops[4] = DAG.getSrcValue(I.getOperand(1)); 4536 Ops[5] = DAG.getSrcValue(F); 4537 4538 Res = DAG.getNode(ISD::TRAMPOLINE, dl, 4539 DAG.getVTList(TLI.getPointerTy(), MVT::Other), 4540 Ops, 6); 4541 4542 setValue(&I, Res); 4543 DAG.setRoot(Res.getValue(1)); 4544 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4545 return 0; 4546 } 4547 case Intrinsic::gcroot: 4548 if (GFI) { 4549 Value *Alloca = I.getOperand(1); 4550 Constant *TypeMap = cast<Constant>(I.getOperand(2)); 4551 4552 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 4553 GFI->addStackRoot(FI->getIndex(), TypeMap); 4554 } 4555 return 0; 4556 case Intrinsic::gcread: 4557 case Intrinsic::gcwrite: 4558 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 4559 return 0; 4560 case Intrinsic::flt_rounds: 4561 Res = DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32); 4562 setValue(&I, Res); 4563 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4564 return 0; 4565 case Intrinsic::trap: 4566 Res = DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()); 4567 DAG.setRoot(Res); 4568 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4569 return 0; 4570 case Intrinsic::uadd_with_overflow: 4571 return implVisitAluOverflow(I, ISD::UADDO); 4572 case Intrinsic::sadd_with_overflow: 4573 return implVisitAluOverflow(I, ISD::SADDO); 4574 case Intrinsic::usub_with_overflow: 4575 return implVisitAluOverflow(I, ISD::USUBO); 4576 case Intrinsic::ssub_with_overflow: 4577 return implVisitAluOverflow(I, ISD::SSUBO); 4578 case Intrinsic::umul_with_overflow: 4579 return implVisitAluOverflow(I, ISD::UMULO); 4580 case Intrinsic::smul_with_overflow: 4581 return implVisitAluOverflow(I, ISD::SMULO); 4582 4583 case Intrinsic::prefetch: { 4584 SDValue Ops[4]; 4585 Ops[0] = getRoot(); 4586 Ops[1] = getValue(I.getOperand(1)); 4587 Ops[2] = getValue(I.getOperand(2)); 4588 Ops[3] = getValue(I.getOperand(3)); 4589 Res = DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4); 4590 DAG.setRoot(Res); 4591 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4592 return 0; 4593 } 4594 4595 case Intrinsic::memory_barrier: { 4596 SDValue Ops[6]; 4597 Ops[0] = getRoot(); 4598 for (int x = 1; x < 6; ++x) 4599 Ops[x] = getValue(I.getOperand(x)); 4600 4601 Res = DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6); 4602 DAG.setRoot(Res); 4603 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4604 return 0; 4605 } 4606 case Intrinsic::atomic_cmp_swap: { 4607 SDValue Root = getRoot(); 4608 SDValue L = 4609 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(), 4610 getValue(I.getOperand(2)).getValueType().getSimpleVT(), 4611 Root, 4612 getValue(I.getOperand(1)), 4613 getValue(I.getOperand(2)), 4614 getValue(I.getOperand(3)), 4615 I.getOperand(1)); 4616 setValue(&I, L); 4617 DAG.setRoot(L.getValue(1)); 4618 DAG.AssignOrdering(L.getNode(), SDNodeOrder); 4619 return 0; 4620 } 4621 case Intrinsic::atomic_load_add: 4622 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD); 4623 case Intrinsic::atomic_load_sub: 4624 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB); 4625 case Intrinsic::atomic_load_or: 4626 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR); 4627 case Intrinsic::atomic_load_xor: 4628 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR); 4629 case Intrinsic::atomic_load_and: 4630 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND); 4631 case Intrinsic::atomic_load_nand: 4632 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND); 4633 case Intrinsic::atomic_load_max: 4634 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX); 4635 case Intrinsic::atomic_load_min: 4636 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN); 4637 case Intrinsic::atomic_load_umin: 4638 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN); 4639 case Intrinsic::atomic_load_umax: 4640 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX); 4641 case Intrinsic::atomic_swap: 4642 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP); 4643 4644 case Intrinsic::invariant_start: 4645 case Intrinsic::lifetime_start: 4646 // Discard region information. 4647 Res = DAG.getUNDEF(TLI.getPointerTy()); 4648 setValue(&I, Res); 4649 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4650 return 0; 4651 case Intrinsic::invariant_end: 4652 case Intrinsic::lifetime_end: 4653 // Discard region information. 4654 return 0; 4655 } 4656 } 4657 4658 /// Test if the given instruction is in a position to be optimized 4659 /// with a tail-call. This roughly means that it's in a block with 4660 /// a return and there's nothing that needs to be scheduled 4661 /// between it and the return. 4662 /// 4663 /// This function only tests target-independent requirements. 4664 static bool 4665 isInTailCallPosition(const Instruction *I, Attributes CalleeRetAttr, 4666 const TargetLowering &TLI) { 4667 const BasicBlock *ExitBB = I->getParent(); 4668 const TerminatorInst *Term = ExitBB->getTerminator(); 4669 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term); 4670 const Function *F = ExitBB->getParent(); 4671 4672 // The block must end in a return statement or an unreachable. 4673 if (!Ret && !isa<UnreachableInst>(Term)) return false; 4674 4675 // If I will have a chain, make sure no other instruction that will have a 4676 // chain interposes between I and the return. 4677 if (I->mayHaveSideEffects() || I->mayReadFromMemory() || 4678 !I->isSafeToSpeculativelyExecute()) 4679 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ; 4680 --BBI) { 4681 if (&*BBI == I) 4682 break; 4683 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() || 4684 !BBI->isSafeToSpeculativelyExecute()) 4685 return false; 4686 } 4687 4688 // If the block ends with a void return or unreachable, it doesn't matter 4689 // what the call's return type is. 4690 if (!Ret || Ret->getNumOperands() == 0) return true; 4691 4692 // If the return value is undef, it doesn't matter what the call's 4693 // return type is. 4694 if (isa<UndefValue>(Ret->getOperand(0))) return true; 4695 4696 // Conservatively require the attributes of the call to match those of 4697 // the return. Ignore noalias because it doesn't affect the call sequence. 4698 unsigned CallerRetAttr = F->getAttributes().getRetAttributes(); 4699 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias) 4700 return false; 4701 4702 // Otherwise, make sure the unmodified return value of I is the return value. 4703 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ; 4704 U = dyn_cast<Instruction>(U->getOperand(0))) { 4705 if (!U) 4706 return false; 4707 if (!U->hasOneUse()) 4708 return false; 4709 if (U == I) 4710 break; 4711 // Check for a truly no-op truncate. 4712 if (isa<TruncInst>(U) && 4713 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType())) 4714 continue; 4715 // Check for a truly no-op bitcast. 4716 if (isa<BitCastInst>(U) && 4717 (U->getOperand(0)->getType() == U->getType() || 4718 (isa<PointerType>(U->getOperand(0)->getType()) && 4719 isa<PointerType>(U->getType())))) 4720 continue; 4721 // Otherwise it's not a true no-op. 4722 return false; 4723 } 4724 4725 return true; 4726 } 4727 4728 void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee, 4729 bool isTailCall, 4730 MachineBasicBlock *LandingPad) { 4731 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 4732 const FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 4733 const Type *RetTy = FTy->getReturnType(); 4734 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 4735 unsigned BeginLabel = 0, EndLabel = 0; 4736 4737 TargetLowering::ArgListTy Args; 4738 TargetLowering::ArgListEntry Entry; 4739 Args.reserve(CS.arg_size()); 4740 4741 // Check whether the function can return without sret-demotion. 4742 SmallVector<EVT, 4> OutVTs; 4743 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags; 4744 SmallVector<uint64_t, 4> Offsets; 4745 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(), 4746 OutVTs, OutsFlags, TLI, &Offsets); 4747 4748 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(), 4749 FTy->isVarArg(), OutVTs, OutsFlags, DAG); 4750 4751 SDValue DemoteStackSlot; 4752 4753 if (!CanLowerReturn) { 4754 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize( 4755 FTy->getReturnType()); 4756 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment( 4757 FTy->getReturnType()); 4758 MachineFunction &MF = DAG.getMachineFunction(); 4759 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 4760 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType()); 4761 4762 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy()); 4763 Entry.Node = DemoteStackSlot; 4764 Entry.Ty = StackSlotPtrType; 4765 Entry.isSExt = false; 4766 Entry.isZExt = false; 4767 Entry.isInReg = false; 4768 Entry.isSRet = true; 4769 Entry.isNest = false; 4770 Entry.isByVal = false; 4771 Entry.Alignment = Align; 4772 Args.push_back(Entry); 4773 RetTy = Type::getVoidTy(FTy->getContext()); 4774 } 4775 4776 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 4777 i != e; ++i) { 4778 SDValue ArgNode = getValue(*i); 4779 Entry.Node = ArgNode; Entry.Ty = (*i)->getType(); 4780 4781 unsigned attrInd = i - CS.arg_begin() + 1; 4782 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt); 4783 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt); 4784 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg); 4785 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet); 4786 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest); 4787 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal); 4788 Entry.Alignment = CS.getParamAlignment(attrInd); 4789 Args.push_back(Entry); 4790 } 4791 4792 if (LandingPad && MMI) { 4793 // Insert a label before the invoke call to mark the try range. This can be 4794 // used to detect deletion of the invoke via the MachineModuleInfo. 4795 BeginLabel = MMI->NextLabelID(); 4796 4797 // For SjLj, keep track of which landing pads go with which invokes 4798 // so as to maintain the ordering of pads in the LSDA. 4799 unsigned CallSiteIndex = MMI->getCurrentCallSite(); 4800 if (CallSiteIndex) { 4801 MMI->setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 4802 // Now that the call site is handled, stop tracking it. 4803 MMI->setCurrentCallSite(0); 4804 } 4805 4806 // Both PendingLoads and PendingExports must be flushed here; 4807 // this call might not return. 4808 (void)getRoot(); 4809 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(), 4810 getControlRoot(), BeginLabel)); 4811 } 4812 4813 // Check if target-independent constraints permit a tail call here. 4814 // Target-dependent constraints are checked within TLI.LowerCallTo. 4815 if (isTailCall && 4816 !isInTailCallPosition(CS.getInstruction(), 4817 CS.getAttributes().getRetAttributes(), 4818 TLI)) 4819 isTailCall = false; 4820 4821 std::pair<SDValue,SDValue> Result = 4822 TLI.LowerCallTo(getRoot(), RetTy, 4823 CS.paramHasAttr(0, Attribute::SExt), 4824 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(), 4825 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(), 4826 CS.getCallingConv(), 4827 isTailCall, 4828 !CS.getInstruction()->use_empty(), 4829 Callee, Args, DAG, getCurDebugLoc(), SDNodeOrder); 4830 assert((isTailCall || Result.second.getNode()) && 4831 "Non-null chain expected with non-tail call!"); 4832 assert((Result.second.getNode() || !Result.first.getNode()) && 4833 "Null value expected with tail call!"); 4834 if (Result.first.getNode()) { 4835 setValue(CS.getInstruction(), Result.first); 4836 DAG.AssignOrdering(Result.first.getNode(), SDNodeOrder); 4837 } else if (!CanLowerReturn && Result.second.getNode()) { 4838 // The instruction result is the result of loading from the 4839 // hidden sret parameter. 4840 SmallVector<EVT, 1> PVTs; 4841 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType()); 4842 4843 ComputeValueVTs(TLI, PtrRetTy, PVTs); 4844 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 4845 EVT PtrVT = PVTs[0]; 4846 unsigned NumValues = OutVTs.size(); 4847 SmallVector<SDValue, 4> Values(NumValues); 4848 SmallVector<SDValue, 4> Chains(NumValues); 4849 4850 for (unsigned i = 0; i < NumValues; ++i) { 4851 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, 4852 DemoteStackSlot, 4853 DAG.getConstant(Offsets[i], PtrVT)); 4854 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second, 4855 Add, NULL, Offsets[i], false, 1); 4856 Values[i] = L; 4857 Chains[i] = L.getValue(1); 4858 } 4859 4860 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 4861 MVT::Other, &Chains[0], NumValues); 4862 PendingLoads.push_back(Chain); 4863 4864 // Collect the legal value parts into potentially illegal values 4865 // that correspond to the original function's return values. 4866 SmallVector<EVT, 4> RetTys; 4867 RetTy = FTy->getReturnType(); 4868 ComputeValueVTs(TLI, RetTy, RetTys); 4869 ISD::NodeType AssertOp = ISD::DELETED_NODE; 4870 SmallVector<SDValue, 4> ReturnValues; 4871 unsigned CurReg = 0; 4872 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 4873 EVT VT = RetTys[I]; 4874 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT); 4875 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT); 4876 4877 SDValue ReturnValue = 4878 getCopyFromParts(DAG, getCurDebugLoc(), SDNodeOrder, &Values[CurReg], NumRegs, 4879 RegisterVT, VT, AssertOp); 4880 ReturnValues.push_back(ReturnValue); 4881 DAG.AssignOrdering(ReturnValue.getNode(), SDNodeOrder); 4882 CurReg += NumRegs; 4883 } 4884 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 4885 DAG.getVTList(&RetTys[0], RetTys.size()), 4886 &ReturnValues[0], ReturnValues.size()); 4887 4888 setValue(CS.getInstruction(), Res); 4889 4890 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder); 4891 DAG.AssignOrdering(Res.getNode(), SDNodeOrder); 4892 } 4893 4894 // As a special case, a null chain means that a tail call has been emitted and 4895 // the DAG root is already updated. 4896 if (Result.second.getNode()) { 4897 DAG.setRoot(Result.second); 4898 DAG.AssignOrdering(Result.second.getNode(), SDNodeOrder); 4899 } else { 4900 HasTailCall = true; 4901 } 4902 4903 if (LandingPad && MMI) { 4904 // Insert a label at the end of the invoke call to mark the try range. This 4905 // can be used to detect deletion of the invoke via the MachineModuleInfo. 4906 EndLabel = MMI->NextLabelID(); 4907 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(), 4908 getRoot(), EndLabel)); 4909 4910 // Inform MachineModuleInfo of range. 4911 MMI->addInvoke(LandingPad, BeginLabel, EndLabel); 4912 } 4913 } 4914 4915 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 4916 /// value is equal or not-equal to zero. 4917 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) { 4918 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); 4919 UI != E; ++UI) { 4920 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI)) 4921 if (IC->isEquality()) 4922 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 4923 if (C->isNullValue()) 4924 continue; 4925 // Unknown instruction. 4926 return false; 4927 } 4928 return true; 4929 } 4930 4931 static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy, 4932 SelectionDAGBuilder &Builder) { 4933 4934 // Check to see if this load can be trivially constant folded, e.g. if the 4935 // input is from a string literal. 4936 if (Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 4937 // Cast pointer to the type we really want to load. 4938 LoadInput = ConstantExpr::getBitCast(LoadInput, 4939 PointerType::getUnqual(LoadTy)); 4940 4941 if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD)) 4942 return Builder.getValue(LoadCst); 4943 } 4944 4945 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 4946 // still constant memory, the input chain can be the entry node. 4947 SDValue Root; 4948 bool ConstantMemory = false; 4949 4950 // Do not serialize (non-volatile) loads of constant memory with anything. 4951 if (Builder.AA->pointsToConstantMemory(PtrVal)) { 4952 Root = Builder.DAG.getEntryNode(); 4953 ConstantMemory = true; 4954 } else { 4955 // Do not serialize non-volatile loads against each other. 4956 Root = Builder.DAG.getRoot(); 4957 } 4958 4959 SDValue Ptr = Builder.getValue(PtrVal); 4960 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root, 4961 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/, 4962 false /*volatile*/, 1 /* align=1 */); 4963 4964 if (!ConstantMemory) 4965 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 4966 return LoadVal; 4967 } 4968 4969 4970 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form. 4971 /// If so, return true and lower it, otherwise return false and it will be 4972 /// lowered like a normal call. 4973 bool SelectionDAGBuilder::visitMemCmpCall(CallInst &I) { 4974 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t) 4975 if (I.getNumOperands() != 4) 4976 return false; 4977 4978 Value *LHS = I.getOperand(1), *RHS = I.getOperand(2); 4979 if (!isa<PointerType>(LHS->getType()) || !isa<PointerType>(RHS->getType()) || 4980 !isa<IntegerType>(I.getOperand(3)->getType()) || 4981 !isa<IntegerType>(I.getType())) 4982 return false; 4983 4984 ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3)); 4985 4986 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 4987 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 4988 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) { 4989 bool ActuallyDoIt = true; 4990 MVT LoadVT; 4991 const Type *LoadTy; 4992 switch (Size->getZExtValue()) { 4993 default: 4994 LoadVT = MVT::Other; 4995 LoadTy = 0; 4996 ActuallyDoIt = false; 4997 break; 4998 case 2: 4999 LoadVT = MVT::i16; 5000 LoadTy = Type::getInt16Ty(Size->getContext()); 5001 break; 5002 case 4: 5003 LoadVT = MVT::i32; 5004 LoadTy = Type::getInt32Ty(Size->getContext()); 5005 break; 5006 case 8: 5007 LoadVT = MVT::i64; 5008 LoadTy = Type::getInt64Ty(Size->getContext()); 5009 break; 5010 /* 5011 case 16: 5012 LoadVT = MVT::v4i32; 5013 LoadTy = Type::getInt32Ty(Size->getContext()); 5014 LoadTy = VectorType::get(LoadTy, 4); 5015 break; 5016 */ 5017 } 5018 5019 // This turns into unaligned loads. We only do this if the target natively 5020 // supports the MVT we'll be loading or if it is small enough (<= 4) that 5021 // we'll only produce a small number of byte loads. 5022 5023 // Require that we can find a legal MVT, and only do this if the target 5024 // supports unaligned loads of that type. Expanding into byte loads would 5025 // bloat the code. 5026 if (ActuallyDoIt && Size->getZExtValue() > 4) { 5027 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 5028 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 5029 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT)) 5030 ActuallyDoIt = false; 5031 } 5032 5033 if (ActuallyDoIt) { 5034 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this); 5035 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this); 5036 5037 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal, 5038 ISD::SETNE); 5039 EVT CallVT = TLI.getValueType(I.getType(), true); 5040 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT)); 5041 return true; 5042 } 5043 } 5044 5045 5046 return false; 5047 } 5048 5049 5050 void SelectionDAGBuilder::visitCall(CallInst &I) { 5051 const char *RenameFn = 0; 5052 if (Function *F = I.getCalledFunction()) { 5053 if (F->isDeclaration()) { 5054 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo(); 5055 if (II) { 5056 if (unsigned IID = II->getIntrinsicID(F)) { 5057 RenameFn = visitIntrinsicCall(I, IID); 5058 if (!RenameFn) 5059 return; 5060 } 5061 } 5062 if (unsigned IID = F->getIntrinsicID()) { 5063 RenameFn = visitIntrinsicCall(I, IID); 5064 if (!RenameFn) 5065 return; 5066 } 5067 } 5068 5069 // Check for well-known libc/libm calls. If the function is internal, it 5070 // can't be a library call. 5071 if (!F->hasLocalLinkage() && F->hasName()) { 5072 StringRef Name = F->getName(); 5073 if (Name == "copysign" || Name == "copysignf") { 5074 if (I.getNumOperands() == 3 && // Basic sanity checks. 5075 I.getOperand(1)->getType()->isFloatingPoint() && 5076 I.getType() == I.getOperand(1)->getType() && 5077 I.getType() == I.getOperand(2)->getType()) { 5078 SDValue LHS = getValue(I.getOperand(1)); 5079 SDValue RHS = getValue(I.getOperand(2)); 5080 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(), 5081 LHS.getValueType(), LHS, RHS)); 5082 return; 5083 } 5084 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") { 5085 if (I.getNumOperands() == 2 && // Basic sanity checks. 5086 I.getOperand(1)->getType()->isFloatingPoint() && 5087 I.getType() == I.getOperand(1)->getType()) { 5088 SDValue Tmp = getValue(I.getOperand(1)); 5089 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(), 5090 Tmp.getValueType(), Tmp)); 5091 return; 5092 } 5093 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") { 5094 if (I.getNumOperands() == 2 && // Basic sanity checks. 5095 I.getOperand(1)->getType()->isFloatingPoint() && 5096 I.getType() == I.getOperand(1)->getType() && 5097 I.onlyReadsMemory()) { 5098 SDValue Tmp = getValue(I.getOperand(1)); 5099 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(), 5100 Tmp.getValueType(), Tmp)); 5101 return; 5102 } 5103 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") { 5104 if (I.getNumOperands() == 2 && // Basic sanity checks. 5105 I.getOperand(1)->getType()->isFloatingPoint() && 5106 I.getType() == I.getOperand(1)->getType() && 5107 I.onlyReadsMemory()) { 5108 SDValue Tmp = getValue(I.getOperand(1)); 5109 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(), 5110 Tmp.getValueType(), Tmp)); 5111 return; 5112 } 5113 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") { 5114 if (I.getNumOperands() == 2 && // Basic sanity checks. 5115 I.getOperand(1)->getType()->isFloatingPoint() && 5116 I.getType() == I.getOperand(1)->getType() && 5117 I.onlyReadsMemory()) { 5118 SDValue Tmp = getValue(I.getOperand(1)); 5119 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(), 5120 Tmp.getValueType(), Tmp)); 5121 return; 5122 } 5123 } else if (Name == "memcmp") { 5124 if (visitMemCmpCall(I)) 5125 return; 5126 } 5127 } 5128 } else if (isa<InlineAsm>(I.getOperand(0))) { 5129 visitInlineAsm(&I); 5130 return; 5131 } 5132 5133 SDValue Callee; 5134 if (!RenameFn) 5135 Callee = getValue(I.getOperand(0)); 5136 else 5137 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy()); 5138 5139 // Check if we can potentially perform a tail call. More detailed checking is 5140 // be done within LowerCallTo, after more information about the call is known. 5141 LowerCallTo(&I, Callee, I.isTailCall()); 5142 } 5143 5144 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 5145 /// this value and returns the result as a ValueVT value. This uses 5146 /// Chain/Flag as the input and updates them for the output Chain/Flag. 5147 /// If the Flag pointer is NULL, no flag is used. 5148 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl, 5149 unsigned Order, SDValue &Chain, 5150 SDValue *Flag) const { 5151 // Assemble the legal parts into the final values. 5152 SmallVector<SDValue, 4> Values(ValueVTs.size()); 5153 SmallVector<SDValue, 8> Parts; 5154 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 5155 // Copy the legal parts from the registers. 5156 EVT ValueVT = ValueVTs[Value]; 5157 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT); 5158 EVT RegisterVT = RegVTs[Value]; 5159 5160 Parts.resize(NumRegs); 5161 for (unsigned i = 0; i != NumRegs; ++i) { 5162 SDValue P; 5163 if (Flag == 0) { 5164 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 5165 } else { 5166 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 5167 *Flag = P.getValue(2); 5168 } 5169 5170 Chain = P.getValue(1); 5171 DAG.AssignOrdering(P.getNode(), Order); 5172 5173 // If the source register was virtual and if we know something about it, 5174 // add an assert node. 5175 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) && 5176 RegisterVT.isInteger() && !RegisterVT.isVector()) { 5177 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister; 5178 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo(); 5179 if (FLI.LiveOutRegInfo.size() > SlotNo) { 5180 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo]; 5181 5182 unsigned RegSize = RegisterVT.getSizeInBits(); 5183 unsigned NumSignBits = LOI.NumSignBits; 5184 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes(); 5185 5186 // FIXME: We capture more information than the dag can represent. For 5187 // now, just use the tightest assertzext/assertsext possible. 5188 bool isSExt = true; 5189 EVT FromVT(MVT::Other); 5190 if (NumSignBits == RegSize) 5191 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1 5192 else if (NumZeroBits >= RegSize-1) 5193 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1 5194 else if (NumSignBits > RegSize-8) 5195 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8 5196 else if (NumZeroBits >= RegSize-8) 5197 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8 5198 else if (NumSignBits > RegSize-16) 5199 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16 5200 else if (NumZeroBits >= RegSize-16) 5201 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16 5202 else if (NumSignBits > RegSize-32) 5203 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32 5204 else if (NumZeroBits >= RegSize-32) 5205 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32 5206 5207 if (FromVT != MVT::Other) { 5208 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 5209 RegisterVT, P, DAG.getValueType(FromVT)); 5210 DAG.AssignOrdering(P.getNode(), Order); 5211 } 5212 } 5213 } 5214 5215 Parts[i] = P; 5216 } 5217 5218 Values[Value] = getCopyFromParts(DAG, dl, Order, Parts.begin(), 5219 NumRegs, RegisterVT, ValueVT); 5220 DAG.AssignOrdering(Values[Value].getNode(), Order); 5221 Part += NumRegs; 5222 Parts.clear(); 5223 } 5224 5225 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 5226 DAG.getVTList(&ValueVTs[0], ValueVTs.size()), 5227 &Values[0], ValueVTs.size()); 5228 DAG.AssignOrdering(Res.getNode(), Order); 5229 return Res; 5230 } 5231 5232 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 5233 /// specified value into the registers specified by this object. This uses 5234 /// Chain/Flag as the input and updates them for the output Chain/Flag. 5235 /// If the Flag pointer is NULL, no flag is used. 5236 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, 5237 unsigned Order, SDValue &Chain, 5238 SDValue *Flag) const { 5239 // Get the list of the values's legal parts. 5240 unsigned NumRegs = Regs.size(); 5241 SmallVector<SDValue, 8> Parts(NumRegs); 5242 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 5243 EVT ValueVT = ValueVTs[Value]; 5244 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT); 5245 EVT RegisterVT = RegVTs[Value]; 5246 5247 getCopyToParts(DAG, dl, Order, 5248 Val.getValue(Val.getResNo() + Value), 5249 &Parts[Part], NumParts, RegisterVT); 5250 Part += NumParts; 5251 } 5252 5253 // Copy the parts into the registers. 5254 SmallVector<SDValue, 8> Chains(NumRegs); 5255 for (unsigned i = 0; i != NumRegs; ++i) { 5256 SDValue Part; 5257 if (Flag == 0) { 5258 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 5259 } else { 5260 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 5261 *Flag = Part.getValue(1); 5262 } 5263 5264 Chains[i] = Part.getValue(0); 5265 DAG.AssignOrdering(Part.getNode(), Order); 5266 } 5267 5268 if (NumRegs == 1 || Flag) 5269 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 5270 // flagged to it. That is the CopyToReg nodes and the user are considered 5271 // a single scheduling unit. If we create a TokenFactor and return it as 5272 // chain, then the TokenFactor is both a predecessor (operand) of the 5273 // user as well as a successor (the TF operands are flagged to the user). 5274 // c1, f1 = CopyToReg 5275 // c2, f2 = CopyToReg 5276 // c3 = TokenFactor c1, c2 5277 // ... 5278 // = op c3, ..., f2 5279 Chain = Chains[NumRegs-1]; 5280 else 5281 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs); 5282 5283 DAG.AssignOrdering(Chain.getNode(), Order); 5284 } 5285 5286 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 5287 /// operand list. This adds the code marker and includes the number of 5288 /// values added into it. 5289 void RegsForValue::AddInlineAsmOperands(unsigned Code, 5290 bool HasMatching,unsigned MatchingIdx, 5291 SelectionDAG &DAG, unsigned Order, 5292 std::vector<SDValue> &Ops) const { 5293 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!"); 5294 unsigned Flag = Code | (Regs.size() << 3); 5295 if (HasMatching) 5296 Flag |= 0x80000000 | (MatchingIdx << 16); 5297 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32); 5298 Ops.push_back(Res); 5299 5300 DAG.AssignOrdering(Res.getNode(), Order); 5301 5302 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 5303 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 5304 EVT RegisterVT = RegVTs[Value]; 5305 for (unsigned i = 0; i != NumRegs; ++i) { 5306 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 5307 SDValue Res = DAG.getRegister(Regs[Reg++], RegisterVT); 5308 Ops.push_back(Res); 5309 DAG.AssignOrdering(Res.getNode(), Order); 5310 } 5311 } 5312 } 5313 5314 /// isAllocatableRegister - If the specified register is safe to allocate, 5315 /// i.e. it isn't a stack pointer or some other special register, return the 5316 /// register class for the register. Otherwise, return null. 5317 static const TargetRegisterClass * 5318 isAllocatableRegister(unsigned Reg, MachineFunction &MF, 5319 const TargetLowering &TLI, 5320 const TargetRegisterInfo *TRI) { 5321 EVT FoundVT = MVT::Other; 5322 const TargetRegisterClass *FoundRC = 0; 5323 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(), 5324 E = TRI->regclass_end(); RCI != E; ++RCI) { 5325 EVT ThisVT = MVT::Other; 5326 5327 const TargetRegisterClass *RC = *RCI; 5328 // If none of the the value types for this register class are valid, we 5329 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5330 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end(); 5331 I != E; ++I) { 5332 if (TLI.isTypeLegal(*I)) { 5333 // If we have already found this register in a different register class, 5334 // choose the one with the largest VT specified. For example, on 5335 // PowerPC, we favor f64 register classes over f32. 5336 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) { 5337 ThisVT = *I; 5338 break; 5339 } 5340 } 5341 } 5342 5343 if (ThisVT == MVT::Other) continue; 5344 5345 // NOTE: This isn't ideal. In particular, this might allocate the 5346 // frame pointer in functions that need it (due to them not being taken 5347 // out of allocation, because a variable sized allocation hasn't been seen 5348 // yet). This is a slight code pessimization, but should still work. 5349 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF), 5350 E = RC->allocation_order_end(MF); I != E; ++I) 5351 if (*I == Reg) { 5352 // We found a matching register class. Keep looking at others in case 5353 // we find one with larger registers that this physreg is also in. 5354 FoundRC = RC; 5355 FoundVT = ThisVT; 5356 break; 5357 } 5358 } 5359 return FoundRC; 5360 } 5361 5362 5363 namespace llvm { 5364 /// AsmOperandInfo - This contains information for each constraint that we are 5365 /// lowering. 5366 class VISIBILITY_HIDDEN SDISelAsmOperandInfo : 5367 public TargetLowering::AsmOperandInfo { 5368 public: 5369 /// CallOperand - If this is the result output operand or a clobber 5370 /// this is null, otherwise it is the incoming operand to the CallInst. 5371 /// This gets modified as the asm is processed. 5372 SDValue CallOperand; 5373 5374 /// AssignedRegs - If this is a register or register class operand, this 5375 /// contains the set of register corresponding to the operand. 5376 RegsForValue AssignedRegs; 5377 5378 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info) 5379 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) { 5380 } 5381 5382 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers 5383 /// busy in OutputRegs/InputRegs. 5384 void MarkAllocatedRegs(bool isOutReg, bool isInReg, 5385 std::set<unsigned> &OutputRegs, 5386 std::set<unsigned> &InputRegs, 5387 const TargetRegisterInfo &TRI) const { 5388 if (isOutReg) { 5389 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 5390 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI); 5391 } 5392 if (isInReg) { 5393 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 5394 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI); 5395 } 5396 } 5397 5398 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 5399 /// corresponds to. If there is no Value* for this operand, it returns 5400 /// MVT::Other. 5401 EVT getCallOperandValEVT(LLVMContext &Context, 5402 const TargetLowering &TLI, 5403 const TargetData *TD) const { 5404 if (CallOperandVal == 0) return MVT::Other; 5405 5406 if (isa<BasicBlock>(CallOperandVal)) 5407 return TLI.getPointerTy(); 5408 5409 const llvm::Type *OpTy = CallOperandVal->getType(); 5410 5411 // If this is an indirect operand, the operand is a pointer to the 5412 // accessed type. 5413 if (isIndirect) { 5414 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 5415 if (!PtrTy) 5416 llvm_report_error("Indirect operand for inline asm not a pointer!"); 5417 OpTy = PtrTy->getElementType(); 5418 } 5419 5420 // If OpTy is not a single value, it may be a struct/union that we 5421 // can tile with integers. 5422 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5423 unsigned BitSize = TD->getTypeSizeInBits(OpTy); 5424 switch (BitSize) { 5425 default: break; 5426 case 1: 5427 case 8: 5428 case 16: 5429 case 32: 5430 case 64: 5431 case 128: 5432 OpTy = IntegerType::get(Context, BitSize); 5433 break; 5434 } 5435 } 5436 5437 return TLI.getValueType(OpTy, true); 5438 } 5439 5440 private: 5441 /// MarkRegAndAliases - Mark the specified register and all aliases in the 5442 /// specified set. 5443 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs, 5444 const TargetRegisterInfo &TRI) { 5445 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg"); 5446 Regs.insert(Reg); 5447 if (const unsigned *Aliases = TRI.getAliasSet(Reg)) 5448 for (; *Aliases; ++Aliases) 5449 Regs.insert(*Aliases); 5450 } 5451 }; 5452 } // end llvm namespace. 5453 5454 5455 /// GetRegistersForValue - Assign registers (virtual or physical) for the 5456 /// specified operand. We prefer to assign virtual registers, to allow the 5457 /// register allocator to handle the assignment process. However, if the asm 5458 /// uses features that we can't model on machineinstrs, we have SDISel do the 5459 /// allocation. This produces generally horrible, but correct, code. 5460 /// 5461 /// OpInfo describes the operand. 5462 /// Input and OutputRegs are the set of already allocated physical registers. 5463 /// 5464 void SelectionDAGBuilder:: 5465 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, 5466 std::set<unsigned> &OutputRegs, 5467 std::set<unsigned> &InputRegs) { 5468 LLVMContext &Context = FuncInfo.Fn->getContext(); 5469 5470 // Compute whether this value requires an input register, an output register, 5471 // or both. 5472 bool isOutReg = false; 5473 bool isInReg = false; 5474 switch (OpInfo.Type) { 5475 case InlineAsm::isOutput: 5476 isOutReg = true; 5477 5478 // If there is an input constraint that matches this, we need to reserve 5479 // the input register so no other inputs allocate to it. 5480 isInReg = OpInfo.hasMatchingInput(); 5481 break; 5482 case InlineAsm::isInput: 5483 isInReg = true; 5484 isOutReg = false; 5485 break; 5486 case InlineAsm::isClobber: 5487 isOutReg = true; 5488 isInReg = true; 5489 break; 5490 } 5491 5492 5493 MachineFunction &MF = DAG.getMachineFunction(); 5494 SmallVector<unsigned, 4> Regs; 5495 5496 // If this is a constraint for a single physreg, or a constraint for a 5497 // register class, find it. 5498 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 5499 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 5500 OpInfo.ConstraintVT); 5501 5502 unsigned NumRegs = 1; 5503 if (OpInfo.ConstraintVT != MVT::Other) { 5504 // If this is a FP input in an integer register (or visa versa) insert a bit 5505 // cast of the input value. More generally, handle any case where the input 5506 // value disagrees with the register class we plan to stick this in. 5507 if (OpInfo.Type == InlineAsm::isInput && 5508 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) { 5509 // Try to convert to the first EVT that the reg class contains. If the 5510 // types are identical size, use a bitcast to convert (e.g. two differing 5511 // vector types). 5512 EVT RegVT = *PhysReg.second->vt_begin(); 5513 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 5514 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 5515 RegVT, OpInfo.CallOperand); 5516 OpInfo.ConstraintVT = RegVT; 5517 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 5518 // If the input is a FP value and we want it in FP registers, do a 5519 // bitcast to the corresponding integer type. This turns an f64 value 5520 // into i64, which can be passed with two i32 values on a 32-bit 5521 // machine. 5522 RegVT = EVT::getIntegerVT(Context, 5523 OpInfo.ConstraintVT.getSizeInBits()); 5524 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 5525 RegVT, OpInfo.CallOperand); 5526 OpInfo.ConstraintVT = RegVT; 5527 } 5528 5529 DAG.AssignOrdering(OpInfo.CallOperand.getNode(), SDNodeOrder); 5530 } 5531 5532 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 5533 } 5534 5535 EVT RegVT; 5536 EVT ValueVT = OpInfo.ConstraintVT; 5537 5538 // If this is a constraint for a specific physical register, like {r17}, 5539 // assign it now. 5540 if (unsigned AssignedReg = PhysReg.first) { 5541 const TargetRegisterClass *RC = PhysReg.second; 5542 if (OpInfo.ConstraintVT == MVT::Other) 5543 ValueVT = *RC->vt_begin(); 5544 5545 // Get the actual register value type. This is important, because the user 5546 // may have asked for (e.g.) the AX register in i32 type. We need to 5547 // remember that AX is actually i16 to get the right extension. 5548 RegVT = *RC->vt_begin(); 5549 5550 // This is a explicit reference to a physical register. 5551 Regs.push_back(AssignedReg); 5552 5553 // If this is an expanded reference, add the rest of the regs to Regs. 5554 if (NumRegs != 1) { 5555 TargetRegisterClass::iterator I = RC->begin(); 5556 for (; *I != AssignedReg; ++I) 5557 assert(I != RC->end() && "Didn't find reg!"); 5558 5559 // Already added the first reg. 5560 --NumRegs; ++I; 5561 for (; NumRegs; --NumRegs, ++I) { 5562 assert(I != RC->end() && "Ran out of registers to allocate!"); 5563 Regs.push_back(*I); 5564 } 5565 } 5566 5567 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT); 5568 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 5569 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 5570 return; 5571 } 5572 5573 // Otherwise, if this was a reference to an LLVM register class, create vregs 5574 // for this reference. 5575 if (const TargetRegisterClass *RC = PhysReg.second) { 5576 RegVT = *RC->vt_begin(); 5577 if (OpInfo.ConstraintVT == MVT::Other) 5578 ValueVT = RegVT; 5579 5580 // Create the appropriate number of virtual registers. 5581 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5582 for (; NumRegs; --NumRegs) 5583 Regs.push_back(RegInfo.createVirtualRegister(RC)); 5584 5585 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT); 5586 return; 5587 } 5588 5589 // This is a reference to a register class that doesn't directly correspond 5590 // to an LLVM register class. Allocate NumRegs consecutive, available, 5591 // registers from the class. 5592 std::vector<unsigned> RegClassRegs 5593 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode, 5594 OpInfo.ConstraintVT); 5595 5596 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 5597 unsigned NumAllocated = 0; 5598 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) { 5599 unsigned Reg = RegClassRegs[i]; 5600 // See if this register is available. 5601 if ((isOutReg && OutputRegs.count(Reg)) || // Already used. 5602 (isInReg && InputRegs.count(Reg))) { // Already used. 5603 // Make sure we find consecutive registers. 5604 NumAllocated = 0; 5605 continue; 5606 } 5607 5608 // Check to see if this register is allocatable (i.e. don't give out the 5609 // stack pointer). 5610 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI); 5611 if (!RC) { // Couldn't allocate this register. 5612 // Reset NumAllocated to make sure we return consecutive registers. 5613 NumAllocated = 0; 5614 continue; 5615 } 5616 5617 // Okay, this register is good, we can use it. 5618 ++NumAllocated; 5619 5620 // If we allocated enough consecutive registers, succeed. 5621 if (NumAllocated == NumRegs) { 5622 unsigned RegStart = (i-NumAllocated)+1; 5623 unsigned RegEnd = i+1; 5624 // Mark all of the allocated registers used. 5625 for (unsigned i = RegStart; i != RegEnd; ++i) 5626 Regs.push_back(RegClassRegs[i]); 5627 5628 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(), 5629 OpInfo.ConstraintVT); 5630 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 5631 return; 5632 } 5633 } 5634 5635 // Otherwise, we couldn't allocate enough registers for this. 5636 } 5637 5638 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being 5639 /// processed uses a memory 'm' constraint. 5640 static bool 5641 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos, 5642 const TargetLowering &TLI) { 5643 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) { 5644 InlineAsm::ConstraintInfo &CI = CInfos[i]; 5645 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) { 5646 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]); 5647 if (CType == TargetLowering::C_Memory) 5648 return true; 5649 } 5650 5651 // Indirect operand accesses access memory. 5652 if (CI.isIndirect) 5653 return true; 5654 } 5655 5656 return false; 5657 } 5658 5659 /// visitInlineAsm - Handle a call to an InlineAsm object. 5660 /// 5661 void SelectionDAGBuilder::visitInlineAsm(CallSite CS) { 5662 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 5663 5664 /// ConstraintOperands - Information about all of the constraints. 5665 std::vector<SDISelAsmOperandInfo> ConstraintOperands; 5666 5667 std::set<unsigned> OutputRegs, InputRegs; 5668 5669 // Do a prepass over the constraints, canonicalizing them, and building up the 5670 // ConstraintOperands list. 5671 std::vector<InlineAsm::ConstraintInfo> 5672 ConstraintInfos = IA->ParseConstraints(); 5673 5674 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI); 5675 5676 SDValue Chain, Flag; 5677 5678 // We won't need to flush pending loads if this asm doesn't touch 5679 // memory and is nonvolatile. 5680 if (hasMemory || IA->hasSideEffects()) 5681 Chain = getRoot(); 5682 else 5683 Chain = DAG.getRoot(); 5684 5685 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5686 unsigned ResNo = 0; // ResNo - The result number of the next output. 5687 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) { 5688 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i])); 5689 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 5690 5691 EVT OpVT = MVT::Other; 5692 5693 // Compute the value type for each operand. 5694 switch (OpInfo.Type) { 5695 case InlineAsm::isOutput: 5696 // Indirect outputs just consume an argument. 5697 if (OpInfo.isIndirect) { 5698 OpInfo.CallOperandVal = CS.getArgument(ArgNo++); 5699 break; 5700 } 5701 5702 // The return value of the call is this value. As such, there is no 5703 // corresponding argument. 5704 assert(!CS.getType()->isVoidTy() && 5705 "Bad inline asm!"); 5706 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) { 5707 OpVT = TLI.getValueType(STy->getElementType(ResNo)); 5708 } else { 5709 assert(ResNo == 0 && "Asm only has one result!"); 5710 OpVT = TLI.getValueType(CS.getType()); 5711 } 5712 ++ResNo; 5713 break; 5714 case InlineAsm::isInput: 5715 OpInfo.CallOperandVal = CS.getArgument(ArgNo++); 5716 break; 5717 case InlineAsm::isClobber: 5718 // Nothing to do. 5719 break; 5720 } 5721 5722 // If this is an input or an indirect output, process the call argument. 5723 // BasicBlocks are labels, currently appearing only in asm's. 5724 if (OpInfo.CallOperandVal) { 5725 // Strip bitcasts, if any. This mostly comes up for functions. 5726 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts(); 5727 5728 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 5729 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 5730 } else { 5731 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 5732 } 5733 5734 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD); 5735 } 5736 5737 OpInfo.ConstraintVT = OpVT; 5738 } 5739 5740 // Second pass over the constraints: compute which constraint option to use 5741 // and assign registers to constraints that want a specific physreg. 5742 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) { 5743 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5744 5745 // If this is an output operand with a matching input operand, look up the 5746 // matching input. If their types mismatch, e.g. one is an integer, the 5747 // other is floating point, or their sizes are different, flag it as an 5748 // error. 5749 if (OpInfo.hasMatchingInput()) { 5750 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5751 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5752 if ((OpInfo.ConstraintVT.isInteger() != 5753 Input.ConstraintVT.isInteger()) || 5754 (OpInfo.ConstraintVT.getSizeInBits() != 5755 Input.ConstraintVT.getSizeInBits())) { 5756 llvm_report_error("Unsupported asm: input constraint" 5757 " with a matching output constraint of incompatible" 5758 " type!"); 5759 } 5760 Input.ConstraintVT = OpInfo.ConstraintVT; 5761 } 5762 } 5763 5764 // Compute the constraint code and ConstraintType to use. 5765 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG); 5766 5767 // If this is a memory input, and if the operand is not indirect, do what we 5768 // need to to provide an address for the memory input. 5769 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 5770 !OpInfo.isIndirect) { 5771 assert(OpInfo.Type == InlineAsm::isInput && 5772 "Can only indirectify direct input operands!"); 5773 5774 // Memory operands really want the address of the value. If we don't have 5775 // an indirect input, put it in the constpool if we can, otherwise spill 5776 // it to a stack slot. 5777 5778 // If the operand is a float, integer, or vector constant, spill to a 5779 // constant pool entry to get its address. 5780 Value *OpVal = OpInfo.CallOperandVal; 5781 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 5782 isa<ConstantVector>(OpVal)) { 5783 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal), 5784 TLI.getPointerTy()); 5785 } else { 5786 // Otherwise, create a stack slot and emit a store to it before the 5787 // asm. 5788 const Type *Ty = OpVal->getType(); 5789 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); 5790 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty); 5791 MachineFunction &MF = DAG.getMachineFunction(); 5792 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 5793 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy()); 5794 Chain = DAG.getStore(Chain, getCurDebugLoc(), 5795 OpInfo.CallOperand, StackSlot, NULL, 0); 5796 OpInfo.CallOperand = StackSlot; 5797 } 5798 5799 // There is no longer a Value* corresponding to this operand. 5800 OpInfo.CallOperandVal = 0; 5801 5802 // It is now an indirect operand. 5803 OpInfo.isIndirect = true; 5804 } 5805 5806 // If this constraint is for a specific register, allocate it before 5807 // anything else. 5808 if (OpInfo.ConstraintType == TargetLowering::C_Register) 5809 GetRegistersForValue(OpInfo, OutputRegs, InputRegs); 5810 } 5811 5812 ConstraintInfos.clear(); 5813 5814 // Second pass - Loop over all of the operands, assigning virtual or physregs 5815 // to register class operands. 5816 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5817 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5818 5819 // C_Register operands have already been allocated, Other/Memory don't need 5820 // to be. 5821 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 5822 GetRegistersForValue(OpInfo, OutputRegs, InputRegs); 5823 } 5824 5825 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 5826 std::vector<SDValue> AsmNodeOperands; 5827 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 5828 AsmNodeOperands.push_back( 5829 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), 5830 TLI.getPointerTy())); 5831 5832 5833 // Loop over all of the inputs, copying the operand values into the 5834 // appropriate registers and processing the output regs. 5835 RegsForValue RetValRegs; 5836 5837 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 5838 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 5839 5840 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5841 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5842 5843 switch (OpInfo.Type) { 5844 case InlineAsm::isOutput: { 5845 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 5846 OpInfo.ConstraintType != TargetLowering::C_Register) { 5847 // Memory output, or 'other' output (e.g. 'X' constraint). 5848 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 5849 5850 // Add information to the INLINEASM node to know about this output. 5851 unsigned ResOpType = 4/*MEM*/ | (1<<3); 5852 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 5853 TLI.getPointerTy())); 5854 AsmNodeOperands.push_back(OpInfo.CallOperand); 5855 break; 5856 } 5857 5858 // Otherwise, this is a register or register class output. 5859 5860 // Copy the output from the appropriate register. Find a register that 5861 // we can use. 5862 if (OpInfo.AssignedRegs.Regs.empty()) { 5863 llvm_report_error("Couldn't allocate output reg for" 5864 " constraint '" + OpInfo.ConstraintCode + "'!"); 5865 } 5866 5867 // If this is an indirect operand, store through the pointer after the 5868 // asm. 5869 if (OpInfo.isIndirect) { 5870 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 5871 OpInfo.CallOperandVal)); 5872 } else { 5873 // This is the result value of the call. 5874 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 5875 // Concatenate this output onto the outputs list. 5876 RetValRegs.append(OpInfo.AssignedRegs); 5877 } 5878 5879 // Add information to the INLINEASM node to know that this register is 5880 // set. 5881 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ? 5882 6 /* EARLYCLOBBER REGDEF */ : 5883 2 /* REGDEF */ , 5884 false, 5885 0, 5886 DAG, SDNodeOrder, 5887 AsmNodeOperands); 5888 break; 5889 } 5890 case InlineAsm::isInput: { 5891 SDValue InOperandVal = OpInfo.CallOperand; 5892 5893 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint? 5894 // If this is required to match an output register we have already set, 5895 // just use its register. 5896 unsigned OperandNo = OpInfo.getMatchedOperand(); 5897 5898 // Scan until we find the definition we already emitted of this operand. 5899 // When we find it, create a RegsForValue operand. 5900 unsigned CurOp = 2; // The first operand. 5901 for (; OperandNo; --OperandNo) { 5902 // Advance to the next operand. 5903 unsigned OpFlag = 5904 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 5905 assert(((OpFlag & 7) == 2 /*REGDEF*/ || 5906 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ || 5907 (OpFlag & 7) == 4 /*MEM*/) && 5908 "Skipped past definitions?"); 5909 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1; 5910 } 5911 5912 unsigned OpFlag = 5913 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 5914 if ((OpFlag & 7) == 2 /*REGDEF*/ 5915 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) { 5916 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 5917 if (OpInfo.isIndirect) { 5918 llvm_report_error("Don't know how to handle tied indirect " 5919 "register inputs yet!"); 5920 } 5921 RegsForValue MatchedRegs; 5922 MatchedRegs.TLI = &TLI; 5923 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType()); 5924 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType(); 5925 MatchedRegs.RegVTs.push_back(RegVT); 5926 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 5927 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag); 5928 i != e; ++i) 5929 MatchedRegs.Regs.push_back 5930 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT))); 5931 5932 // Use the produced MatchedRegs object to 5933 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), 5934 SDNodeOrder, Chain, &Flag); 5935 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, 5936 true, OpInfo.getMatchedOperand(), 5937 DAG, SDNodeOrder, AsmNodeOperands); 5938 break; 5939 } else { 5940 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!"); 5941 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 && 5942 "Unexpected number of operands"); 5943 // Add information to the INLINEASM node to know about this input. 5944 // See InlineAsm.h isUseOperandTiedToDef. 5945 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16); 5946 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag, 5947 TLI.getPointerTy())); 5948 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 5949 break; 5950 } 5951 } 5952 5953 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 5954 assert(!OpInfo.isIndirect && 5955 "Don't know how to handle indirect other inputs yet!"); 5956 5957 std::vector<SDValue> Ops; 5958 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0], 5959 hasMemory, Ops, DAG); 5960 if (Ops.empty()) { 5961 llvm_report_error("Invalid operand for inline asm" 5962 " constraint '" + OpInfo.ConstraintCode + "'!"); 5963 } 5964 5965 // Add information to the INLINEASM node to know about this input. 5966 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3); 5967 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 5968 TLI.getPointerTy())); 5969 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 5970 break; 5971 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 5972 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 5973 assert(InOperandVal.getValueType() == TLI.getPointerTy() && 5974 "Memory operands expect pointer values"); 5975 5976 // Add information to the INLINEASM node to know about this input. 5977 unsigned ResOpType = 4/*MEM*/ | (1<<3); 5978 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 5979 TLI.getPointerTy())); 5980 AsmNodeOperands.push_back(InOperandVal); 5981 break; 5982 } 5983 5984 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 5985 OpInfo.ConstraintType == TargetLowering::C_Register) && 5986 "Unknown constraint type!"); 5987 assert(!OpInfo.isIndirect && 5988 "Don't know how to handle indirect register inputs yet!"); 5989 5990 // Copy the input into the appropriate registers. 5991 if (OpInfo.AssignedRegs.Regs.empty()) { 5992 llvm_report_error("Couldn't allocate input reg for" 5993 " constraint '"+ OpInfo.ConstraintCode +"'!"); 5994 } 5995 5996 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), 5997 SDNodeOrder, Chain, &Flag); 5998 5999 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0, 6000 DAG, SDNodeOrder, 6001 AsmNodeOperands); 6002 break; 6003 } 6004 case InlineAsm::isClobber: { 6005 // Add the clobbered value to the operand list, so that the register 6006 // allocator is aware that the physreg got clobbered. 6007 if (!OpInfo.AssignedRegs.Regs.empty()) 6008 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */, 6009 false, 0, DAG, SDNodeOrder, 6010 AsmNodeOperands); 6011 break; 6012 } 6013 } 6014 } 6015 6016 // Finish up input operands. 6017 AsmNodeOperands[0] = Chain; 6018 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 6019 6020 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(), 6021 DAG.getVTList(MVT::Other, MVT::Flag), 6022 &AsmNodeOperands[0], AsmNodeOperands.size()); 6023 Flag = Chain.getValue(1); 6024 6025 // If this asm returns a register value, copy the result from that register 6026 // and set it as the value of the call. 6027 if (!RetValRegs.Regs.empty()) { 6028 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(), 6029 SDNodeOrder, Chain, &Flag); 6030 6031 // FIXME: Why don't we do this for inline asms with MRVs? 6032 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 6033 EVT ResultType = TLI.getValueType(CS.getType()); 6034 6035 // If any of the results of the inline asm is a vector, it may have the 6036 // wrong width/num elts. This can happen for register classes that can 6037 // contain multiple different value types. The preg or vreg allocated may 6038 // not have the same VT as was expected. Convert it to the right type 6039 // with bit_convert. 6040 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 6041 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 6042 ResultType, Val); 6043 6044 } else if (ResultType != Val.getValueType() && 6045 ResultType.isInteger() && Val.getValueType().isInteger()) { 6046 // If a result value was tied to an input value, the computed result may 6047 // have a wider width than the expected result. Extract the relevant 6048 // portion. 6049 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val); 6050 } 6051 6052 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 6053 } 6054 6055 setValue(CS.getInstruction(), Val); 6056 // Don't need to use this as a chain in this case. 6057 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 6058 return; 6059 } 6060 6061 std::vector<std::pair<SDValue, Value*> > StoresToEmit; 6062 6063 // Process indirect outputs, first output all of the flagged copies out of 6064 // physregs. 6065 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 6066 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 6067 Value *Ptr = IndirectStoresToEmit[i].second; 6068 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(), 6069 SDNodeOrder, Chain, &Flag); 6070 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 6071 6072 } 6073 6074 // Emit the non-flagged stores from the physregs. 6075 SmallVector<SDValue, 8> OutChains; 6076 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 6077 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(), 6078 StoresToEmit[i].first, 6079 getValue(StoresToEmit[i].second), 6080 StoresToEmit[i].second, 0); 6081 OutChains.push_back(Val); 6082 } 6083 6084 if (!OutChains.empty()) 6085 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 6086 &OutChains[0], OutChains.size()); 6087 6088 DAG.setRoot(Chain); 6089 } 6090 6091 void SelectionDAGBuilder::visitVAStart(CallInst &I) { 6092 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(), 6093 MVT::Other, getRoot(), 6094 getValue(I.getOperand(1)), 6095 DAG.getSrcValue(I.getOperand(1)))); 6096 } 6097 6098 void SelectionDAGBuilder::visitVAArg(VAArgInst &I) { 6099 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(), 6100 getRoot(), getValue(I.getOperand(0)), 6101 DAG.getSrcValue(I.getOperand(0))); 6102 setValue(&I, V); 6103 DAG.setRoot(V.getValue(1)); 6104 } 6105 6106 void SelectionDAGBuilder::visitVAEnd(CallInst &I) { 6107 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(), 6108 MVT::Other, getRoot(), 6109 getValue(I.getOperand(1)), 6110 DAG.getSrcValue(I.getOperand(1)))); 6111 } 6112 6113 void SelectionDAGBuilder::visitVACopy(CallInst &I) { 6114 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(), 6115 MVT::Other, getRoot(), 6116 getValue(I.getOperand(1)), 6117 getValue(I.getOperand(2)), 6118 DAG.getSrcValue(I.getOperand(1)), 6119 DAG.getSrcValue(I.getOperand(2)))); 6120 } 6121 6122 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 6123 /// implementation, which just calls LowerCall. 6124 /// FIXME: When all targets are 6125 /// migrated to using LowerCall, this hook should be integrated into SDISel. 6126 std::pair<SDValue, SDValue> 6127 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy, 6128 bool RetSExt, bool RetZExt, bool isVarArg, 6129 bool isInreg, unsigned NumFixedArgs, 6130 CallingConv::ID CallConv, bool isTailCall, 6131 bool isReturnValueUsed, 6132 SDValue Callee, 6133 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl, 6134 unsigned Order) { 6135 // Handle all of the outgoing arguments. 6136 SmallVector<ISD::OutputArg, 32> Outs; 6137 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 6138 SmallVector<EVT, 4> ValueVTs; 6139 ComputeValueVTs(*this, Args[i].Ty, ValueVTs); 6140 for (unsigned Value = 0, NumValues = ValueVTs.size(); 6141 Value != NumValues; ++Value) { 6142 EVT VT = ValueVTs[Value]; 6143 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext()); 6144 SDValue Op = SDValue(Args[i].Node.getNode(), 6145 Args[i].Node.getResNo() + Value); 6146 ISD::ArgFlagsTy Flags; 6147 unsigned OriginalAlignment = 6148 getTargetData()->getABITypeAlignment(ArgTy); 6149 6150 if (Args[i].isZExt) 6151 Flags.setZExt(); 6152 if (Args[i].isSExt) 6153 Flags.setSExt(); 6154 if (Args[i].isInReg) 6155 Flags.setInReg(); 6156 if (Args[i].isSRet) 6157 Flags.setSRet(); 6158 if (Args[i].isByVal) { 6159 Flags.setByVal(); 6160 const PointerType *Ty = cast<PointerType>(Args[i].Ty); 6161 const Type *ElementTy = Ty->getElementType(); 6162 unsigned FrameAlign = getByValTypeAlignment(ElementTy); 6163 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy); 6164 // For ByVal, alignment should come from FE. BE will guess if this 6165 // info is not there but there are cases it cannot get right. 6166 if (Args[i].Alignment) 6167 FrameAlign = Args[i].Alignment; 6168 Flags.setByValAlign(FrameAlign); 6169 Flags.setByValSize(FrameSize); 6170 } 6171 if (Args[i].isNest) 6172 Flags.setNest(); 6173 Flags.setOrigAlign(OriginalAlignment); 6174 6175 EVT PartVT = getRegisterType(RetTy->getContext(), VT); 6176 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT); 6177 SmallVector<SDValue, 4> Parts(NumParts); 6178 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 6179 6180 if (Args[i].isSExt) 6181 ExtendKind = ISD::SIGN_EXTEND; 6182 else if (Args[i].isZExt) 6183 ExtendKind = ISD::ZERO_EXTEND; 6184 6185 getCopyToParts(DAG, dl, Order, Op, &Parts[0], NumParts, 6186 PartVT, ExtendKind); 6187 6188 for (unsigned j = 0; j != NumParts; ++j) { 6189 // if it isn't first piece, alignment must be 1 6190 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs); 6191 if (NumParts > 1 && j == 0) 6192 MyFlags.Flags.setSplit(); 6193 else if (j != 0) 6194 MyFlags.Flags.setOrigAlign(1); 6195 6196 Outs.push_back(MyFlags); 6197 } 6198 } 6199 } 6200 6201 // Handle the incoming return values from the call. 6202 SmallVector<ISD::InputArg, 32> Ins; 6203 SmallVector<EVT, 4> RetTys; 6204 ComputeValueVTs(*this, RetTy, RetTys); 6205 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 6206 EVT VT = RetTys[I]; 6207 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT); 6208 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT); 6209 for (unsigned i = 0; i != NumRegs; ++i) { 6210 ISD::InputArg MyFlags; 6211 MyFlags.VT = RegisterVT; 6212 MyFlags.Used = isReturnValueUsed; 6213 if (RetSExt) 6214 MyFlags.Flags.setSExt(); 6215 if (RetZExt) 6216 MyFlags.Flags.setZExt(); 6217 if (isInreg) 6218 MyFlags.Flags.setInReg(); 6219 Ins.push_back(MyFlags); 6220 } 6221 } 6222 6223 SmallVector<SDValue, 4> InVals; 6224 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall, 6225 Outs, Ins, dl, DAG, InVals); 6226 6227 // Verify that the target's LowerCall behaved as expected. 6228 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 6229 "LowerCall didn't return a valid chain!"); 6230 assert((!isTailCall || InVals.empty()) && 6231 "LowerCall emitted a return value for a tail call!"); 6232 assert((isTailCall || InVals.size() == Ins.size()) && 6233 "LowerCall didn't emit the correct number of values!"); 6234 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 6235 assert(InVals[i].getNode() && 6236 "LowerCall emitted a null value!"); 6237 assert(Ins[i].VT == InVals[i].getValueType() && 6238 "LowerCall emitted a value with the wrong type!"); 6239 }); 6240 6241 DAG.AssignOrdering(Chain.getNode(), Order); 6242 6243 // For a tail call, the return value is merely live-out and there aren't 6244 // any nodes in the DAG representing it. Return a special value to 6245 // indicate that a tail call has been emitted and no more Instructions 6246 // should be processed in the current block. 6247 if (isTailCall) { 6248 DAG.setRoot(Chain); 6249 return std::make_pair(SDValue(), SDValue()); 6250 } 6251 6252 // Collect the legal value parts into potentially illegal values 6253 // that correspond to the original function's return values. 6254 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6255 if (RetSExt) 6256 AssertOp = ISD::AssertSext; 6257 else if (RetZExt) 6258 AssertOp = ISD::AssertZext; 6259 SmallVector<SDValue, 4> ReturnValues; 6260 unsigned CurReg = 0; 6261 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 6262 EVT VT = RetTys[I]; 6263 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT); 6264 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT); 6265 6266 SDValue ReturnValue = 6267 getCopyFromParts(DAG, dl, Order, &InVals[CurReg], NumRegs, 6268 RegisterVT, VT, AssertOp); 6269 ReturnValues.push_back(ReturnValue); 6270 DAG.AssignOrdering(ReturnValue.getNode(), Order); 6271 CurReg += NumRegs; 6272 } 6273 6274 // For a function returning void, there is no return value. We can't create 6275 // such a node, so we just return a null return value in that case. In 6276 // that case, nothing will actualy look at the value. 6277 if (ReturnValues.empty()) 6278 return std::make_pair(SDValue(), Chain); 6279 6280 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 6281 DAG.getVTList(&RetTys[0], RetTys.size()), 6282 &ReturnValues[0], ReturnValues.size()); 6283 DAG.AssignOrdering(Res.getNode(), Order); 6284 return std::make_pair(Res, Chain); 6285 } 6286 6287 void TargetLowering::LowerOperationWrapper(SDNode *N, 6288 SmallVectorImpl<SDValue> &Results, 6289 SelectionDAG &DAG) { 6290 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 6291 if (Res.getNode()) 6292 Results.push_back(Res); 6293 } 6294 6295 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { 6296 llvm_unreachable("LowerOperation not implemented for this target!"); 6297 return SDValue(); 6298 } 6299 6300 void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) { 6301 SDValue Op = getValue(V); 6302 assert((Op.getOpcode() != ISD::CopyFromReg || 6303 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 6304 "Copy from a reg to the same reg!"); 6305 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 6306 6307 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType()); 6308 SDValue Chain = DAG.getEntryNode(); 6309 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), SDNodeOrder, Chain, 0); 6310 PendingExports.push_back(Chain); 6311 } 6312 6313 #include "llvm/CodeGen/SelectionDAGISel.h" 6314 6315 void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) { 6316 // If this is the entry block, emit arguments. 6317 Function &F = *LLVMBB->getParent(); 6318 SelectionDAG &DAG = SDB->DAG; 6319 SDValue OldRoot = DAG.getRoot(); 6320 DebugLoc dl = SDB->getCurDebugLoc(); 6321 const TargetData *TD = TLI.getTargetData(); 6322 SmallVector<ISD::InputArg, 16> Ins; 6323 6324 // Check whether the function can return without sret-demotion. 6325 SmallVector<EVT, 4> OutVTs; 6326 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags; 6327 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(), 6328 OutVTs, OutsFlags, TLI); 6329 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo(); 6330 6331 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(), 6332 OutVTs, OutsFlags, DAG); 6333 if (!FLI.CanLowerReturn) { 6334 // Put in an sret pointer parameter before all the other parameters. 6335 SmallVector<EVT, 1> ValueVTs; 6336 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 6337 6338 // NOTE: Assuming that a pointer will never break down to more than one VT 6339 // or one register. 6340 ISD::ArgFlagsTy Flags; 6341 Flags.setSRet(); 6342 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]); 6343 ISD::InputArg RetArg(Flags, RegisterVT, true); 6344 Ins.push_back(RetArg); 6345 } 6346 6347 // Set up the incoming argument description vector. 6348 unsigned Idx = 1; 6349 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); 6350 I != E; ++I, ++Idx) { 6351 SmallVector<EVT, 4> ValueVTs; 6352 ComputeValueVTs(TLI, I->getType(), ValueVTs); 6353 bool isArgValueUsed = !I->use_empty(); 6354 for (unsigned Value = 0, NumValues = ValueVTs.size(); 6355 Value != NumValues; ++Value) { 6356 EVT VT = ValueVTs[Value]; 6357 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 6358 ISD::ArgFlagsTy Flags; 6359 unsigned OriginalAlignment = 6360 TD->getABITypeAlignment(ArgTy); 6361 6362 if (F.paramHasAttr(Idx, Attribute::ZExt)) 6363 Flags.setZExt(); 6364 if (F.paramHasAttr(Idx, Attribute::SExt)) 6365 Flags.setSExt(); 6366 if (F.paramHasAttr(Idx, Attribute::InReg)) 6367 Flags.setInReg(); 6368 if (F.paramHasAttr(Idx, Attribute::StructRet)) 6369 Flags.setSRet(); 6370 if (F.paramHasAttr(Idx, Attribute::ByVal)) { 6371 Flags.setByVal(); 6372 const PointerType *Ty = cast<PointerType>(I->getType()); 6373 const Type *ElementTy = Ty->getElementType(); 6374 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy); 6375 unsigned FrameSize = TD->getTypeAllocSize(ElementTy); 6376 // For ByVal, alignment should be passed from FE. BE will guess if 6377 // this info is not there but there are cases it cannot get right. 6378 if (F.getParamAlignment(Idx)) 6379 FrameAlign = F.getParamAlignment(Idx); 6380 Flags.setByValAlign(FrameAlign); 6381 Flags.setByValSize(FrameSize); 6382 } 6383 if (F.paramHasAttr(Idx, Attribute::Nest)) 6384 Flags.setNest(); 6385 Flags.setOrigAlign(OriginalAlignment); 6386 6387 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6388 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT); 6389 for (unsigned i = 0; i != NumRegs; ++i) { 6390 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed); 6391 if (NumRegs > 1 && i == 0) 6392 MyFlags.Flags.setSplit(); 6393 // if it isn't first piece, alignment must be 1 6394 else if (i > 0) 6395 MyFlags.Flags.setOrigAlign(1); 6396 Ins.push_back(MyFlags); 6397 } 6398 } 6399 } 6400 6401 // Call the target to set up the argument values. 6402 SmallVector<SDValue, 8> InVals; 6403 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(), 6404 F.isVarArg(), Ins, 6405 dl, DAG, InVals); 6406 6407 // Verify that the target's LowerFormalArguments behaved as expected. 6408 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 6409 "LowerFormalArguments didn't return a valid chain!"); 6410 assert(InVals.size() == Ins.size() && 6411 "LowerFormalArguments didn't emit the correct number of values!"); 6412 DEBUG({ 6413 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 6414 assert(InVals[i].getNode() && 6415 "LowerFormalArguments emitted a null value!"); 6416 assert(Ins[i].VT == InVals[i].getValueType() && 6417 "LowerFormalArguments emitted a value with the wrong type!"); 6418 } 6419 }); 6420 6421 // Update the DAG with the new chain value resulting from argument lowering. 6422 DAG.setRoot(NewRoot); 6423 6424 // Set up the argument values. 6425 unsigned i = 0; 6426 Idx = 1; 6427 if (!FLI.CanLowerReturn) { 6428 // Create a virtual register for the sret pointer, and put in a copy 6429 // from the sret argument into it. 6430 SmallVector<EVT, 1> ValueVTs; 6431 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 6432 EVT VT = ValueVTs[0]; 6433 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6434 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6435 SDValue ArgValue = getCopyFromParts(DAG, dl, 0, &InVals[0], 1, 6436 RegVT, VT, AssertOp); 6437 6438 MachineFunction& MF = SDB->DAG.getMachineFunction(); 6439 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 6440 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)); 6441 FLI.DemoteRegister = SRetReg; 6442 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), 6443 SRetReg, ArgValue); 6444 DAG.setRoot(NewRoot); 6445 6446 // i indexes lowered arguments. Bump it past the hidden sret argument. 6447 // Idx indexes LLVM arguments. Don't touch it. 6448 ++i; 6449 } 6450 6451 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 6452 ++I, ++Idx) { 6453 SmallVector<SDValue, 4> ArgValues; 6454 SmallVector<EVT, 4> ValueVTs; 6455 ComputeValueVTs(TLI, I->getType(), ValueVTs); 6456 unsigned NumValues = ValueVTs.size(); 6457 for (unsigned Value = 0; Value != NumValues; ++Value) { 6458 EVT VT = ValueVTs[Value]; 6459 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6460 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT); 6461 6462 if (!I->use_empty()) { 6463 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6464 if (F.paramHasAttr(Idx, Attribute::SExt)) 6465 AssertOp = ISD::AssertSext; 6466 else if (F.paramHasAttr(Idx, Attribute::ZExt)) 6467 AssertOp = ISD::AssertZext; 6468 6469 ArgValues.push_back(getCopyFromParts(DAG, dl, 0, &InVals[i], 6470 NumParts, PartVT, VT, 6471 AssertOp)); 6472 } 6473 6474 i += NumParts; 6475 } 6476 6477 if (!I->use_empty()) { 6478 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues, 6479 SDB->getCurDebugLoc()); 6480 SDB->setValue(I, Res); 6481 6482 // If this argument is live outside of the entry block, insert a copy from 6483 // whereever we got it to the vreg that other BB's will reference it as. 6484 SDB->CopyToExportRegsIfNeeded(I); 6485 } 6486 } 6487 6488 assert(i == InVals.size() && "Argument register count mismatch!"); 6489 6490 // Finally, if the target has anything special to do, allow it to do so. 6491 // FIXME: this should insert code into the DAG! 6492 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction()); 6493 } 6494 6495 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 6496 /// ensure constants are generated when needed. Remember the virtual registers 6497 /// that need to be added to the Machine PHI nodes as input. We cannot just 6498 /// directly add them, because expansion might result in multiple MBB's for one 6499 /// BB. As such, the start of the BB might correspond to a different MBB than 6500 /// the end. 6501 /// 6502 void 6503 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) { 6504 TerminatorInst *TI = LLVMBB->getTerminator(); 6505 6506 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 6507 6508 // Check successor nodes' PHI nodes that expect a constant to be available 6509 // from this block. 6510 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 6511 BasicBlock *SuccBB = TI->getSuccessor(succ); 6512 if (!isa<PHINode>(SuccBB->begin())) continue; 6513 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB]; 6514 6515 // If this terminator has multiple identical successors (common for 6516 // switches), only handle each succ once. 6517 if (!SuccsHandled.insert(SuccMBB)) continue; 6518 6519 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 6520 PHINode *PN; 6521 6522 // At this point we know that there is a 1-1 correspondence between LLVM PHI 6523 // nodes and Machine PHI nodes, but the incoming operands have not been 6524 // emitted yet. 6525 for (BasicBlock::iterator I = SuccBB->begin(); 6526 (PN = dyn_cast<PHINode>(I)); ++I) { 6527 // Ignore dead phi's. 6528 if (PN->use_empty()) continue; 6529 6530 unsigned Reg; 6531 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 6532 6533 if (Constant *C = dyn_cast<Constant>(PHIOp)) { 6534 unsigned &RegOut = SDB->ConstantsOut[C]; 6535 if (RegOut == 0) { 6536 RegOut = FuncInfo->CreateRegForValue(C); 6537 SDB->CopyValueToVirtualRegister(C, RegOut); 6538 } 6539 Reg = RegOut; 6540 } else { 6541 Reg = FuncInfo->ValueMap[PHIOp]; 6542 if (Reg == 0) { 6543 assert(isa<AllocaInst>(PHIOp) && 6544 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 6545 "Didn't codegen value into a register!??"); 6546 Reg = FuncInfo->CreateRegForValue(PHIOp); 6547 SDB->CopyValueToVirtualRegister(PHIOp, Reg); 6548 } 6549 } 6550 6551 // Remember that this register needs to added to the machine PHI node as 6552 // the input for this MBB. 6553 SmallVector<EVT, 4> ValueVTs; 6554 ComputeValueVTs(TLI, PN->getType(), ValueVTs); 6555 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 6556 EVT VT = ValueVTs[vti]; 6557 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT); 6558 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 6559 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 6560 Reg += NumRegisters; 6561 } 6562 } 6563 } 6564 SDB->ConstantsOut.clear(); 6565 } 6566 6567 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only 6568 /// supports legal types, and it emits MachineInstrs directly instead of 6569 /// creating SelectionDAG nodes. 6570 /// 6571 bool 6572 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB, 6573 FastISel *F) { 6574 TerminatorInst *TI = LLVMBB->getTerminator(); 6575 6576 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 6577 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size(); 6578 6579 // Check successor nodes' PHI nodes that expect a constant to be available 6580 // from this block. 6581 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 6582 BasicBlock *SuccBB = TI->getSuccessor(succ); 6583 if (!isa<PHINode>(SuccBB->begin())) continue; 6584 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB]; 6585 6586 // If this terminator has multiple identical successors (common for 6587 // switches), only handle each succ once. 6588 if (!SuccsHandled.insert(SuccMBB)) continue; 6589 6590 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 6591 PHINode *PN; 6592 6593 // At this point we know that there is a 1-1 correspondence between LLVM PHI 6594 // nodes and Machine PHI nodes, but the incoming operands have not been 6595 // emitted yet. 6596 for (BasicBlock::iterator I = SuccBB->begin(); 6597 (PN = dyn_cast<PHINode>(I)); ++I) { 6598 // Ignore dead phi's. 6599 if (PN->use_empty()) continue; 6600 6601 // Only handle legal types. Two interesting things to note here. First, 6602 // by bailing out early, we may leave behind some dead instructions, 6603 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its 6604 // own moves. Second, this check is necessary becuase FastISel doesn't 6605 // use CreateRegForValue to create registers, so it always creates 6606 // exactly one register for each non-void instruction. 6607 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true); 6608 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) { 6609 // Promote MVT::i1. 6610 if (VT == MVT::i1) 6611 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT); 6612 else { 6613 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate); 6614 return false; 6615 } 6616 } 6617 6618 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 6619 6620 unsigned Reg = F->getRegForValue(PHIOp); 6621 if (Reg == 0) { 6622 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate); 6623 return false; 6624 } 6625 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg)); 6626 } 6627 } 6628 6629 return true; 6630 } 6631