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