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