1 //===- FastISel.cpp - Implementation of the FastISel class ----------------===// 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 file contains the implementation of the FastISel class. 11 // 12 // "Fast" instruction selection is designed to emit very poor code quickly. 13 // Also, it is not designed to be able to do much lowering, so most illegal 14 // types (e.g. i64 on 32-bit targets) and operations are not supported. It is 15 // also not intended to be able to do much optimization, except in a few cases 16 // where doing optimizations reduces overall compile time. For example, folding 17 // constants into immediate fields is often done, because it's cheap and it 18 // reduces the number of instructions later phases have to examine. 19 // 20 // "Fast" instruction selection is able to fail gracefully and transfer 21 // control to the SelectionDAG selector for operations that it doesn't 22 // support. In many cases, this allows us to avoid duplicating a lot of 23 // the complicated lowering logic that SelectionDAG currently has. 24 // 25 // The intended use for "fast" instruction selection is "-O0" mode 26 // compilation, where the quality of the generated code is irrelevant when 27 // weighed against the speed at which the code can be generated. Also, 28 // at -O0, the LLVM optimizers are not running, and this makes the 29 // compile time of codegen a much higher portion of the overall compile 30 // time. Despite its limitations, "fast" instruction selection is able to 31 // handle enough code on its own to provide noticeable overall speedups 32 // in -O0 compiles. 33 // 34 // Basic operations are supported in a target-independent way, by reading 35 // the same instruction descriptions that the SelectionDAG selector reads, 36 // and identifying simple arithmetic operations that can be directly selected 37 // from simple operators. More complicated operations currently require 38 // target-specific code. 39 // 40 //===----------------------------------------------------------------------===// 41 42 #include "llvm/CodeGen/FastISel.h" 43 #include "llvm/ADT/APFloat.h" 44 #include "llvm/ADT/APSInt.h" 45 #include "llvm/ADT/DenseMap.h" 46 #include "llvm/ADT/Optional.h" 47 #include "llvm/ADT/SmallPtrSet.h" 48 #include "llvm/ADT/SmallString.h" 49 #include "llvm/ADT/SmallVector.h" 50 #include "llvm/ADT/Statistic.h" 51 #include "llvm/Analysis/BranchProbabilityInfo.h" 52 #include "llvm/Analysis/TargetLibraryInfo.h" 53 #include "llvm/CodeGen/Analysis.h" 54 #include "llvm/CodeGen/FunctionLoweringInfo.h" 55 #include "llvm/CodeGen/ISDOpcodes.h" 56 #include "llvm/CodeGen/MachineBasicBlock.h" 57 #include "llvm/CodeGen/MachineFrameInfo.h" 58 #include "llvm/CodeGen/MachineInstr.h" 59 #include "llvm/CodeGen/MachineInstrBuilder.h" 60 #include "llvm/CodeGen/MachineMemOperand.h" 61 #include "llvm/CodeGen/MachineModuleInfo.h" 62 #include "llvm/CodeGen/MachineOperand.h" 63 #include "llvm/CodeGen/MachineRegisterInfo.h" 64 #include "llvm/CodeGen/StackMaps.h" 65 #include "llvm/CodeGen/TargetInstrInfo.h" 66 #include "llvm/CodeGen/TargetLowering.h" 67 #include "llvm/CodeGen/TargetSubtargetInfo.h" 68 #include "llvm/CodeGen/ValueTypes.h" 69 #include "llvm/IR/Argument.h" 70 #include "llvm/IR/Attributes.h" 71 #include "llvm/IR/BasicBlock.h" 72 #include "llvm/IR/CallSite.h" 73 #include "llvm/IR/CallingConv.h" 74 #include "llvm/IR/Constant.h" 75 #include "llvm/IR/Constants.h" 76 #include "llvm/IR/DataLayout.h" 77 #include "llvm/IR/DebugInfo.h" 78 #include "llvm/IR/DebugLoc.h" 79 #include "llvm/IR/DerivedTypes.h" 80 #include "llvm/IR/Function.h" 81 #include "llvm/IR/GetElementPtrTypeIterator.h" 82 #include "llvm/IR/GlobalValue.h" 83 #include "llvm/IR/InlineAsm.h" 84 #include "llvm/IR/InstrTypes.h" 85 #include "llvm/IR/Instruction.h" 86 #include "llvm/IR/Instructions.h" 87 #include "llvm/IR/IntrinsicInst.h" 88 #include "llvm/IR/LLVMContext.h" 89 #include "llvm/IR/Mangler.h" 90 #include "llvm/IR/Metadata.h" 91 #include "llvm/IR/Operator.h" 92 #include "llvm/IR/Type.h" 93 #include "llvm/IR/User.h" 94 #include "llvm/IR/Value.h" 95 #include "llvm/MC/MCContext.h" 96 #include "llvm/MC/MCInstrDesc.h" 97 #include "llvm/MC/MCRegisterInfo.h" 98 #include "llvm/Support/Casting.h" 99 #include "llvm/Support/Debug.h" 100 #include "llvm/Support/ErrorHandling.h" 101 #include "llvm/Support/MachineValueType.h" 102 #include "llvm/Support/MathExtras.h" 103 #include "llvm/Support/raw_ostream.h" 104 #include "llvm/Target/TargetMachine.h" 105 #include "llvm/Target/TargetOptions.h" 106 #include <algorithm> 107 #include <cassert> 108 #include <cstdint> 109 #include <iterator> 110 #include <utility> 111 112 using namespace llvm; 113 114 #define DEBUG_TYPE "isel" 115 116 // FIXME: Remove this after the feature has proven reliable. 117 static cl::opt<bool> SinkLocalValues("fast-isel-sink-local-values", 118 cl::init(true), cl::Hidden, 119 cl::desc("Sink local values in FastISel")); 120 121 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by " 122 "target-independent selector"); 123 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by " 124 "target-specific selector"); 125 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure"); 126 127 /// Set the current block to which generated machine instructions will be 128 /// appended. 129 void FastISel::startNewBlock() { 130 assert(LocalValueMap.empty() && 131 "local values should be cleared after finishing a BB"); 132 133 // Instructions are appended to FuncInfo.MBB. If the basic block already 134 // contains labels or copies, use the last instruction as the last local 135 // value. 136 EmitStartPt = nullptr; 137 if (!FuncInfo.MBB->empty()) 138 EmitStartPt = &FuncInfo.MBB->back(); 139 LastLocalValue = EmitStartPt; 140 } 141 142 /// Flush the local CSE map and sink anything we can. 143 void FastISel::finishBasicBlock() { flushLocalValueMap(); } 144 145 bool FastISel::lowerArguments() { 146 if (!FuncInfo.CanLowerReturn) 147 // Fallback to SDISel argument lowering code to deal with sret pointer 148 // parameter. 149 return false; 150 151 if (!fastLowerArguments()) 152 return false; 153 154 // Enter arguments into ValueMap for uses in non-entry BBs. 155 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(), 156 E = FuncInfo.Fn->arg_end(); 157 I != E; ++I) { 158 DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(&*I); 159 assert(VI != LocalValueMap.end() && "Missed an argument?"); 160 FuncInfo.ValueMap[&*I] = VI->second; 161 } 162 return true; 163 } 164 165 /// Return the defined register if this instruction defines exactly one 166 /// virtual register and uses no other virtual registers. Otherwise return 0. 167 static unsigned findSinkableLocalRegDef(MachineInstr &MI) { 168 unsigned RegDef = 0; 169 for (const MachineOperand &MO : MI.operands()) { 170 if (!MO.isReg()) 171 continue; 172 if (MO.isDef()) { 173 if (RegDef) 174 return 0; 175 RegDef = MO.getReg(); 176 } else if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) { 177 // This is another use of a vreg. Don't try to sink it. 178 return 0; 179 } 180 } 181 return RegDef; 182 } 183 184 void FastISel::flushLocalValueMap() { 185 // Try to sink local values down to their first use so that we can give them a 186 // better debug location. This has the side effect of shrinking local value 187 // live ranges, which helps out fast regalloc. 188 if (SinkLocalValues && LastLocalValue != EmitStartPt) { 189 // Sink local value materialization instructions between EmitStartPt and 190 // LastLocalValue. Visit them bottom-up, starting from LastLocalValue, to 191 // avoid inserting into the range that we're iterating over. 192 MachineBasicBlock::reverse_iterator RE = 193 EmitStartPt ? MachineBasicBlock::reverse_iterator(EmitStartPt) 194 : FuncInfo.MBB->rend(); 195 MachineBasicBlock::reverse_iterator RI(LastLocalValue); 196 197 InstOrderMap OrderMap; 198 for (; RI != RE;) { 199 MachineInstr &LocalMI = *RI; 200 ++RI; 201 bool Store = true; 202 if (!LocalMI.isSafeToMove(nullptr, Store)) 203 continue; 204 unsigned DefReg = findSinkableLocalRegDef(LocalMI); 205 if (DefReg == 0) 206 continue; 207 208 sinkLocalValueMaterialization(LocalMI, DefReg, OrderMap); 209 } 210 } 211 212 LocalValueMap.clear(); 213 LastLocalValue = EmitStartPt; 214 recomputeInsertPt(); 215 SavedInsertPt = FuncInfo.InsertPt; 216 LastFlushPoint = FuncInfo.InsertPt; 217 } 218 219 static bool isRegUsedByPhiNodes(unsigned DefReg, 220 FunctionLoweringInfo &FuncInfo) { 221 for (auto &P : FuncInfo.PHINodesToUpdate) 222 if (P.second == DefReg) 223 return true; 224 return false; 225 } 226 227 /// Build a map of instruction orders. Return the first terminator and its 228 /// order. Consider EH_LABEL instructions to be terminators as well, since local 229 /// values for phis after invokes must be materialized before the call. 230 void FastISel::InstOrderMap::initialize( 231 MachineBasicBlock *MBB, MachineBasicBlock::iterator LastFlushPoint) { 232 unsigned Order = 0; 233 for (MachineInstr &I : *MBB) { 234 if (!FirstTerminator && 235 (I.isTerminator() || (I.isEHLabel() && &I != &MBB->front()))) { 236 FirstTerminator = &I; 237 FirstTerminatorOrder = Order; 238 } 239 Orders[&I] = Order++; 240 241 // We don't need to order instructions past the last flush point. 242 if (I.getIterator() == LastFlushPoint) 243 break; 244 } 245 } 246 247 void FastISel::sinkLocalValueMaterialization(MachineInstr &LocalMI, 248 unsigned DefReg, 249 InstOrderMap &OrderMap) { 250 // If this register is used by a register fixup, MRI will not contain all 251 // the uses until after register fixups, so don't attempt to sink or DCE 252 // this instruction. Register fixups typically come from no-op cast 253 // instructions, which replace the cast instruction vreg with the local 254 // value vreg. 255 if (FuncInfo.RegsWithFixups.count(DefReg)) 256 return; 257 258 // We can DCE this instruction if there are no uses and it wasn't a 259 // materialized for a successor PHI node. 260 bool UsedByPHI = isRegUsedByPhiNodes(DefReg, FuncInfo); 261 if (!UsedByPHI && MRI.use_nodbg_empty(DefReg)) { 262 if (EmitStartPt == &LocalMI) 263 EmitStartPt = EmitStartPt->getPrevNode(); 264 DEBUG(dbgs() << "removing dead local value materialization " << LocalMI); 265 OrderMap.Orders.erase(&LocalMI); 266 LocalMI.eraseFromParent(); 267 return; 268 } 269 270 // Number the instructions if we haven't yet so we can efficiently find the 271 // earliest use. 272 if (OrderMap.Orders.empty()) 273 OrderMap.initialize(FuncInfo.MBB, LastFlushPoint); 274 275 // Find the first user in the BB. 276 MachineInstr *FirstUser = nullptr; 277 unsigned FirstOrder = std::numeric_limits<unsigned>::max(); 278 for (MachineInstr &UseInst : MRI.use_nodbg_instructions(DefReg)) { 279 auto I = OrderMap.Orders.find(&UseInst); 280 assert(I != OrderMap.Orders.end() && 281 "local value used by instruction outside local region"); 282 unsigned UseOrder = I->second; 283 if (UseOrder < FirstOrder) { 284 FirstOrder = UseOrder; 285 FirstUser = &UseInst; 286 } 287 } 288 289 // The insertion point will be the first terminator or the first user, 290 // whichever came first. If there was no terminator, this must be a 291 // fallthrough block and the insertion point is the end of the block. 292 MachineBasicBlock::instr_iterator SinkPos; 293 if (UsedByPHI && OrderMap.FirstTerminatorOrder < FirstOrder) { 294 FirstOrder = OrderMap.FirstTerminatorOrder; 295 SinkPos = OrderMap.FirstTerminator->getIterator(); 296 } else if (FirstUser) { 297 SinkPos = FirstUser->getIterator(); 298 } else { 299 assert(UsedByPHI && "must be users if not used by a phi"); 300 SinkPos = FuncInfo.MBB->instr_end(); 301 } 302 303 // Collect all DBG_VALUEs before the new insertion position so that we can 304 // sink them. 305 SmallVector<MachineInstr *, 1> DbgValues; 306 for (MachineInstr &DbgVal : MRI.use_instructions(DefReg)) { 307 if (!DbgVal.isDebugValue()) 308 continue; 309 unsigned UseOrder = OrderMap.Orders[&DbgVal]; 310 if (UseOrder < FirstOrder) 311 DbgValues.push_back(&DbgVal); 312 } 313 314 // Sink LocalMI before SinkPos and assign it the same DebugLoc. 315 DEBUG(dbgs() << "sinking local value to first use " << LocalMI); 316 FuncInfo.MBB->remove(&LocalMI); 317 FuncInfo.MBB->insert(SinkPos, &LocalMI); 318 if (SinkPos != FuncInfo.MBB->end()) 319 LocalMI.setDebugLoc(SinkPos->getDebugLoc()); 320 321 // Sink any debug values that we've collected. 322 for (MachineInstr *DI : DbgValues) { 323 FuncInfo.MBB->remove(DI); 324 FuncInfo.MBB->insert(SinkPos, DI); 325 } 326 } 327 328 bool FastISel::hasTrivialKill(const Value *V) { 329 // Don't consider constants or arguments to have trivial kills. 330 const Instruction *I = dyn_cast<Instruction>(V); 331 if (!I) 332 return false; 333 334 // No-op casts are trivially coalesced by fast-isel. 335 if (const auto *Cast = dyn_cast<CastInst>(I)) 336 if (Cast->isNoopCast(DL) && !hasTrivialKill(Cast->getOperand(0))) 337 return false; 338 339 // Even the value might have only one use in the LLVM IR, it is possible that 340 // FastISel might fold the use into another instruction and now there is more 341 // than one use at the Machine Instruction level. 342 unsigned Reg = lookUpRegForValue(V); 343 if (Reg && !MRI.use_empty(Reg)) 344 return false; 345 346 // GEPs with all zero indices are trivially coalesced by fast-isel. 347 if (const auto *GEP = dyn_cast<GetElementPtrInst>(I)) 348 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0))) 349 return false; 350 351 // Only instructions with a single use in the same basic block are considered 352 // to have trivial kills. 353 return I->hasOneUse() && 354 !(I->getOpcode() == Instruction::BitCast || 355 I->getOpcode() == Instruction::PtrToInt || 356 I->getOpcode() == Instruction::IntToPtr) && 357 cast<Instruction>(*I->user_begin())->getParent() == I->getParent(); 358 } 359 360 unsigned FastISel::getRegForValue(const Value *V) { 361 EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true); 362 // Don't handle non-simple values in FastISel. 363 if (!RealVT.isSimple()) 364 return 0; 365 366 // Ignore illegal types. We must do this before looking up the value 367 // in ValueMap because Arguments are given virtual registers regardless 368 // of whether FastISel can handle them. 369 MVT VT = RealVT.getSimpleVT(); 370 if (!TLI.isTypeLegal(VT)) { 371 // Handle integer promotions, though, because they're common and easy. 372 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16) 373 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT(); 374 else 375 return 0; 376 } 377 378 // Look up the value to see if we already have a register for it. 379 unsigned Reg = lookUpRegForValue(V); 380 if (Reg) 381 return Reg; 382 383 // In bottom-up mode, just create the virtual register which will be used 384 // to hold the value. It will be materialized later. 385 if (isa<Instruction>(V) && 386 (!isa<AllocaInst>(V) || 387 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V)))) 388 return FuncInfo.InitializeRegForValue(V); 389 390 SavePoint SaveInsertPt = enterLocalValueArea(); 391 392 // Materialize the value in a register. Emit any instructions in the 393 // local value area. 394 Reg = materializeRegForValue(V, VT); 395 396 leaveLocalValueArea(SaveInsertPt); 397 398 return Reg; 399 } 400 401 unsigned FastISel::materializeConstant(const Value *V, MVT VT) { 402 unsigned Reg = 0; 403 if (const auto *CI = dyn_cast<ConstantInt>(V)) { 404 if (CI->getValue().getActiveBits() <= 64) 405 Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue()); 406 } else if (isa<AllocaInst>(V)) 407 Reg = fastMaterializeAlloca(cast<AllocaInst>(V)); 408 else if (isa<ConstantPointerNull>(V)) 409 // Translate this as an integer zero so that it can be 410 // local-CSE'd with actual integer zeros. 411 Reg = getRegForValue( 412 Constant::getNullValue(DL.getIntPtrType(V->getContext()))); 413 else if (const auto *CF = dyn_cast<ConstantFP>(V)) { 414 if (CF->isNullValue()) 415 Reg = fastMaterializeFloatZero(CF); 416 else 417 // Try to emit the constant directly. 418 Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF); 419 420 if (!Reg) { 421 // Try to emit the constant by using an integer constant with a cast. 422 const APFloat &Flt = CF->getValueAPF(); 423 EVT IntVT = TLI.getPointerTy(DL); 424 uint32_t IntBitWidth = IntVT.getSizeInBits(); 425 APSInt SIntVal(IntBitWidth, /*isUnsigned=*/false); 426 bool isExact; 427 (void)Flt.convertToInteger(SIntVal, APFloat::rmTowardZero, &isExact); 428 if (isExact) { 429 unsigned IntegerReg = 430 getRegForValue(ConstantInt::get(V->getContext(), SIntVal)); 431 if (IntegerReg != 0) 432 Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg, 433 /*Kill=*/false); 434 } 435 } 436 } else if (const auto *Op = dyn_cast<Operator>(V)) { 437 if (!selectOperator(Op, Op->getOpcode())) 438 if (!isa<Instruction>(Op) || 439 !fastSelectInstruction(cast<Instruction>(Op))) 440 return 0; 441 Reg = lookUpRegForValue(Op); 442 } else if (isa<UndefValue>(V)) { 443 Reg = createResultReg(TLI.getRegClassFor(VT)); 444 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 445 TII.get(TargetOpcode::IMPLICIT_DEF), Reg); 446 } 447 return Reg; 448 } 449 450 /// Helper for getRegForValue. This function is called when the value isn't 451 /// already available in a register and must be materialized with new 452 /// instructions. 453 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) { 454 unsigned Reg = 0; 455 // Give the target-specific code a try first. 456 if (isa<Constant>(V)) 457 Reg = fastMaterializeConstant(cast<Constant>(V)); 458 459 // If target-specific code couldn't or didn't want to handle the value, then 460 // give target-independent code a try. 461 if (!Reg) 462 Reg = materializeConstant(V, VT); 463 464 // Don't cache constant materializations in the general ValueMap. 465 // To do so would require tracking what uses they dominate. 466 if (Reg) { 467 LocalValueMap[V] = Reg; 468 LastLocalValue = MRI.getVRegDef(Reg); 469 } 470 return Reg; 471 } 472 473 unsigned FastISel::lookUpRegForValue(const Value *V) { 474 // Look up the value to see if we already have a register for it. We 475 // cache values defined by Instructions across blocks, and other values 476 // only locally. This is because Instructions already have the SSA 477 // def-dominates-use requirement enforced. 478 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V); 479 if (I != FuncInfo.ValueMap.end()) 480 return I->second; 481 return LocalValueMap[V]; 482 } 483 484 void FastISel::updateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) { 485 if (!isa<Instruction>(I)) { 486 LocalValueMap[I] = Reg; 487 return; 488 } 489 490 unsigned &AssignedReg = FuncInfo.ValueMap[I]; 491 if (AssignedReg == 0) 492 // Use the new register. 493 AssignedReg = Reg; 494 else if (Reg != AssignedReg) { 495 // Arrange for uses of AssignedReg to be replaced by uses of Reg. 496 for (unsigned i = 0; i < NumRegs; i++) { 497 FuncInfo.RegFixups[AssignedReg + i] = Reg + i; 498 FuncInfo.RegsWithFixups.insert(Reg + i); 499 } 500 501 AssignedReg = Reg; 502 } 503 } 504 505 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) { 506 unsigned IdxN = getRegForValue(Idx); 507 if (IdxN == 0) 508 // Unhandled operand. Halt "fast" selection and bail. 509 return std::pair<unsigned, bool>(0, false); 510 511 bool IdxNIsKill = hasTrivialKill(Idx); 512 513 // If the index is smaller or larger than intptr_t, truncate or extend it. 514 MVT PtrVT = TLI.getPointerTy(DL); 515 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false); 516 if (IdxVT.bitsLT(PtrVT)) { 517 IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN, 518 IdxNIsKill); 519 IdxNIsKill = true; 520 } else if (IdxVT.bitsGT(PtrVT)) { 521 IdxN = 522 fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN, IdxNIsKill); 523 IdxNIsKill = true; 524 } 525 return std::pair<unsigned, bool>(IdxN, IdxNIsKill); 526 } 527 528 void FastISel::recomputeInsertPt() { 529 if (getLastLocalValue()) { 530 FuncInfo.InsertPt = getLastLocalValue(); 531 FuncInfo.MBB = FuncInfo.InsertPt->getParent(); 532 ++FuncInfo.InsertPt; 533 } else 534 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI(); 535 536 // Now skip past any EH_LABELs, which must remain at the beginning. 537 while (FuncInfo.InsertPt != FuncInfo.MBB->end() && 538 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL) 539 ++FuncInfo.InsertPt; 540 } 541 542 void FastISel::removeDeadCode(MachineBasicBlock::iterator I, 543 MachineBasicBlock::iterator E) { 544 assert(I.isValid() && E.isValid() && std::distance(I, E) > 0 && 545 "Invalid iterator!"); 546 while (I != E) { 547 MachineInstr *Dead = &*I; 548 ++I; 549 Dead->eraseFromParent(); 550 ++NumFastIselDead; 551 } 552 recomputeInsertPt(); 553 } 554 555 FastISel::SavePoint FastISel::enterLocalValueArea() { 556 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt; 557 DebugLoc OldDL = DbgLoc; 558 recomputeInsertPt(); 559 DbgLoc = DebugLoc(); 560 SavePoint SP = {OldInsertPt, OldDL}; 561 return SP; 562 } 563 564 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) { 565 if (FuncInfo.InsertPt != FuncInfo.MBB->begin()) 566 LastLocalValue = &*std::prev(FuncInfo.InsertPt); 567 568 // Restore the previous insert position. 569 FuncInfo.InsertPt = OldInsertPt.InsertPt; 570 DbgLoc = OldInsertPt.DL; 571 } 572 573 bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) { 574 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true); 575 if (VT == MVT::Other || !VT.isSimple()) 576 // Unhandled type. Halt "fast" selection and bail. 577 return false; 578 579 // We only handle legal types. For example, on x86-32 the instruction 580 // selector contains all of the 64-bit instructions from x86-64, 581 // under the assumption that i64 won't be used if the target doesn't 582 // support it. 583 if (!TLI.isTypeLegal(VT)) { 584 // MVT::i1 is special. Allow AND, OR, or XOR because they 585 // don't require additional zeroing, which makes them easy. 586 if (VT == MVT::i1 && (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR || 587 ISDOpcode == ISD::XOR)) 588 VT = TLI.getTypeToTransformTo(I->getContext(), VT); 589 else 590 return false; 591 } 592 593 // Check if the first operand is a constant, and handle it as "ri". At -O0, 594 // we don't have anything that canonicalizes operand order. 595 if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0))) 596 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) { 597 unsigned Op1 = getRegForValue(I->getOperand(1)); 598 if (!Op1) 599 return false; 600 bool Op1IsKill = hasTrivialKill(I->getOperand(1)); 601 602 unsigned ResultReg = 603 fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, Op1IsKill, 604 CI->getZExtValue(), VT.getSimpleVT()); 605 if (!ResultReg) 606 return false; 607 608 // We successfully emitted code for the given LLVM Instruction. 609 updateValueMap(I, ResultReg); 610 return true; 611 } 612 613 unsigned Op0 = getRegForValue(I->getOperand(0)); 614 if (!Op0) // Unhandled operand. Halt "fast" selection and bail. 615 return false; 616 bool Op0IsKill = hasTrivialKill(I->getOperand(0)); 617 618 // Check if the second operand is a constant and handle it appropriately. 619 if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { 620 uint64_t Imm = CI->getSExtValue(); 621 622 // Transform "sdiv exact X, 8" -> "sra X, 3". 623 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) && 624 cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) { 625 Imm = Log2_64(Imm); 626 ISDOpcode = ISD::SRA; 627 } 628 629 // Transform "urem x, pow2" -> "and x, pow2-1". 630 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) && 631 isPowerOf2_64(Imm)) { 632 --Imm; 633 ISDOpcode = ISD::AND; 634 } 635 636 unsigned ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0, 637 Op0IsKill, Imm, VT.getSimpleVT()); 638 if (!ResultReg) 639 return false; 640 641 // We successfully emitted code for the given LLVM Instruction. 642 updateValueMap(I, ResultReg); 643 return true; 644 } 645 646 unsigned Op1 = getRegForValue(I->getOperand(1)); 647 if (!Op1) // Unhandled operand. Halt "fast" selection and bail. 648 return false; 649 bool Op1IsKill = hasTrivialKill(I->getOperand(1)); 650 651 // Now we have both operands in registers. Emit the instruction. 652 unsigned ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(), 653 ISDOpcode, Op0, Op0IsKill, Op1, Op1IsKill); 654 if (!ResultReg) 655 // Target-specific code wasn't able to find a machine opcode for 656 // the given ISD opcode and type. Halt "fast" selection and bail. 657 return false; 658 659 // We successfully emitted code for the given LLVM Instruction. 660 updateValueMap(I, ResultReg); 661 return true; 662 } 663 664 bool FastISel::selectGetElementPtr(const User *I) { 665 unsigned N = getRegForValue(I->getOperand(0)); 666 if (!N) // Unhandled operand. Halt "fast" selection and bail. 667 return false; 668 bool NIsKill = hasTrivialKill(I->getOperand(0)); 669 670 // Keep a running tab of the total offset to coalesce multiple N = N + Offset 671 // into a single N = N + TotalOffset. 672 uint64_t TotalOffs = 0; 673 // FIXME: What's a good SWAG number for MaxOffs? 674 uint64_t MaxOffs = 2048; 675 MVT VT = TLI.getPointerTy(DL); 676 for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I); 677 GTI != E; ++GTI) { 678 const Value *Idx = GTI.getOperand(); 679 if (StructType *StTy = GTI.getStructTypeOrNull()) { 680 uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue(); 681 if (Field) { 682 // N = N + Offset 683 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field); 684 if (TotalOffs >= MaxOffs) { 685 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 686 if (!N) // Unhandled operand. Halt "fast" selection and bail. 687 return false; 688 NIsKill = true; 689 TotalOffs = 0; 690 } 691 } 692 } else { 693 Type *Ty = GTI.getIndexedType(); 694 695 // If this is a constant subscript, handle it quickly. 696 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 697 if (CI->isZero()) 698 continue; 699 // N = N + Offset 700 uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue(); 701 TotalOffs += DL.getTypeAllocSize(Ty) * IdxN; 702 if (TotalOffs >= MaxOffs) { 703 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 704 if (!N) // Unhandled operand. Halt "fast" selection and bail. 705 return false; 706 NIsKill = true; 707 TotalOffs = 0; 708 } 709 continue; 710 } 711 if (TotalOffs) { 712 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 713 if (!N) // Unhandled operand. Halt "fast" selection and bail. 714 return false; 715 NIsKill = true; 716 TotalOffs = 0; 717 } 718 719 // N = N + Idx * ElementSize; 720 uint64_t ElementSize = DL.getTypeAllocSize(Ty); 721 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx); 722 unsigned IdxN = Pair.first; 723 bool IdxNIsKill = Pair.second; 724 if (!IdxN) // Unhandled operand. Halt "fast" selection and bail. 725 return false; 726 727 if (ElementSize != 1) { 728 IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT); 729 if (!IdxN) // Unhandled operand. Halt "fast" selection and bail. 730 return false; 731 IdxNIsKill = true; 732 } 733 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill); 734 if (!N) // Unhandled operand. Halt "fast" selection and bail. 735 return false; 736 } 737 } 738 if (TotalOffs) { 739 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 740 if (!N) // Unhandled operand. Halt "fast" selection and bail. 741 return false; 742 } 743 744 // We successfully emitted code for the given LLVM Instruction. 745 updateValueMap(I, N); 746 return true; 747 } 748 749 bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops, 750 const CallInst *CI, unsigned StartIdx) { 751 for (unsigned i = StartIdx, e = CI->getNumArgOperands(); i != e; ++i) { 752 Value *Val = CI->getArgOperand(i); 753 // Check for constants and encode them with a StackMaps::ConstantOp prefix. 754 if (const auto *C = dyn_cast<ConstantInt>(Val)) { 755 Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp)); 756 Ops.push_back(MachineOperand::CreateImm(C->getSExtValue())); 757 } else if (isa<ConstantPointerNull>(Val)) { 758 Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp)); 759 Ops.push_back(MachineOperand::CreateImm(0)); 760 } else if (auto *AI = dyn_cast<AllocaInst>(Val)) { 761 // Values coming from a stack location also require a special encoding, 762 // but that is added later on by the target specific frame index 763 // elimination implementation. 764 auto SI = FuncInfo.StaticAllocaMap.find(AI); 765 if (SI != FuncInfo.StaticAllocaMap.end()) 766 Ops.push_back(MachineOperand::CreateFI(SI->second)); 767 else 768 return false; 769 } else { 770 unsigned Reg = getRegForValue(Val); 771 if (!Reg) 772 return false; 773 Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false)); 774 } 775 } 776 return true; 777 } 778 779 bool FastISel::selectStackmap(const CallInst *I) { 780 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 781 // [live variables...]) 782 assert(I->getCalledFunction()->getReturnType()->isVoidTy() && 783 "Stackmap cannot return a value."); 784 785 // The stackmap intrinsic only records the live variables (the arguments 786 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 787 // intrinsic, this won't be lowered to a function call. This means we don't 788 // have to worry about calling conventions and target-specific lowering code. 789 // Instead we perform the call lowering right here. 790 // 791 // CALLSEQ_START(0, 0...) 792 // STACKMAP(id, nbytes, ...) 793 // CALLSEQ_END(0, 0) 794 // 795 SmallVector<MachineOperand, 32> Ops; 796 797 // Add the <id> and <numBytes> constants. 798 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) && 799 "Expected a constant integer."); 800 const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)); 801 Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue())); 802 803 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) && 804 "Expected a constant integer."); 805 const auto *NumBytes = 806 cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)); 807 Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue())); 808 809 // Push live variables for the stack map (skipping the first two arguments 810 // <id> and <numBytes>). 811 if (!addStackMapLiveVars(Ops, I, 2)) 812 return false; 813 814 // We are not adding any register mask info here, because the stackmap doesn't 815 // clobber anything. 816 817 // Add scratch registers as implicit def and early clobber. 818 CallingConv::ID CC = I->getCallingConv(); 819 const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC); 820 for (unsigned i = 0; ScratchRegs[i]; ++i) 821 Ops.push_back(MachineOperand::CreateReg( 822 ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false, 823 /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true)); 824 825 // Issue CALLSEQ_START 826 unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); 827 auto Builder = 828 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown)); 829 const MCInstrDesc &MCID = Builder.getInstr()->getDesc(); 830 for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I) 831 Builder.addImm(0); 832 833 // Issue STACKMAP. 834 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 835 TII.get(TargetOpcode::STACKMAP)); 836 for (auto const &MO : Ops) 837 MIB.add(MO); 838 839 // Issue CALLSEQ_END 840 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode(); 841 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp)) 842 .addImm(0) 843 .addImm(0); 844 845 // Inform the Frame Information that we have a stackmap in this function. 846 FuncInfo.MF->getFrameInfo().setHasStackMap(); 847 848 return true; 849 } 850 851 /// Lower an argument list according to the target calling convention. 852 /// 853 /// This is a helper for lowering intrinsics that follow a target calling 854 /// convention or require stack pointer adjustment. Only a subset of the 855 /// intrinsic's operands need to participate in the calling convention. 856 bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx, 857 unsigned NumArgs, const Value *Callee, 858 bool ForceRetVoidTy, CallLoweringInfo &CLI) { 859 ArgListTy Args; 860 Args.reserve(NumArgs); 861 862 // Populate the argument list. 863 ImmutableCallSite CS(CI); 864 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; ArgI != ArgE; ++ArgI) { 865 Value *V = CI->getOperand(ArgI); 866 867 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 868 869 ArgListEntry Entry; 870 Entry.Val = V; 871 Entry.Ty = V->getType(); 872 Entry.setAttributes(&CS, ArgI); 873 Args.push_back(Entry); 874 } 875 876 Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext()) 877 : CI->getType(); 878 CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs); 879 880 return lowerCallTo(CLI); 881 } 882 883 FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee( 884 const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy, 885 StringRef Target, ArgListTy &&ArgsList, unsigned FixedArgs) { 886 SmallString<32> MangledName; 887 Mangler::getNameWithPrefix(MangledName, Target, DL); 888 MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName); 889 return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs); 890 } 891 892 bool FastISel::selectPatchpoint(const CallInst *I) { 893 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 894 // i32 <numBytes>, 895 // i8* <target>, 896 // i32 <numArgs>, 897 // [Args...], 898 // [live variables...]) 899 CallingConv::ID CC = I->getCallingConv(); 900 bool IsAnyRegCC = CC == CallingConv::AnyReg; 901 bool HasDef = !I->getType()->isVoidTy(); 902 Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts(); 903 904 // Get the real number of arguments participating in the call <numArgs> 905 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) && 906 "Expected a constant integer."); 907 const auto *NumArgsVal = 908 cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)); 909 unsigned NumArgs = NumArgsVal->getZExtValue(); 910 911 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 912 // This includes all meta-operands up to but not including CC. 913 unsigned NumMetaOpers = PatchPointOpers::CCPos; 914 assert(I->getNumArgOperands() >= NumMetaOpers + NumArgs && 915 "Not enough arguments provided to the patchpoint intrinsic"); 916 917 // For AnyRegCC the arguments are lowered later on manually. 918 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 919 CallLoweringInfo CLI; 920 CLI.setIsPatchPoint(); 921 if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI)) 922 return false; 923 924 assert(CLI.Call && "No call instruction specified."); 925 926 SmallVector<MachineOperand, 32> Ops; 927 928 // Add an explicit result reg if we use the anyreg calling convention. 929 if (IsAnyRegCC && HasDef) { 930 assert(CLI.NumResultRegs == 0 && "Unexpected result register."); 931 CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64)); 932 CLI.NumResultRegs = 1; 933 Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*IsDef=*/true)); 934 } 935 936 // Add the <id> and <numBytes> constants. 937 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) && 938 "Expected a constant integer."); 939 const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)); 940 Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue())); 941 942 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) && 943 "Expected a constant integer."); 944 const auto *NumBytes = 945 cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)); 946 Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue())); 947 948 // Add the call target. 949 if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) { 950 uint64_t CalleeConstAddr = 951 cast<ConstantInt>(C->getOperand(0))->getZExtValue(); 952 Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr)); 953 } else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) { 954 if (C->getOpcode() == Instruction::IntToPtr) { 955 uint64_t CalleeConstAddr = 956 cast<ConstantInt>(C->getOperand(0))->getZExtValue(); 957 Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr)); 958 } else 959 llvm_unreachable("Unsupported ConstantExpr."); 960 } else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) { 961 Ops.push_back(MachineOperand::CreateGA(GV, 0)); 962 } else if (isa<ConstantPointerNull>(Callee)) 963 Ops.push_back(MachineOperand::CreateImm(0)); 964 else 965 llvm_unreachable("Unsupported callee address."); 966 967 // Adjust <numArgs> to account for any arguments that have been passed on 968 // the stack instead. 969 unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size(); 970 Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs)); 971 972 // Add the calling convention 973 Ops.push_back(MachineOperand::CreateImm((unsigned)CC)); 974 975 // Add the arguments we omitted previously. The register allocator should 976 // place these in any free register. 977 if (IsAnyRegCC) { 978 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) { 979 unsigned Reg = getRegForValue(I->getArgOperand(i)); 980 if (!Reg) 981 return false; 982 Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false)); 983 } 984 } 985 986 // Push the arguments from the call instruction. 987 for (auto Reg : CLI.OutRegs) 988 Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false)); 989 990 // Push live variables for the stack map. 991 if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs)) 992 return false; 993 994 // Push the register mask info. 995 Ops.push_back(MachineOperand::CreateRegMask( 996 TRI.getCallPreservedMask(*FuncInfo.MF, CC))); 997 998 // Add scratch registers as implicit def and early clobber. 999 const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC); 1000 for (unsigned i = 0; ScratchRegs[i]; ++i) 1001 Ops.push_back(MachineOperand::CreateReg( 1002 ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false, 1003 /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true)); 1004 1005 // Add implicit defs (return values). 1006 for (auto Reg : CLI.InRegs) 1007 Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/true, 1008 /*IsImpl=*/true)); 1009 1010 // Insert the patchpoint instruction before the call generated by the target. 1011 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, DbgLoc, 1012 TII.get(TargetOpcode::PATCHPOINT)); 1013 1014 for (auto &MO : Ops) 1015 MIB.add(MO); 1016 1017 MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI); 1018 1019 // Delete the original call instruction. 1020 CLI.Call->eraseFromParent(); 1021 1022 // Inform the Frame Information that we have a patchpoint in this function. 1023 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 1024 1025 if (CLI.NumResultRegs) 1026 updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs); 1027 return true; 1028 } 1029 1030 bool FastISel::selectXRayCustomEvent(const CallInst *I) { 1031 const auto &Triple = TM.getTargetTriple(); 1032 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 1033 return true; // don't do anything to this instruction. 1034 SmallVector<MachineOperand, 8> Ops; 1035 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)), 1036 /*IsDef=*/false)); 1037 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)), 1038 /*IsDef=*/false)); 1039 MachineInstrBuilder MIB = 1040 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1041 TII.get(TargetOpcode::PATCHABLE_EVENT_CALL)); 1042 for (auto &MO : Ops) 1043 MIB.add(MO); 1044 1045 // Insert the Patchable Event Call instruction, that gets lowered properly. 1046 return true; 1047 } 1048 1049 bool FastISel::selectXRayTypedEvent(const CallInst *I) { 1050 const auto &Triple = TM.getTargetTriple(); 1051 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 1052 return true; // don't do anything to this instruction. 1053 SmallVector<MachineOperand, 8> Ops; 1054 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)), 1055 /*IsDef=*/false)); 1056 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)), 1057 /*IsDef=*/false)); 1058 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(2)), 1059 /*IsDef=*/false)); 1060 MachineInstrBuilder MIB = 1061 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1062 TII.get(TargetOpcode::PATCHABLE_TYPED_EVENT_CALL)); 1063 for (auto &MO : Ops) 1064 MIB.add(MO); 1065 1066 // Insert the Patchable Typed Event Call instruction, that gets lowered properly. 1067 return true; 1068 } 1069 1070 /// Returns an AttributeList representing the attributes applied to the return 1071 /// value of the given call. 1072 static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI) { 1073 SmallVector<Attribute::AttrKind, 2> Attrs; 1074 if (CLI.RetSExt) 1075 Attrs.push_back(Attribute::SExt); 1076 if (CLI.RetZExt) 1077 Attrs.push_back(Attribute::ZExt); 1078 if (CLI.IsInReg) 1079 Attrs.push_back(Attribute::InReg); 1080 1081 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 1082 Attrs); 1083 } 1084 1085 bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName, 1086 unsigned NumArgs) { 1087 MCContext &Ctx = MF->getContext(); 1088 SmallString<32> MangledName; 1089 Mangler::getNameWithPrefix(MangledName, SymName, DL); 1090 MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName); 1091 return lowerCallTo(CI, Sym, NumArgs); 1092 } 1093 1094 bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol, 1095 unsigned NumArgs) { 1096 ImmutableCallSite CS(CI); 1097 1098 FunctionType *FTy = CS.getFunctionType(); 1099 Type *RetTy = CS.getType(); 1100 1101 ArgListTy Args; 1102 Args.reserve(NumArgs); 1103 1104 // Populate the argument list. 1105 // Attributes for args start at offset 1, after the return attribute. 1106 for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) { 1107 Value *V = CI->getOperand(ArgI); 1108 1109 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 1110 1111 ArgListEntry Entry; 1112 Entry.Val = V; 1113 Entry.Ty = V->getType(); 1114 Entry.setAttributes(&CS, ArgI); 1115 Args.push_back(Entry); 1116 } 1117 TLI.markLibCallAttributes(MF, CS.getCallingConv(), Args); 1118 1119 CallLoweringInfo CLI; 1120 CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), CS, NumArgs); 1121 1122 return lowerCallTo(CLI); 1123 } 1124 1125 bool FastISel::lowerCallTo(CallLoweringInfo &CLI) { 1126 // Handle the incoming return values from the call. 1127 CLI.clearIns(); 1128 SmallVector<EVT, 4> RetTys; 1129 ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys); 1130 1131 SmallVector<ISD::OutputArg, 4> Outs; 1132 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL); 1133 1134 bool CanLowerReturn = TLI.CanLowerReturn( 1135 CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 1136 1137 // FIXME: sret demotion isn't supported yet - bail out. 1138 if (!CanLowerReturn) 1139 return false; 1140 1141 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 1142 EVT VT = RetTys[I]; 1143 MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT); 1144 unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT); 1145 for (unsigned i = 0; i != NumRegs; ++i) { 1146 ISD::InputArg MyFlags; 1147 MyFlags.VT = RegisterVT; 1148 MyFlags.ArgVT = VT; 1149 MyFlags.Used = CLI.IsReturnValueUsed; 1150 if (CLI.RetSExt) 1151 MyFlags.Flags.setSExt(); 1152 if (CLI.RetZExt) 1153 MyFlags.Flags.setZExt(); 1154 if (CLI.IsInReg) 1155 MyFlags.Flags.setInReg(); 1156 CLI.Ins.push_back(MyFlags); 1157 } 1158 } 1159 1160 // Handle all of the outgoing arguments. 1161 CLI.clearOuts(); 1162 for (auto &Arg : CLI.getArgs()) { 1163 Type *FinalType = Arg.Ty; 1164 if (Arg.IsByVal) 1165 FinalType = cast<PointerType>(Arg.Ty)->getElementType(); 1166 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1167 FinalType, CLI.CallConv, CLI.IsVarArg); 1168 1169 ISD::ArgFlagsTy Flags; 1170 if (Arg.IsZExt) 1171 Flags.setZExt(); 1172 if (Arg.IsSExt) 1173 Flags.setSExt(); 1174 if (Arg.IsInReg) 1175 Flags.setInReg(); 1176 if (Arg.IsSRet) 1177 Flags.setSRet(); 1178 if (Arg.IsSwiftSelf) 1179 Flags.setSwiftSelf(); 1180 if (Arg.IsSwiftError) 1181 Flags.setSwiftError(); 1182 if (Arg.IsByVal) 1183 Flags.setByVal(); 1184 if (Arg.IsInAlloca) { 1185 Flags.setInAlloca(); 1186 // Set the byval flag for CCAssignFn callbacks that don't know about 1187 // inalloca. This way we can know how many bytes we should've allocated 1188 // and how many bytes a callee cleanup function will pop. If we port 1189 // inalloca to more targets, we'll have to add custom inalloca handling in 1190 // the various CC lowering callbacks. 1191 Flags.setByVal(); 1192 } 1193 if (Arg.IsByVal || Arg.IsInAlloca) { 1194 PointerType *Ty = cast<PointerType>(Arg.Ty); 1195 Type *ElementTy = Ty->getElementType(); 1196 unsigned FrameSize = DL.getTypeAllocSize(ElementTy); 1197 // For ByVal, alignment should come from FE. BE will guess if this info is 1198 // not there, but there are cases it cannot get right. 1199 unsigned FrameAlign = Arg.Alignment; 1200 if (!FrameAlign) 1201 FrameAlign = TLI.getByValTypeAlignment(ElementTy, DL); 1202 Flags.setByValSize(FrameSize); 1203 Flags.setByValAlign(FrameAlign); 1204 } 1205 if (Arg.IsNest) 1206 Flags.setNest(); 1207 if (NeedsRegBlock) 1208 Flags.setInConsecutiveRegs(); 1209 unsigned OriginalAlignment = DL.getABITypeAlignment(Arg.Ty); 1210 Flags.setOrigAlign(OriginalAlignment); 1211 1212 CLI.OutVals.push_back(Arg.Val); 1213 CLI.OutFlags.push_back(Flags); 1214 } 1215 1216 if (!fastLowerCall(CLI)) 1217 return false; 1218 1219 // Set all unused physreg defs as dead. 1220 assert(CLI.Call && "No call instruction specified."); 1221 CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI); 1222 1223 if (CLI.NumResultRegs && CLI.CS) 1224 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs); 1225 1226 return true; 1227 } 1228 1229 bool FastISel::lowerCall(const CallInst *CI) { 1230 ImmutableCallSite CS(CI); 1231 1232 FunctionType *FuncTy = CS.getFunctionType(); 1233 Type *RetTy = CS.getType(); 1234 1235 ArgListTy Args; 1236 ArgListEntry Entry; 1237 Args.reserve(CS.arg_size()); 1238 1239 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 1240 i != e; ++i) { 1241 Value *V = *i; 1242 1243 // Skip empty types 1244 if (V->getType()->isEmptyTy()) 1245 continue; 1246 1247 Entry.Val = V; 1248 Entry.Ty = V->getType(); 1249 1250 // Skip the first return-type Attribute to get to params. 1251 Entry.setAttributes(&CS, i - CS.arg_begin()); 1252 Args.push_back(Entry); 1253 } 1254 1255 // Check if target-independent constraints permit a tail call here. 1256 // Target-dependent constraints are checked within fastLowerCall. 1257 bool IsTailCall = CI->isTailCall(); 1258 if (IsTailCall && !isInTailCallPosition(CS, TM)) 1259 IsTailCall = false; 1260 1261 CallLoweringInfo CLI; 1262 CLI.setCallee(RetTy, FuncTy, CI->getCalledValue(), std::move(Args), CS) 1263 .setTailCall(IsTailCall); 1264 1265 return lowerCallTo(CLI); 1266 } 1267 1268 bool FastISel::selectCall(const User *I) { 1269 const CallInst *Call = cast<CallInst>(I); 1270 1271 // Handle simple inline asms. 1272 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) { 1273 // If the inline asm has side effects, then make sure that no local value 1274 // lives across by flushing the local value map. 1275 if (IA->hasSideEffects()) 1276 flushLocalValueMap(); 1277 1278 // Don't attempt to handle constraints. 1279 if (!IA->getConstraintString().empty()) 1280 return false; 1281 1282 unsigned ExtraInfo = 0; 1283 if (IA->hasSideEffects()) 1284 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 1285 if (IA->isAlignStack()) 1286 ExtraInfo |= InlineAsm::Extra_IsAlignStack; 1287 1288 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1289 TII.get(TargetOpcode::INLINEASM)) 1290 .addExternalSymbol(IA->getAsmString().c_str()) 1291 .addImm(ExtraInfo); 1292 return true; 1293 } 1294 1295 MachineModuleInfo &MMI = FuncInfo.MF->getMMI(); 1296 computeUsesVAFloatArgument(*Call, MMI); 1297 1298 // Handle intrinsic function calls. 1299 if (const auto *II = dyn_cast<IntrinsicInst>(Call)) 1300 return selectIntrinsicCall(II); 1301 1302 // Usually, it does not make sense to initialize a value, 1303 // make an unrelated function call and use the value, because 1304 // it tends to be spilled on the stack. So, we move the pointer 1305 // to the last local value to the beginning of the block, so that 1306 // all the values which have already been materialized, 1307 // appear after the call. It also makes sense to skip intrinsics 1308 // since they tend to be inlined. 1309 flushLocalValueMap(); 1310 1311 return lowerCall(Call); 1312 } 1313 1314 bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) { 1315 switch (II->getIntrinsicID()) { 1316 default: 1317 break; 1318 // At -O0 we don't care about the lifetime intrinsics. 1319 case Intrinsic::lifetime_start: 1320 case Intrinsic::lifetime_end: 1321 // The donothing intrinsic does, well, nothing. 1322 case Intrinsic::donothing: 1323 // Neither does the sideeffect intrinsic. 1324 case Intrinsic::sideeffect: 1325 // Neither does the assume intrinsic; it's also OK not to codegen its operand. 1326 case Intrinsic::assume: 1327 return true; 1328 case Intrinsic::dbg_declare: { 1329 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II); 1330 assert(DI->getVariable() && "Missing variable"); 1331 if (!FuncInfo.MF->getMMI().hasDebugInfo()) { 1332 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1333 return true; 1334 } 1335 1336 const Value *Address = DI->getAddress(); 1337 if (!Address || isa<UndefValue>(Address)) { 1338 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1339 return true; 1340 } 1341 1342 // Byval arguments with frame indices were already handled after argument 1343 // lowering and before isel. 1344 const auto *Arg = 1345 dyn_cast<Argument>(Address->stripInBoundsConstantOffsets()); 1346 if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX) 1347 return true; 1348 1349 Optional<MachineOperand> Op; 1350 if (unsigned Reg = lookUpRegForValue(Address)) 1351 Op = MachineOperand::CreateReg(Reg, false); 1352 1353 // If we have a VLA that has a "use" in a metadata node that's then used 1354 // here but it has no other uses, then we have a problem. E.g., 1355 // 1356 // int foo (const int *x) { 1357 // char a[*x]; 1358 // return 0; 1359 // } 1360 // 1361 // If we assign 'a' a vreg and fast isel later on has to use the selection 1362 // DAG isel, it will want to copy the value to the vreg. However, there are 1363 // no uses, which goes counter to what selection DAG isel expects. 1364 if (!Op && !Address->use_empty() && isa<Instruction>(Address) && 1365 (!isa<AllocaInst>(Address) || 1366 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address)))) 1367 Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address), 1368 false); 1369 1370 if (Op) { 1371 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) && 1372 "Expected inlined-at fields to agree"); 1373 if (Op->isReg()) { 1374 Op->setIsDebug(true); 1375 // A dbg.declare describes the address of a source variable, so lower it 1376 // into an indirect DBG_VALUE. 1377 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1378 TII.get(TargetOpcode::DBG_VALUE), /*IsIndirect*/ true, 1379 Op->getReg(), DI->getVariable(), DI->getExpression()); 1380 } else 1381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1382 TII.get(TargetOpcode::DBG_VALUE)) 1383 .add(*Op) 1384 .addImm(0) 1385 .addMetadata(DI->getVariable()) 1386 .addMetadata(DI->getExpression()); 1387 } else { 1388 // We can't yet handle anything else here because it would require 1389 // generating code, thus altering codegen because of debug info. 1390 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1391 } 1392 return true; 1393 } 1394 case Intrinsic::dbg_value: { 1395 // This form of DBG_VALUE is target-independent. 1396 const DbgValueInst *DI = cast<DbgValueInst>(II); 1397 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 1398 const Value *V = DI->getValue(); 1399 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) && 1400 "Expected inlined-at fields to agree"); 1401 if (!V) { 1402 // Currently the optimizer can produce this; insert an undef to 1403 // help debugging. Probably the optimizer should not do this. 1404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, false, 0U, 1405 DI->getVariable(), DI->getExpression()); 1406 } else if (const auto *CI = dyn_cast<ConstantInt>(V)) { 1407 if (CI->getBitWidth() > 64) 1408 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1409 .addCImm(CI) 1410 .addImm(0U) 1411 .addMetadata(DI->getVariable()) 1412 .addMetadata(DI->getExpression()); 1413 else 1414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1415 .addImm(CI->getZExtValue()) 1416 .addImm(0U) 1417 .addMetadata(DI->getVariable()) 1418 .addMetadata(DI->getExpression()); 1419 } else if (const auto *CF = dyn_cast<ConstantFP>(V)) { 1420 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1421 .addFPImm(CF) 1422 .addImm(0U) 1423 .addMetadata(DI->getVariable()) 1424 .addMetadata(DI->getExpression()); 1425 } else if (unsigned Reg = lookUpRegForValue(V)) { 1426 // FIXME: This does not handle register-indirect values at offset 0. 1427 bool IsIndirect = false; 1428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg, 1429 DI->getVariable(), DI->getExpression()); 1430 } else { 1431 // We can't yet handle anything else here because it would require 1432 // generating code, thus altering codegen because of debug info. 1433 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1434 } 1435 return true; 1436 } 1437 case Intrinsic::objectsize: { 1438 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1)); 1439 unsigned long long Res = CI->isZero() ? -1ULL : 0; 1440 Constant *ResCI = ConstantInt::get(II->getType(), Res); 1441 unsigned ResultReg = getRegForValue(ResCI); 1442 if (!ResultReg) 1443 return false; 1444 updateValueMap(II, ResultReg); 1445 return true; 1446 } 1447 case Intrinsic::launder_invariant_group: 1448 case Intrinsic::expect: { 1449 unsigned ResultReg = getRegForValue(II->getArgOperand(0)); 1450 if (!ResultReg) 1451 return false; 1452 updateValueMap(II, ResultReg); 1453 return true; 1454 } 1455 case Intrinsic::experimental_stackmap: 1456 return selectStackmap(II); 1457 case Intrinsic::experimental_patchpoint_void: 1458 case Intrinsic::experimental_patchpoint_i64: 1459 return selectPatchpoint(II); 1460 1461 case Intrinsic::xray_customevent: 1462 return selectXRayCustomEvent(II); 1463 case Intrinsic::xray_typedevent: 1464 return selectXRayTypedEvent(II); 1465 } 1466 1467 return fastLowerIntrinsicCall(II); 1468 } 1469 1470 bool FastISel::selectCast(const User *I, unsigned Opcode) { 1471 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1472 EVT DstVT = TLI.getValueType(DL, I->getType()); 1473 1474 if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other || 1475 !DstVT.isSimple()) 1476 // Unhandled type. Halt "fast" selection and bail. 1477 return false; 1478 1479 // Check if the destination type is legal. 1480 if (!TLI.isTypeLegal(DstVT)) 1481 return false; 1482 1483 // Check if the source operand is legal. 1484 if (!TLI.isTypeLegal(SrcVT)) 1485 return false; 1486 1487 unsigned InputReg = getRegForValue(I->getOperand(0)); 1488 if (!InputReg) 1489 // Unhandled operand. Halt "fast" selection and bail. 1490 return false; 1491 1492 bool InputRegIsKill = hasTrivialKill(I->getOperand(0)); 1493 1494 unsigned ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), 1495 Opcode, InputReg, InputRegIsKill); 1496 if (!ResultReg) 1497 return false; 1498 1499 updateValueMap(I, ResultReg); 1500 return true; 1501 } 1502 1503 bool FastISel::selectBitCast(const User *I) { 1504 // If the bitcast doesn't change the type, just use the operand value. 1505 if (I->getType() == I->getOperand(0)->getType()) { 1506 unsigned Reg = getRegForValue(I->getOperand(0)); 1507 if (!Reg) 1508 return false; 1509 updateValueMap(I, Reg); 1510 return true; 1511 } 1512 1513 // Bitcasts of other values become reg-reg copies or BITCAST operators. 1514 EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1515 EVT DstEVT = TLI.getValueType(DL, I->getType()); 1516 if (SrcEVT == MVT::Other || DstEVT == MVT::Other || 1517 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT)) 1518 // Unhandled type. Halt "fast" selection and bail. 1519 return false; 1520 1521 MVT SrcVT = SrcEVT.getSimpleVT(); 1522 MVT DstVT = DstEVT.getSimpleVT(); 1523 unsigned Op0 = getRegForValue(I->getOperand(0)); 1524 if (!Op0) // Unhandled operand. Halt "fast" selection and bail. 1525 return false; 1526 bool Op0IsKill = hasTrivialKill(I->getOperand(0)); 1527 1528 // First, try to perform the bitcast by inserting a reg-reg copy. 1529 unsigned ResultReg = 0; 1530 if (SrcVT == DstVT) { 1531 const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT); 1532 const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT); 1533 // Don't attempt a cross-class copy. It will likely fail. 1534 if (SrcClass == DstClass) { 1535 ResultReg = createResultReg(DstClass); 1536 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1537 TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0); 1538 } 1539 } 1540 1541 // If the reg-reg copy failed, select a BITCAST opcode. 1542 if (!ResultReg) 1543 ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill); 1544 1545 if (!ResultReg) 1546 return false; 1547 1548 updateValueMap(I, ResultReg); 1549 return true; 1550 } 1551 1552 // Remove local value instructions starting from the instruction after 1553 // SavedLastLocalValue to the current function insert point. 1554 void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue) 1555 { 1556 MachineInstr *CurLastLocalValue = getLastLocalValue(); 1557 if (CurLastLocalValue != SavedLastLocalValue) { 1558 // Find the first local value instruction to be deleted. 1559 // This is the instruction after SavedLastLocalValue if it is non-NULL. 1560 // Otherwise it's the first instruction in the block. 1561 MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue); 1562 if (SavedLastLocalValue) 1563 ++FirstDeadInst; 1564 else 1565 FirstDeadInst = FuncInfo.MBB->getFirstNonPHI(); 1566 setLastLocalValue(SavedLastLocalValue); 1567 removeDeadCode(FirstDeadInst, FuncInfo.InsertPt); 1568 } 1569 } 1570 1571 bool FastISel::selectInstruction(const Instruction *I) { 1572 MachineInstr *SavedLastLocalValue = getLastLocalValue(); 1573 // Just before the terminator instruction, insert instructions to 1574 // feed PHI nodes in successor blocks. 1575 if (isa<TerminatorInst>(I)) { 1576 if (!handlePHINodesInSuccessorBlocks(I->getParent())) { 1577 // PHI node handling may have generated local value instructions, 1578 // even though it failed to handle all PHI nodes. 1579 // We remove these instructions because SelectionDAGISel will generate 1580 // them again. 1581 removeDeadLocalValueCode(SavedLastLocalValue); 1582 return false; 1583 } 1584 } 1585 1586 // FastISel does not handle any operand bundles except OB_funclet. 1587 if (ImmutableCallSite CS = ImmutableCallSite(I)) 1588 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) 1589 if (CS.getOperandBundleAt(i).getTagID() != LLVMContext::OB_funclet) 1590 return false; 1591 1592 DbgLoc = I->getDebugLoc(); 1593 1594 SavedInsertPt = FuncInfo.InsertPt; 1595 1596 if (const auto *Call = dyn_cast<CallInst>(I)) { 1597 const Function *F = Call->getCalledFunction(); 1598 LibFunc Func; 1599 1600 // As a special case, don't handle calls to builtin library functions that 1601 // may be translated directly to target instructions. 1602 if (F && !F->hasLocalLinkage() && F->hasName() && 1603 LibInfo->getLibFunc(F->getName(), Func) && 1604 LibInfo->hasOptimizedCodeGen(Func)) 1605 return false; 1606 1607 // Don't handle Intrinsic::trap if a trap function is specified. 1608 if (F && F->getIntrinsicID() == Intrinsic::trap && 1609 Call->hasFnAttr("trap-func-name")) 1610 return false; 1611 } 1612 1613 // First, try doing target-independent selection. 1614 if (!SkipTargetIndependentISel) { 1615 if (selectOperator(I, I->getOpcode())) { 1616 ++NumFastIselSuccessIndependent; 1617 DbgLoc = DebugLoc(); 1618 return true; 1619 } 1620 // Remove dead code. 1621 recomputeInsertPt(); 1622 if (SavedInsertPt != FuncInfo.InsertPt) 1623 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt); 1624 SavedInsertPt = FuncInfo.InsertPt; 1625 } 1626 // Next, try calling the target to attempt to handle the instruction. 1627 if (fastSelectInstruction(I)) { 1628 ++NumFastIselSuccessTarget; 1629 DbgLoc = DebugLoc(); 1630 return true; 1631 } 1632 // Remove dead code. 1633 recomputeInsertPt(); 1634 if (SavedInsertPt != FuncInfo.InsertPt) 1635 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt); 1636 1637 DbgLoc = DebugLoc(); 1638 // Undo phi node updates, because they will be added again by SelectionDAG. 1639 if (isa<TerminatorInst>(I)) { 1640 // PHI node handling may have generated local value instructions. 1641 // We remove them because SelectionDAGISel will generate them again. 1642 removeDeadLocalValueCode(SavedLastLocalValue); 1643 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 1644 } 1645 return false; 1646 } 1647 1648 /// Emit an unconditional branch to the given block, unless it is the immediate 1649 /// (fall-through) successor, and update the CFG. 1650 void FastISel::fastEmitBranch(MachineBasicBlock *MSucc, 1651 const DebugLoc &DbgLoc) { 1652 if (FuncInfo.MBB->getBasicBlock()->size() > 1 && 1653 FuncInfo.MBB->isLayoutSuccessor(MSucc)) { 1654 // For more accurate line information if this is the only instruction 1655 // in the block then emit it, otherwise we have the unconditional 1656 // fall-through case, which needs no instructions. 1657 } else { 1658 // The unconditional branch case. 1659 TII.insertBranch(*FuncInfo.MBB, MSucc, nullptr, 1660 SmallVector<MachineOperand, 0>(), DbgLoc); 1661 } 1662 if (FuncInfo.BPI) { 1663 auto BranchProbability = FuncInfo.BPI->getEdgeProbability( 1664 FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock()); 1665 FuncInfo.MBB->addSuccessor(MSucc, BranchProbability); 1666 } else 1667 FuncInfo.MBB->addSuccessorWithoutProb(MSucc); 1668 } 1669 1670 void FastISel::finishCondBranch(const BasicBlock *BranchBB, 1671 MachineBasicBlock *TrueMBB, 1672 MachineBasicBlock *FalseMBB) { 1673 // Add TrueMBB as successor unless it is equal to the FalseMBB: This can 1674 // happen in degenerate IR and MachineIR forbids to have a block twice in the 1675 // successor/predecessor lists. 1676 if (TrueMBB != FalseMBB) { 1677 if (FuncInfo.BPI) { 1678 auto BranchProbability = 1679 FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock()); 1680 FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability); 1681 } else 1682 FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB); 1683 } 1684 1685 fastEmitBranch(FalseMBB, DbgLoc); 1686 } 1687 1688 /// Emit an FNeg operation. 1689 bool FastISel::selectFNeg(const User *I) { 1690 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I)); 1691 if (!OpReg) 1692 return false; 1693 bool OpRegIsKill = hasTrivialKill(I); 1694 1695 // If the target has ISD::FNEG, use it. 1696 EVT VT = TLI.getValueType(DL, I->getType()); 1697 unsigned ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG, 1698 OpReg, OpRegIsKill); 1699 if (ResultReg) { 1700 updateValueMap(I, ResultReg); 1701 return true; 1702 } 1703 1704 // Bitcast the value to integer, twiddle the sign bit with xor, 1705 // and then bitcast it back to floating-point. 1706 if (VT.getSizeInBits() > 64) 1707 return false; 1708 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits()); 1709 if (!TLI.isTypeLegal(IntVT)) 1710 return false; 1711 1712 unsigned IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(), 1713 ISD::BITCAST, OpReg, OpRegIsKill); 1714 if (!IntReg) 1715 return false; 1716 1717 unsigned IntResultReg = fastEmit_ri_( 1718 IntVT.getSimpleVT(), ISD::XOR, IntReg, /*IsKill=*/true, 1719 UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT()); 1720 if (!IntResultReg) 1721 return false; 1722 1723 ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST, 1724 IntResultReg, /*IsKill=*/true); 1725 if (!ResultReg) 1726 return false; 1727 1728 updateValueMap(I, ResultReg); 1729 return true; 1730 } 1731 1732 bool FastISel::selectExtractValue(const User *U) { 1733 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U); 1734 if (!EVI) 1735 return false; 1736 1737 // Make sure we only try to handle extracts with a legal result. But also 1738 // allow i1 because it's easy. 1739 EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true); 1740 if (!RealVT.isSimple()) 1741 return false; 1742 MVT VT = RealVT.getSimpleVT(); 1743 if (!TLI.isTypeLegal(VT) && VT != MVT::i1) 1744 return false; 1745 1746 const Value *Op0 = EVI->getOperand(0); 1747 Type *AggTy = Op0->getType(); 1748 1749 // Get the base result register. 1750 unsigned ResultReg; 1751 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0); 1752 if (I != FuncInfo.ValueMap.end()) 1753 ResultReg = I->second; 1754 else if (isa<Instruction>(Op0)) 1755 ResultReg = FuncInfo.InitializeRegForValue(Op0); 1756 else 1757 return false; // fast-isel can't handle aggregate constants at the moment 1758 1759 // Get the actual result register, which is an offset from the base register. 1760 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices()); 1761 1762 SmallVector<EVT, 4> AggValueVTs; 1763 ComputeValueVTs(TLI, DL, AggTy, AggValueVTs); 1764 1765 for (unsigned i = 0; i < VTIndex; i++) 1766 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]); 1767 1768 updateValueMap(EVI, ResultReg); 1769 return true; 1770 } 1771 1772 bool FastISel::selectOperator(const User *I, unsigned Opcode) { 1773 switch (Opcode) { 1774 case Instruction::Add: 1775 return selectBinaryOp(I, ISD::ADD); 1776 case Instruction::FAdd: 1777 return selectBinaryOp(I, ISD::FADD); 1778 case Instruction::Sub: 1779 return selectBinaryOp(I, ISD::SUB); 1780 case Instruction::FSub: 1781 // FNeg is currently represented in LLVM IR as a special case of FSub. 1782 if (BinaryOperator::isFNeg(I)) 1783 return selectFNeg(I); 1784 return selectBinaryOp(I, ISD::FSUB); 1785 case Instruction::Mul: 1786 return selectBinaryOp(I, ISD::MUL); 1787 case Instruction::FMul: 1788 return selectBinaryOp(I, ISD::FMUL); 1789 case Instruction::SDiv: 1790 return selectBinaryOp(I, ISD::SDIV); 1791 case Instruction::UDiv: 1792 return selectBinaryOp(I, ISD::UDIV); 1793 case Instruction::FDiv: 1794 return selectBinaryOp(I, ISD::FDIV); 1795 case Instruction::SRem: 1796 return selectBinaryOp(I, ISD::SREM); 1797 case Instruction::URem: 1798 return selectBinaryOp(I, ISD::UREM); 1799 case Instruction::FRem: 1800 return selectBinaryOp(I, ISD::FREM); 1801 case Instruction::Shl: 1802 return selectBinaryOp(I, ISD::SHL); 1803 case Instruction::LShr: 1804 return selectBinaryOp(I, ISD::SRL); 1805 case Instruction::AShr: 1806 return selectBinaryOp(I, ISD::SRA); 1807 case Instruction::And: 1808 return selectBinaryOp(I, ISD::AND); 1809 case Instruction::Or: 1810 return selectBinaryOp(I, ISD::OR); 1811 case Instruction::Xor: 1812 return selectBinaryOp(I, ISD::XOR); 1813 1814 case Instruction::GetElementPtr: 1815 return selectGetElementPtr(I); 1816 1817 case Instruction::Br: { 1818 const BranchInst *BI = cast<BranchInst>(I); 1819 1820 if (BI->isUnconditional()) { 1821 const BasicBlock *LLVMSucc = BI->getSuccessor(0); 1822 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc]; 1823 fastEmitBranch(MSucc, BI->getDebugLoc()); 1824 return true; 1825 } 1826 1827 // Conditional branches are not handed yet. 1828 // Halt "fast" selection and bail. 1829 return false; 1830 } 1831 1832 case Instruction::Unreachable: 1833 if (TM.Options.TrapUnreachable) 1834 return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0; 1835 else 1836 return true; 1837 1838 case Instruction::Alloca: 1839 // FunctionLowering has the static-sized case covered. 1840 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I))) 1841 return true; 1842 1843 // Dynamic-sized alloca is not handled yet. 1844 return false; 1845 1846 case Instruction::Call: 1847 return selectCall(I); 1848 1849 case Instruction::BitCast: 1850 return selectBitCast(I); 1851 1852 case Instruction::FPToSI: 1853 return selectCast(I, ISD::FP_TO_SINT); 1854 case Instruction::ZExt: 1855 return selectCast(I, ISD::ZERO_EXTEND); 1856 case Instruction::SExt: 1857 return selectCast(I, ISD::SIGN_EXTEND); 1858 case Instruction::Trunc: 1859 return selectCast(I, ISD::TRUNCATE); 1860 case Instruction::SIToFP: 1861 return selectCast(I, ISD::SINT_TO_FP); 1862 1863 case Instruction::IntToPtr: // Deliberate fall-through. 1864 case Instruction::PtrToInt: { 1865 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1866 EVT DstVT = TLI.getValueType(DL, I->getType()); 1867 if (DstVT.bitsGT(SrcVT)) 1868 return selectCast(I, ISD::ZERO_EXTEND); 1869 if (DstVT.bitsLT(SrcVT)) 1870 return selectCast(I, ISD::TRUNCATE); 1871 unsigned Reg = getRegForValue(I->getOperand(0)); 1872 if (!Reg) 1873 return false; 1874 updateValueMap(I, Reg); 1875 return true; 1876 } 1877 1878 case Instruction::ExtractValue: 1879 return selectExtractValue(I); 1880 1881 case Instruction::PHI: 1882 llvm_unreachable("FastISel shouldn't visit PHI nodes!"); 1883 1884 default: 1885 // Unhandled instruction. Halt "fast" selection and bail. 1886 return false; 1887 } 1888 } 1889 1890 FastISel::FastISel(FunctionLoweringInfo &FuncInfo, 1891 const TargetLibraryInfo *LibInfo, 1892 bool SkipTargetIndependentISel) 1893 : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()), 1894 MFI(FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()), 1895 TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()), 1896 TII(*MF->getSubtarget().getInstrInfo()), 1897 TLI(*MF->getSubtarget().getTargetLowering()), 1898 TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo), 1899 SkipTargetIndependentISel(SkipTargetIndependentISel) {} 1900 1901 FastISel::~FastISel() = default; 1902 1903 bool FastISel::fastLowerArguments() { return false; } 1904 1905 bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; } 1906 1907 bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) { 1908 return false; 1909 } 1910 1911 unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; } 1912 1913 unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/, 1914 bool /*Op0IsKill*/) { 1915 return 0; 1916 } 1917 1918 unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/, 1919 bool /*Op0IsKill*/, unsigned /*Op1*/, 1920 bool /*Op1IsKill*/) { 1921 return 0; 1922 } 1923 1924 unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) { 1925 return 0; 1926 } 1927 1928 unsigned FastISel::fastEmit_f(MVT, MVT, unsigned, 1929 const ConstantFP * /*FPImm*/) { 1930 return 0; 1931 } 1932 1933 unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/, 1934 bool /*Op0IsKill*/, uint64_t /*Imm*/) { 1935 return 0; 1936 } 1937 1938 /// This method is a wrapper of fastEmit_ri. It first tries to emit an 1939 /// instruction with an immediate operand using fastEmit_ri. 1940 /// If that fails, it materializes the immediate into a register and try 1941 /// fastEmit_rr instead. 1942 unsigned FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0, 1943 bool Op0IsKill, uint64_t Imm, MVT ImmType) { 1944 // If this is a multiply by a power of two, emit this as a shift left. 1945 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) { 1946 Opcode = ISD::SHL; 1947 Imm = Log2_64(Imm); 1948 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) { 1949 // div x, 8 -> srl x, 3 1950 Opcode = ISD::SRL; 1951 Imm = Log2_64(Imm); 1952 } 1953 1954 // Horrible hack (to be removed), check to make sure shift amounts are 1955 // in-range. 1956 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) && 1957 Imm >= VT.getSizeInBits()) 1958 return 0; 1959 1960 // First check if immediate type is legal. If not, we can't use the ri form. 1961 unsigned ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm); 1962 if (ResultReg) 1963 return ResultReg; 1964 unsigned MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm); 1965 bool IsImmKill = true; 1966 if (!MaterialReg) { 1967 // This is a bit ugly/slow, but failing here means falling out of 1968 // fast-isel, which would be very slow. 1969 IntegerType *ITy = 1970 IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits()); 1971 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm)); 1972 if (!MaterialReg) 1973 return 0; 1974 // FIXME: If the materialized register here has no uses yet then this 1975 // will be the first use and we should be able to mark it as killed. 1976 // However, the local value area for materialising constant expressions 1977 // grows down, not up, which means that any constant expressions we generate 1978 // later which also use 'Imm' could be after this instruction and therefore 1979 // after this kill. 1980 IsImmKill = false; 1981 } 1982 return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg, IsImmKill); 1983 } 1984 1985 unsigned FastISel::createResultReg(const TargetRegisterClass *RC) { 1986 return MRI.createVirtualRegister(RC); 1987 } 1988 1989 unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II, unsigned Op, 1990 unsigned OpNum) { 1991 if (TargetRegisterInfo::isVirtualRegister(Op)) { 1992 const TargetRegisterClass *RegClass = 1993 TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF); 1994 if (!MRI.constrainRegClass(Op, RegClass)) { 1995 // If it's not legal to COPY between the register classes, something 1996 // has gone very wrong before we got here. 1997 unsigned NewOp = createResultReg(RegClass); 1998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1999 TII.get(TargetOpcode::COPY), NewOp).addReg(Op); 2000 return NewOp; 2001 } 2002 } 2003 return Op; 2004 } 2005 2006 unsigned FastISel::fastEmitInst_(unsigned MachineInstOpcode, 2007 const TargetRegisterClass *RC) { 2008 unsigned ResultReg = createResultReg(RC); 2009 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2010 2011 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg); 2012 return ResultReg; 2013 } 2014 2015 unsigned FastISel::fastEmitInst_r(unsigned MachineInstOpcode, 2016 const TargetRegisterClass *RC, unsigned Op0, 2017 bool Op0IsKill) { 2018 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2019 2020 unsigned ResultReg = createResultReg(RC); 2021 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2022 2023 if (II.getNumDefs() >= 1) 2024 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2025 .addReg(Op0, getKillRegState(Op0IsKill)); 2026 else { 2027 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2028 .addReg(Op0, getKillRegState(Op0IsKill)); 2029 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2030 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2031 } 2032 2033 return ResultReg; 2034 } 2035 2036 unsigned FastISel::fastEmitInst_rr(unsigned MachineInstOpcode, 2037 const TargetRegisterClass *RC, unsigned Op0, 2038 bool Op0IsKill, unsigned Op1, 2039 bool Op1IsKill) { 2040 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2041 2042 unsigned ResultReg = createResultReg(RC); 2043 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2044 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 2045 2046 if (II.getNumDefs() >= 1) 2047 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2048 .addReg(Op0, getKillRegState(Op0IsKill)) 2049 .addReg(Op1, getKillRegState(Op1IsKill)); 2050 else { 2051 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2052 .addReg(Op0, getKillRegState(Op0IsKill)) 2053 .addReg(Op1, getKillRegState(Op1IsKill)); 2054 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2055 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2056 } 2057 return ResultReg; 2058 } 2059 2060 unsigned FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode, 2061 const TargetRegisterClass *RC, unsigned Op0, 2062 bool Op0IsKill, unsigned Op1, 2063 bool Op1IsKill, unsigned Op2, 2064 bool Op2IsKill) { 2065 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2066 2067 unsigned ResultReg = createResultReg(RC); 2068 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2069 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 2070 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2); 2071 2072 if (II.getNumDefs() >= 1) 2073 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2074 .addReg(Op0, getKillRegState(Op0IsKill)) 2075 .addReg(Op1, getKillRegState(Op1IsKill)) 2076 .addReg(Op2, getKillRegState(Op2IsKill)); 2077 else { 2078 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2079 .addReg(Op0, getKillRegState(Op0IsKill)) 2080 .addReg(Op1, getKillRegState(Op1IsKill)) 2081 .addReg(Op2, getKillRegState(Op2IsKill)); 2082 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2083 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2084 } 2085 return ResultReg; 2086 } 2087 2088 unsigned FastISel::fastEmitInst_ri(unsigned MachineInstOpcode, 2089 const TargetRegisterClass *RC, unsigned Op0, 2090 bool Op0IsKill, uint64_t Imm) { 2091 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2092 2093 unsigned ResultReg = createResultReg(RC); 2094 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2095 2096 if (II.getNumDefs() >= 1) 2097 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2098 .addReg(Op0, getKillRegState(Op0IsKill)) 2099 .addImm(Imm); 2100 else { 2101 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2102 .addReg(Op0, getKillRegState(Op0IsKill)) 2103 .addImm(Imm); 2104 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2105 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2106 } 2107 return ResultReg; 2108 } 2109 2110 unsigned FastISel::fastEmitInst_rii(unsigned MachineInstOpcode, 2111 const TargetRegisterClass *RC, unsigned Op0, 2112 bool Op0IsKill, uint64_t Imm1, 2113 uint64_t Imm2) { 2114 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2115 2116 unsigned ResultReg = createResultReg(RC); 2117 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2118 2119 if (II.getNumDefs() >= 1) 2120 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2121 .addReg(Op0, getKillRegState(Op0IsKill)) 2122 .addImm(Imm1) 2123 .addImm(Imm2); 2124 else { 2125 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2126 .addReg(Op0, getKillRegState(Op0IsKill)) 2127 .addImm(Imm1) 2128 .addImm(Imm2); 2129 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2130 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2131 } 2132 return ResultReg; 2133 } 2134 2135 unsigned FastISel::fastEmitInst_f(unsigned MachineInstOpcode, 2136 const TargetRegisterClass *RC, 2137 const ConstantFP *FPImm) { 2138 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2139 2140 unsigned ResultReg = createResultReg(RC); 2141 2142 if (II.getNumDefs() >= 1) 2143 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2144 .addFPImm(FPImm); 2145 else { 2146 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2147 .addFPImm(FPImm); 2148 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2149 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2150 } 2151 return ResultReg; 2152 } 2153 2154 unsigned FastISel::fastEmitInst_rri(unsigned MachineInstOpcode, 2155 const TargetRegisterClass *RC, unsigned Op0, 2156 bool Op0IsKill, unsigned Op1, 2157 bool Op1IsKill, uint64_t Imm) { 2158 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2159 2160 unsigned ResultReg = createResultReg(RC); 2161 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2162 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 2163 2164 if (II.getNumDefs() >= 1) 2165 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2166 .addReg(Op0, getKillRegState(Op0IsKill)) 2167 .addReg(Op1, getKillRegState(Op1IsKill)) 2168 .addImm(Imm); 2169 else { 2170 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2171 .addReg(Op0, getKillRegState(Op0IsKill)) 2172 .addReg(Op1, getKillRegState(Op1IsKill)) 2173 .addImm(Imm); 2174 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2175 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2176 } 2177 return ResultReg; 2178 } 2179 2180 unsigned FastISel::fastEmitInst_i(unsigned MachineInstOpcode, 2181 const TargetRegisterClass *RC, uint64_t Imm) { 2182 unsigned ResultReg = createResultReg(RC); 2183 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2184 2185 if (II.getNumDefs() >= 1) 2186 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2187 .addImm(Imm); 2188 else { 2189 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm); 2190 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2191 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2192 } 2193 return ResultReg; 2194 } 2195 2196 unsigned FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0, 2197 bool Op0IsKill, uint32_t Idx) { 2198 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT)); 2199 assert(TargetRegisterInfo::isVirtualRegister(Op0) && 2200 "Cannot yet extract from physregs"); 2201 const TargetRegisterClass *RC = MRI.getRegClass(Op0); 2202 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx)); 2203 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY), 2204 ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx); 2205 return ResultReg; 2206 } 2207 2208 /// Emit MachineInstrs to compute the value of Op with all but the least 2209 /// significant bit set to zero. 2210 unsigned FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) { 2211 return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1); 2212 } 2213 2214 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks. 2215 /// Emit code to ensure constants are copied into registers when needed. 2216 /// Remember the virtual registers that need to be added to the Machine PHI 2217 /// nodes as input. We cannot just directly add them, because expansion 2218 /// might result in multiple MBB's for one BB. As such, the start of the 2219 /// BB might correspond to a different MBB than the end. 2220 bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 2221 const TerminatorInst *TI = LLVMBB->getTerminator(); 2222 2223 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 2224 FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size(); 2225 2226 // Check successor nodes' PHI nodes that expect a constant to be available 2227 // from this block. 2228 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 2229 const BasicBlock *SuccBB = TI->getSuccessor(succ); 2230 if (!isa<PHINode>(SuccBB->begin())) 2231 continue; 2232 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 2233 2234 // If this terminator has multiple identical successors (common for 2235 // switches), only handle each succ once. 2236 if (!SuccsHandled.insert(SuccMBB).second) 2237 continue; 2238 2239 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 2240 2241 // At this point we know that there is a 1-1 correspondence between LLVM PHI 2242 // nodes and Machine PHI nodes, but the incoming operands have not been 2243 // emitted yet. 2244 for (const PHINode &PN : SuccBB->phis()) { 2245 // Ignore dead phi's. 2246 if (PN.use_empty()) 2247 continue; 2248 2249 // Only handle legal types. Two interesting things to note here. First, 2250 // by bailing out early, we may leave behind some dead instructions, 2251 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its 2252 // own moves. Second, this check is necessary because FastISel doesn't 2253 // use CreateRegs to create registers, so it always creates 2254 // exactly one register for each non-void instruction. 2255 EVT VT = TLI.getValueType(DL, PN.getType(), /*AllowUnknown=*/true); 2256 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) { 2257 // Handle integer promotions, though, because they're common and easy. 2258 if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) { 2259 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 2260 return false; 2261 } 2262 } 2263 2264 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 2265 2266 // Set the DebugLoc for the copy. Prefer the location of the operand 2267 // if there is one; use the location of the PHI otherwise. 2268 DbgLoc = PN.getDebugLoc(); 2269 if (const auto *Inst = dyn_cast<Instruction>(PHIOp)) 2270 DbgLoc = Inst->getDebugLoc(); 2271 2272 unsigned Reg = getRegForValue(PHIOp); 2273 if (!Reg) { 2274 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 2275 return false; 2276 } 2277 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(&*MBBI++, Reg)); 2278 DbgLoc = DebugLoc(); 2279 } 2280 } 2281 2282 return true; 2283 } 2284 2285 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) { 2286 assert(LI->hasOneUse() && 2287 "tryToFoldLoad expected a LoadInst with a single use"); 2288 // We know that the load has a single use, but don't know what it is. If it 2289 // isn't one of the folded instructions, then we can't succeed here. Handle 2290 // this by scanning the single-use users of the load until we get to FoldInst. 2291 unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs. 2292 2293 const Instruction *TheUser = LI->user_back(); 2294 while (TheUser != FoldInst && // Scan up until we find FoldInst. 2295 // Stay in the right block. 2296 TheUser->getParent() == FoldInst->getParent() && 2297 --MaxUsers) { // Don't scan too far. 2298 // If there are multiple or no uses of this instruction, then bail out. 2299 if (!TheUser->hasOneUse()) 2300 return false; 2301 2302 TheUser = TheUser->user_back(); 2303 } 2304 2305 // If we didn't find the fold instruction, then we failed to collapse the 2306 // sequence. 2307 if (TheUser != FoldInst) 2308 return false; 2309 2310 // Don't try to fold volatile loads. Target has to deal with alignment 2311 // constraints. 2312 if (LI->isVolatile()) 2313 return false; 2314 2315 // Figure out which vreg this is going into. If there is no assigned vreg yet 2316 // then there actually was no reference to it. Perhaps the load is referenced 2317 // by a dead instruction. 2318 unsigned LoadReg = getRegForValue(LI); 2319 if (!LoadReg) 2320 return false; 2321 2322 // We can't fold if this vreg has no uses or more than one use. Multiple uses 2323 // may mean that the instruction got lowered to multiple MIs, or the use of 2324 // the loaded value ended up being multiple operands of the result. 2325 if (!MRI.hasOneUse(LoadReg)) 2326 return false; 2327 2328 MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg); 2329 MachineInstr *User = RI->getParent(); 2330 2331 // Set the insertion point properly. Folding the load can cause generation of 2332 // other random instructions (like sign extends) for addressing modes; make 2333 // sure they get inserted in a logical place before the new instruction. 2334 FuncInfo.InsertPt = User; 2335 FuncInfo.MBB = User->getParent(); 2336 2337 // Ask the target to try folding the load. 2338 return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI); 2339 } 2340 2341 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) { 2342 // Must be an add. 2343 if (!isa<AddOperator>(Add)) 2344 return false; 2345 // Type size needs to match. 2346 if (DL.getTypeSizeInBits(GEP->getType()) != 2347 DL.getTypeSizeInBits(Add->getType())) 2348 return false; 2349 // Must be in the same basic block. 2350 if (isa<Instruction>(Add) && 2351 FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB) 2352 return false; 2353 // Must have a constant operand. 2354 return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1)); 2355 } 2356 2357 MachineMemOperand * 2358 FastISel::createMachineMemOperandFor(const Instruction *I) const { 2359 const Value *Ptr; 2360 Type *ValTy; 2361 unsigned Alignment; 2362 MachineMemOperand::Flags Flags; 2363 bool IsVolatile; 2364 2365 if (const auto *LI = dyn_cast<LoadInst>(I)) { 2366 Alignment = LI->getAlignment(); 2367 IsVolatile = LI->isVolatile(); 2368 Flags = MachineMemOperand::MOLoad; 2369 Ptr = LI->getPointerOperand(); 2370 ValTy = LI->getType(); 2371 } else if (const auto *SI = dyn_cast<StoreInst>(I)) { 2372 Alignment = SI->getAlignment(); 2373 IsVolatile = SI->isVolatile(); 2374 Flags = MachineMemOperand::MOStore; 2375 Ptr = SI->getPointerOperand(); 2376 ValTy = SI->getValueOperand()->getType(); 2377 } else 2378 return nullptr; 2379 2380 bool IsNonTemporal = I->getMetadata(LLVMContext::MD_nontemporal) != nullptr; 2381 bool IsInvariant = I->getMetadata(LLVMContext::MD_invariant_load) != nullptr; 2382 bool IsDereferenceable = 2383 I->getMetadata(LLVMContext::MD_dereferenceable) != nullptr; 2384 const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range); 2385 2386 AAMDNodes AAInfo; 2387 I->getAAMetadata(AAInfo); 2388 2389 if (Alignment == 0) // Ensure that codegen never sees alignment 0. 2390 Alignment = DL.getABITypeAlignment(ValTy); 2391 2392 unsigned Size = DL.getTypeStoreSize(ValTy); 2393 2394 if (IsVolatile) 2395 Flags |= MachineMemOperand::MOVolatile; 2396 if (IsNonTemporal) 2397 Flags |= MachineMemOperand::MONonTemporal; 2398 if (IsDereferenceable) 2399 Flags |= MachineMemOperand::MODereferenceable; 2400 if (IsInvariant) 2401 Flags |= MachineMemOperand::MOInvariant; 2402 2403 return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size, 2404 Alignment, AAInfo, Ranges); 2405 } 2406 2407 CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const { 2408 // If both operands are the same, then try to optimize or fold the cmp. 2409 CmpInst::Predicate Predicate = CI->getPredicate(); 2410 if (CI->getOperand(0) != CI->getOperand(1)) 2411 return Predicate; 2412 2413 switch (Predicate) { 2414 default: llvm_unreachable("Invalid predicate!"); 2415 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break; 2416 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break; 2417 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break; 2418 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break; 2419 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break; 2420 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break; 2421 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break; 2422 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break; 2423 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break; 2424 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break; 2425 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break; 2426 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break; 2427 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break; 2428 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break; 2429 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break; 2430 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break; 2431 2432 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break; 2433 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break; 2434 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break; 2435 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break; 2436 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break; 2437 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break; 2438 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break; 2439 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break; 2440 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break; 2441 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break; 2442 } 2443 2444 return Predicate; 2445 } 2446