1 //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// This file implements the IRTranslator class. 10 //===----------------------------------------------------------------------===// 11 12 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 13 #include "llvm/ADT/PostOrderIterator.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/ScopeExit.h" 16 #include "llvm/ADT/SmallSet.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/BranchProbabilityInfo.h" 19 #include "llvm/Analysis/Loads.h" 20 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/CodeGen/Analysis.h" 23 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 24 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h" 25 #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h" 26 #include "llvm/CodeGen/LowLevelType.h" 27 #include "llvm/CodeGen/MachineBasicBlock.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineFunction.h" 30 #include "llvm/CodeGen/MachineInstrBuilder.h" 31 #include "llvm/CodeGen/MachineMemOperand.h" 32 #include "llvm/CodeGen/MachineOperand.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/StackProtector.h" 35 #include "llvm/CodeGen/TargetFrameLowering.h" 36 #include "llvm/CodeGen/TargetInstrInfo.h" 37 #include "llvm/CodeGen/TargetLowering.h" 38 #include "llvm/CodeGen/TargetPassConfig.h" 39 #include "llvm/CodeGen/TargetRegisterInfo.h" 40 #include "llvm/CodeGen/TargetSubtargetInfo.h" 41 #include "llvm/IR/BasicBlock.h" 42 #include "llvm/IR/CFG.h" 43 #include "llvm/IR/Constant.h" 44 #include "llvm/IR/Constants.h" 45 #include "llvm/IR/DataLayout.h" 46 #include "llvm/IR/DebugInfo.h" 47 #include "llvm/IR/DerivedTypes.h" 48 #include "llvm/IR/Function.h" 49 #include "llvm/IR/GetElementPtrTypeIterator.h" 50 #include "llvm/IR/InlineAsm.h" 51 #include "llvm/IR/Instructions.h" 52 #include "llvm/IR/IntrinsicInst.h" 53 #include "llvm/IR/Intrinsics.h" 54 #include "llvm/IR/LLVMContext.h" 55 #include "llvm/IR/Metadata.h" 56 #include "llvm/IR/Type.h" 57 #include "llvm/IR/User.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/InitializePasses.h" 60 #include "llvm/MC/MCContext.h" 61 #include "llvm/Pass.h" 62 #include "llvm/Support/Casting.h" 63 #include "llvm/Support/CodeGen.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/LowLevelTypeImpl.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Target/TargetIntrinsicInfo.h" 70 #include "llvm/Target/TargetMachine.h" 71 #include <algorithm> 72 #include <cassert> 73 #include <cstdint> 74 #include <iterator> 75 #include <string> 76 #include <utility> 77 #include <vector> 78 79 #define DEBUG_TYPE "irtranslator" 80 81 using namespace llvm; 82 83 static cl::opt<bool> 84 EnableCSEInIRTranslator("enable-cse-in-irtranslator", 85 cl::desc("Should enable CSE in irtranslator"), 86 cl::Optional, cl::init(false)); 87 char IRTranslator::ID = 0; 88 89 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 90 false, false) 91 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 92 INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass) 93 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 94 false, false) 95 96 static void reportTranslationError(MachineFunction &MF, 97 const TargetPassConfig &TPC, 98 OptimizationRemarkEmitter &ORE, 99 OptimizationRemarkMissed &R) { 100 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 101 102 // Print the function name explicitly if we don't have a debug location (which 103 // makes the diagnostic less useful) or if we're going to emit a raw error. 104 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled()) 105 R << (" (in function: " + MF.getName() + ")").str(); 106 107 if (TPC.isGlobalISelAbortEnabled()) 108 report_fatal_error(R.getMsg()); 109 else 110 ORE.emit(R); 111 } 112 113 IRTranslator::IRTranslator() : MachineFunctionPass(ID) { } 114 115 #ifndef NDEBUG 116 namespace { 117 /// Verify that every instruction created has the same DILocation as the 118 /// instruction being translated. 119 class DILocationVerifier : public GISelChangeObserver { 120 const Instruction *CurrInst = nullptr; 121 122 public: 123 DILocationVerifier() = default; 124 ~DILocationVerifier() = default; 125 126 const Instruction *getCurrentInst() const { return CurrInst; } 127 void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; } 128 129 void erasingInstr(MachineInstr &MI) override {} 130 void changingInstr(MachineInstr &MI) override {} 131 void changedInstr(MachineInstr &MI) override {} 132 133 void createdInstr(MachineInstr &MI) override { 134 assert(getCurrentInst() && "Inserted instruction without a current MI"); 135 136 // Only print the check message if we're actually checking it. 137 #ifndef NDEBUG 138 LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst 139 << " was copied to " << MI); 140 #endif 141 // We allow insts in the entry block to have a debug loc line of 0 because 142 // they could have originated from constants, and we don't want a jumpy 143 // debug experience. 144 assert((CurrInst->getDebugLoc() == MI.getDebugLoc() || 145 MI.getDebugLoc().getLine() == 0) && 146 "Line info was not transferred to all instructions"); 147 } 148 }; 149 } // namespace 150 #endif // ifndef NDEBUG 151 152 153 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const { 154 AU.addRequired<StackProtector>(); 155 AU.addRequired<TargetPassConfig>(); 156 AU.addRequired<GISelCSEAnalysisWrapperPass>(); 157 getSelectionDAGFallbackAnalysisUsage(AU); 158 MachineFunctionPass::getAnalysisUsage(AU); 159 } 160 161 IRTranslator::ValueToVRegInfo::VRegListT & 162 IRTranslator::allocateVRegs(const Value &Val) { 163 assert(!VMap.contains(Val) && "Value already allocated in VMap"); 164 auto *Regs = VMap.getVRegs(Val); 165 auto *Offsets = VMap.getOffsets(Val); 166 SmallVector<LLT, 4> SplitTys; 167 computeValueLLTs(*DL, *Val.getType(), SplitTys, 168 Offsets->empty() ? Offsets : nullptr); 169 for (unsigned i = 0; i < SplitTys.size(); ++i) 170 Regs->push_back(0); 171 return *Regs; 172 } 173 174 ArrayRef<Register> IRTranslator::getOrCreateVRegs(const Value &Val) { 175 auto VRegsIt = VMap.findVRegs(Val); 176 if (VRegsIt != VMap.vregs_end()) 177 return *VRegsIt->second; 178 179 if (Val.getType()->isVoidTy()) 180 return *VMap.getVRegs(Val); 181 182 // Create entry for this type. 183 auto *VRegs = VMap.getVRegs(Val); 184 auto *Offsets = VMap.getOffsets(Val); 185 186 assert(Val.getType()->isSized() && 187 "Don't know how to create an empty vreg"); 188 189 SmallVector<LLT, 4> SplitTys; 190 computeValueLLTs(*DL, *Val.getType(), SplitTys, 191 Offsets->empty() ? Offsets : nullptr); 192 193 if (!isa<Constant>(Val)) { 194 for (auto Ty : SplitTys) 195 VRegs->push_back(MRI->createGenericVirtualRegister(Ty)); 196 return *VRegs; 197 } 198 199 if (Val.getType()->isAggregateType()) { 200 // UndefValue, ConstantAggregateZero 201 auto &C = cast<Constant>(Val); 202 unsigned Idx = 0; 203 while (auto Elt = C.getAggregateElement(Idx++)) { 204 auto EltRegs = getOrCreateVRegs(*Elt); 205 llvm::copy(EltRegs, std::back_inserter(*VRegs)); 206 } 207 } else { 208 assert(SplitTys.size() == 1 && "unexpectedly split LLT"); 209 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0])); 210 bool Success = translate(cast<Constant>(Val), VRegs->front()); 211 if (!Success) { 212 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 213 MF->getFunction().getSubprogram(), 214 &MF->getFunction().getEntryBlock()); 215 R << "unable to translate constant: " << ore::NV("Type", Val.getType()); 216 reportTranslationError(*MF, *TPC, *ORE, R); 217 return *VRegs; 218 } 219 } 220 221 return *VRegs; 222 } 223 224 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) { 225 if (FrameIndices.find(&AI) != FrameIndices.end()) 226 return FrameIndices[&AI]; 227 228 uint64_t ElementSize = DL->getTypeAllocSize(AI.getAllocatedType()); 229 uint64_t Size = 230 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue(); 231 232 // Always allocate at least one byte. 233 Size = std::max<uint64_t>(Size, 1u); 234 235 int &FI = FrameIndices[&AI]; 236 FI = MF->getFrameInfo().CreateStackObject(Size, AI.getAlign(), false, &AI); 237 return FI; 238 } 239 240 Align IRTranslator::getMemOpAlign(const Instruction &I) { 241 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) 242 return SI->getAlign(); 243 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 244 return LI->getAlign(); 245 } 246 if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) { 247 // TODO(PR27168): This instruction has no alignment attribute, but unlike 248 // the default alignment for load/store, the default here is to assume 249 // it has NATURAL alignment, not DataLayout-specified alignment. 250 const DataLayout &DL = AI->getModule()->getDataLayout(); 251 return Align(DL.getTypeStoreSize(AI->getCompareOperand()->getType())); 252 } 253 if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) { 254 // TODO(PR27168): This instruction has no alignment attribute, but unlike 255 // the default alignment for load/store, the default here is to assume 256 // it has NATURAL alignment, not DataLayout-specified alignment. 257 const DataLayout &DL = AI->getModule()->getDataLayout(); 258 return Align(DL.getTypeStoreSize(AI->getValOperand()->getType())); 259 } 260 OptimizationRemarkMissed R("gisel-irtranslator", "", &I); 261 R << "unable to translate memop: " << ore::NV("Opcode", &I); 262 reportTranslationError(*MF, *TPC, *ORE, R); 263 return Align(1); 264 } 265 266 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) { 267 MachineBasicBlock *&MBB = BBToMBB[&BB]; 268 assert(MBB && "BasicBlock was not encountered before"); 269 return *MBB; 270 } 271 272 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) { 273 assert(NewPred && "new predecessor must be a real MachineBasicBlock"); 274 MachinePreds[Edge].push_back(NewPred); 275 } 276 277 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U, 278 MachineIRBuilder &MIRBuilder) { 279 // Get or create a virtual register for each value. 280 // Unless the value is a Constant => loadimm cst? 281 // or inline constant each time? 282 // Creation of a virtual register needs to have a size. 283 Register Op0 = getOrCreateVReg(*U.getOperand(0)); 284 Register Op1 = getOrCreateVReg(*U.getOperand(1)); 285 Register Res = getOrCreateVReg(U); 286 uint16_t Flags = 0; 287 if (isa<Instruction>(U)) { 288 const Instruction &I = cast<Instruction>(U); 289 Flags = MachineInstr::copyFlagsFromInstruction(I); 290 } 291 292 MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags); 293 return true; 294 } 295 296 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) { 297 // -0.0 - X --> G_FNEG 298 if (isa<Constant>(U.getOperand(0)) && 299 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) { 300 Register Op1 = getOrCreateVReg(*U.getOperand(1)); 301 Register Res = getOrCreateVReg(U); 302 uint16_t Flags = 0; 303 if (isa<Instruction>(U)) { 304 const Instruction &I = cast<Instruction>(U); 305 Flags = MachineInstr::copyFlagsFromInstruction(I); 306 } 307 // Negate the last operand of the FSUB 308 MIRBuilder.buildFNeg(Res, Op1, Flags); 309 return true; 310 } 311 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder); 312 } 313 314 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) { 315 Register Op0 = getOrCreateVReg(*U.getOperand(0)); 316 Register Res = getOrCreateVReg(U); 317 uint16_t Flags = 0; 318 if (isa<Instruction>(U)) { 319 const Instruction &I = cast<Instruction>(U); 320 Flags = MachineInstr::copyFlagsFromInstruction(I); 321 } 322 MIRBuilder.buildFNeg(Res, Op0, Flags); 323 return true; 324 } 325 326 bool IRTranslator::translateCompare(const User &U, 327 MachineIRBuilder &MIRBuilder) { 328 auto *CI = dyn_cast<CmpInst>(&U); 329 Register Op0 = getOrCreateVReg(*U.getOperand(0)); 330 Register Op1 = getOrCreateVReg(*U.getOperand(1)); 331 Register Res = getOrCreateVReg(U); 332 CmpInst::Predicate Pred = 333 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>( 334 cast<ConstantExpr>(U).getPredicate()); 335 if (CmpInst::isIntPredicate(Pred)) 336 MIRBuilder.buildICmp(Pred, Res, Op0, Op1); 337 else if (Pred == CmpInst::FCMP_FALSE) 338 MIRBuilder.buildCopy( 339 Res, getOrCreateVReg(*Constant::getNullValue(U.getType()))); 340 else if (Pred == CmpInst::FCMP_TRUE) 341 MIRBuilder.buildCopy( 342 Res, getOrCreateVReg(*Constant::getAllOnesValue(U.getType()))); 343 else { 344 assert(CI && "Instruction should be CmpInst"); 345 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1, 346 MachineInstr::copyFlagsFromInstruction(*CI)); 347 } 348 349 return true; 350 } 351 352 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) { 353 const ReturnInst &RI = cast<ReturnInst>(U); 354 const Value *Ret = RI.getReturnValue(); 355 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0) 356 Ret = nullptr; 357 358 ArrayRef<Register> VRegs; 359 if (Ret) 360 VRegs = getOrCreateVRegs(*Ret); 361 362 Register SwiftErrorVReg = 0; 363 if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) { 364 SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt( 365 &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg()); 366 } 367 368 // The target may mess up with the insertion point, but 369 // this is not important as a return is the last instruction 370 // of the block anyway. 371 return CLI->lowerReturn(MIRBuilder, Ret, VRegs, SwiftErrorVReg); 372 } 373 374 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) { 375 const BranchInst &BrInst = cast<BranchInst>(U); 376 unsigned Succ = 0; 377 if (!BrInst.isUnconditional()) { 378 // We want a G_BRCOND to the true BB followed by an unconditional branch. 379 Register Tst = getOrCreateVReg(*BrInst.getCondition()); 380 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++)); 381 MachineBasicBlock &TrueBB = getMBB(TrueTgt); 382 MIRBuilder.buildBrCond(Tst, TrueBB); 383 } 384 385 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ)); 386 MachineBasicBlock &TgtBB = getMBB(BrTgt); 387 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 388 389 // If the unconditional target is the layout successor, fallthrough. 390 if (!CurBB.isLayoutSuccessor(&TgtBB)) 391 MIRBuilder.buildBr(TgtBB); 392 393 // Link successors. 394 for (const BasicBlock *Succ : successors(&BrInst)) 395 CurBB.addSuccessor(&getMBB(*Succ)); 396 return true; 397 } 398 399 void IRTranslator::addSuccessorWithProb(MachineBasicBlock *Src, 400 MachineBasicBlock *Dst, 401 BranchProbability Prob) { 402 if (!FuncInfo.BPI) { 403 Src->addSuccessorWithoutProb(Dst); 404 return; 405 } 406 if (Prob.isUnknown()) 407 Prob = getEdgeProbability(Src, Dst); 408 Src->addSuccessor(Dst, Prob); 409 } 410 411 BranchProbability 412 IRTranslator::getEdgeProbability(const MachineBasicBlock *Src, 413 const MachineBasicBlock *Dst) const { 414 const BasicBlock *SrcBB = Src->getBasicBlock(); 415 const BasicBlock *DstBB = Dst->getBasicBlock(); 416 if (!FuncInfo.BPI) { 417 // If BPI is not available, set the default probability as 1 / N, where N is 418 // the number of successors. 419 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 420 return BranchProbability(1, SuccSize); 421 } 422 return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB); 423 } 424 425 bool IRTranslator::translateSwitch(const User &U, MachineIRBuilder &MIB) { 426 using namespace SwitchCG; 427 // Extract cases from the switch. 428 const SwitchInst &SI = cast<SwitchInst>(U); 429 BranchProbabilityInfo *BPI = FuncInfo.BPI; 430 CaseClusterVector Clusters; 431 Clusters.reserve(SI.getNumCases()); 432 for (auto &I : SI.cases()) { 433 MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor()); 434 assert(Succ && "Could not find successor mbb in mapping"); 435 const ConstantInt *CaseVal = I.getCaseValue(); 436 BranchProbability Prob = 437 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 438 : BranchProbability(1, SI.getNumCases() + 1); 439 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 440 } 441 442 MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest()); 443 444 // Cluster adjacent cases with the same destination. We do this at all 445 // optimization levels because it's cheap to do and will make codegen faster 446 // if there are many clusters. 447 sortAndRangeify(Clusters); 448 449 MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent()); 450 451 // If there is only the default destination, jump there directly. 452 if (Clusters.empty()) { 453 SwitchMBB->addSuccessor(DefaultMBB); 454 if (DefaultMBB != SwitchMBB->getNextNode()) 455 MIB.buildBr(*DefaultMBB); 456 return true; 457 } 458 459 SL->findJumpTables(Clusters, &SI, DefaultMBB, nullptr, nullptr); 460 461 LLVM_DEBUG({ 462 dbgs() << "Case clusters: "; 463 for (const CaseCluster &C : Clusters) { 464 if (C.Kind == CC_JumpTable) 465 dbgs() << "JT:"; 466 if (C.Kind == CC_BitTests) 467 dbgs() << "BT:"; 468 469 C.Low->getValue().print(dbgs(), true); 470 if (C.Low != C.High) { 471 dbgs() << '-'; 472 C.High->getValue().print(dbgs(), true); 473 } 474 dbgs() << ' '; 475 } 476 dbgs() << '\n'; 477 }); 478 479 assert(!Clusters.empty()); 480 SwitchWorkList WorkList; 481 CaseClusterIt First = Clusters.begin(); 482 CaseClusterIt Last = Clusters.end() - 1; 483 auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB); 484 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 485 486 // FIXME: At the moment we don't do any splitting optimizations here like 487 // SelectionDAG does, so this worklist only has one entry. 488 while (!WorkList.empty()) { 489 SwitchWorkListItem W = WorkList.back(); 490 WorkList.pop_back(); 491 if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB)) 492 return false; 493 } 494 return true; 495 } 496 497 void IRTranslator::emitJumpTable(SwitchCG::JumpTable &JT, 498 MachineBasicBlock *MBB) { 499 // Emit the code for the jump table 500 assert(JT.Reg != -1U && "Should lower JT Header first!"); 501 MachineIRBuilder MIB(*MBB->getParent()); 502 MIB.setMBB(*MBB); 503 MIB.setDebugLoc(CurBuilder->getDebugLoc()); 504 505 Type *PtrIRTy = Type::getInt8PtrTy(MF->getFunction().getContext()); 506 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL); 507 508 auto Table = MIB.buildJumpTable(PtrTy, JT.JTI); 509 MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg); 510 } 511 512 bool IRTranslator::emitJumpTableHeader(SwitchCG::JumpTable &JT, 513 SwitchCG::JumpTableHeader &JTH, 514 MachineBasicBlock *HeaderBB) { 515 MachineIRBuilder MIB(*HeaderBB->getParent()); 516 MIB.setMBB(*HeaderBB); 517 MIB.setDebugLoc(CurBuilder->getDebugLoc()); 518 519 const Value &SValue = *JTH.SValue; 520 // Subtract the lowest switch case value from the value being switched on. 521 const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL); 522 Register SwitchOpReg = getOrCreateVReg(SValue); 523 auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First); 524 auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst); 525 526 // This value may be smaller or larger than the target's pointer type, and 527 // therefore require extension or truncating. 528 Type *PtrIRTy = SValue.getType()->getPointerTo(); 529 const LLT PtrScalarTy = LLT::scalar(DL->getTypeSizeInBits(PtrIRTy)); 530 Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub); 531 532 JT.Reg = Sub.getReg(0); 533 534 if (JTH.OmitRangeCheck) { 535 if (JT.MBB != HeaderBB->getNextNode()) 536 MIB.buildBr(*JT.MBB); 537 return true; 538 } 539 540 // Emit the range check for the jump table, and branch to the default block 541 // for the switch statement if the value being switched on exceeds the 542 // largest case in the switch. 543 auto Cst = getOrCreateVReg( 544 *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First)); 545 Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0); 546 auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::scalar(1), Sub, Cst); 547 548 auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default); 549 550 // Avoid emitting unnecessary branches to the next block. 551 if (JT.MBB != HeaderBB->getNextNode()) 552 BrCond = MIB.buildBr(*JT.MBB); 553 return true; 554 } 555 556 void IRTranslator::emitSwitchCase(SwitchCG::CaseBlock &CB, 557 MachineBasicBlock *SwitchBB, 558 MachineIRBuilder &MIB) { 559 Register CondLHS = getOrCreateVReg(*CB.CmpLHS); 560 Register Cond; 561 DebugLoc OldDbgLoc = MIB.getDebugLoc(); 562 MIB.setDebugLoc(CB.DbgLoc); 563 MIB.setMBB(*CB.ThisBB); 564 565 if (CB.PredInfo.NoCmp) { 566 // Branch or fall through to TrueBB. 567 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb); 568 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()}, 569 CB.ThisBB); 570 CB.ThisBB->normalizeSuccProbs(); 571 if (CB.TrueBB != CB.ThisBB->getNextNode()) 572 MIB.buildBr(*CB.TrueBB); 573 MIB.setDebugLoc(OldDbgLoc); 574 return; 575 } 576 577 const LLT i1Ty = LLT::scalar(1); 578 // Build the compare. 579 if (!CB.CmpMHS) { 580 Register CondRHS = getOrCreateVReg(*CB.CmpRHS); 581 Cond = MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0); 582 } else { 583 assert(CB.PredInfo.Pred == CmpInst::ICMP_SLE && 584 "Can only handle SLE ranges"); 585 586 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 587 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 588 589 Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS); 590 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 591 Register CondRHS = getOrCreateVReg(*CB.CmpRHS); 592 Cond = 593 MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0); 594 } else { 595 const LLT CmpTy = MRI->getType(CmpOpReg); 596 auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS); 597 auto Diff = MIB.buildConstant(CmpTy, High - Low); 598 Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0); 599 } 600 } 601 602 // Update successor info 603 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb); 604 605 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()}, 606 CB.ThisBB); 607 608 // TrueBB and FalseBB are always different unless the incoming IR is 609 // degenerate. This only happens when running llc on weird IR. 610 if (CB.TrueBB != CB.FalseBB) 611 addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb); 612 CB.ThisBB->normalizeSuccProbs(); 613 614 // if (SwitchBB->getBasicBlock() != CB.FalseBB->getBasicBlock()) 615 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()}, 616 CB.ThisBB); 617 618 // If the lhs block is the next block, invert the condition so that we can 619 // fall through to the lhs instead of the rhs block. 620 if (CB.TrueBB == CB.ThisBB->getNextNode()) { 621 std::swap(CB.TrueBB, CB.FalseBB); 622 auto True = MIB.buildConstant(i1Ty, 1); 623 Cond = MIB.buildXor(i1Ty, Cond, True).getReg(0); 624 } 625 626 MIB.buildBrCond(Cond, *CB.TrueBB); 627 MIB.buildBr(*CB.FalseBB); 628 MIB.setDebugLoc(OldDbgLoc); 629 } 630 631 bool IRTranslator::lowerJumpTableWorkItem(SwitchCG::SwitchWorkListItem W, 632 MachineBasicBlock *SwitchMBB, 633 MachineBasicBlock *CurMBB, 634 MachineBasicBlock *DefaultMBB, 635 MachineIRBuilder &MIB, 636 MachineFunction::iterator BBI, 637 BranchProbability UnhandledProbs, 638 SwitchCG::CaseClusterIt I, 639 MachineBasicBlock *Fallthrough, 640 bool FallthroughUnreachable) { 641 using namespace SwitchCG; 642 MachineFunction *CurMF = SwitchMBB->getParent(); 643 // FIXME: Optimize away range check based on pivot comparisons. 644 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 645 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 646 BranchProbability DefaultProb = W.DefaultProb; 647 648 // The jump block hasn't been inserted yet; insert it here. 649 MachineBasicBlock *JumpMBB = JT->MBB; 650 CurMF->insert(BBI, JumpMBB); 651 652 // Since the jump table block is separate from the switch block, we need 653 // to keep track of it as a machine predecessor to the default block, 654 // otherwise we lose the phi edges. 655 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()}, 656 CurMBB); 657 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()}, 658 JumpMBB); 659 660 auto JumpProb = I->Prob; 661 auto FallthroughProb = UnhandledProbs; 662 663 // If the default statement is a target of the jump table, we evenly 664 // distribute the default probability to successors of CurMBB. Also 665 // update the probability on the edge from JumpMBB to Fallthrough. 666 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 667 SE = JumpMBB->succ_end(); 668 SI != SE; ++SI) { 669 if (*SI == DefaultMBB) { 670 JumpProb += DefaultProb / 2; 671 FallthroughProb -= DefaultProb / 2; 672 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 673 JumpMBB->normalizeSuccProbs(); 674 } else { 675 // Also record edges from the jump table block to it's successors. 676 addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()}, 677 JumpMBB); 678 } 679 } 680 681 // Skip the range check if the fallthrough block is unreachable. 682 if (FallthroughUnreachable) 683 JTH->OmitRangeCheck = true; 684 685 if (!JTH->OmitRangeCheck) 686 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 687 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 688 CurMBB->normalizeSuccProbs(); 689 690 // The jump table header will be inserted in our current block, do the 691 // range check, and fall through to our fallthrough block. 692 JTH->HeaderBB = CurMBB; 693 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 694 695 // If we're in the right place, emit the jump table header right now. 696 if (CurMBB == SwitchMBB) { 697 if (!emitJumpTableHeader(*JT, *JTH, CurMBB)) 698 return false; 699 JTH->Emitted = true; 700 } 701 return true; 702 } 703 bool IRTranslator::lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I, 704 Value *Cond, 705 MachineBasicBlock *Fallthrough, 706 bool FallthroughUnreachable, 707 BranchProbability UnhandledProbs, 708 MachineBasicBlock *CurMBB, 709 MachineIRBuilder &MIB, 710 MachineBasicBlock *SwitchMBB) { 711 using namespace SwitchCG; 712 const Value *RHS, *LHS, *MHS; 713 CmpInst::Predicate Pred; 714 if (I->Low == I->High) { 715 // Check Cond == I->Low. 716 Pred = CmpInst::ICMP_EQ; 717 LHS = Cond; 718 RHS = I->Low; 719 MHS = nullptr; 720 } else { 721 // Check I->Low <= Cond <= I->High. 722 Pred = CmpInst::ICMP_SLE; 723 LHS = I->Low; 724 MHS = Cond; 725 RHS = I->High; 726 } 727 728 // If Fallthrough is unreachable, fold away the comparison. 729 // The false probability is the sum of all unhandled cases. 730 CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough, 731 CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs); 732 733 emitSwitchCase(CB, SwitchMBB, MIB); 734 return true; 735 } 736 737 bool IRTranslator::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W, 738 Value *Cond, 739 MachineBasicBlock *SwitchMBB, 740 MachineBasicBlock *DefaultMBB, 741 MachineIRBuilder &MIB) { 742 using namespace SwitchCG; 743 MachineFunction *CurMF = FuncInfo.MF; 744 MachineBasicBlock *NextMBB = nullptr; 745 MachineFunction::iterator BBI(W.MBB); 746 if (++BBI != FuncInfo.MF->end()) 747 NextMBB = &*BBI; 748 749 if (EnableOpts) { 750 // Here, we order cases by probability so the most likely case will be 751 // checked first. However, two clusters can have the same probability in 752 // which case their relative ordering is non-deterministic. So we use Low 753 // as a tie-breaker as clusters are guaranteed to never overlap. 754 llvm::sort(W.FirstCluster, W.LastCluster + 1, 755 [](const CaseCluster &a, const CaseCluster &b) { 756 return a.Prob != b.Prob 757 ? a.Prob > b.Prob 758 : a.Low->getValue().slt(b.Low->getValue()); 759 }); 760 761 // Rearrange the case blocks so that the last one falls through if possible 762 // without changing the order of probabilities. 763 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) { 764 --I; 765 if (I->Prob > W.LastCluster->Prob) 766 break; 767 if (I->Kind == CC_Range && I->MBB == NextMBB) { 768 std::swap(*I, *W.LastCluster); 769 break; 770 } 771 } 772 } 773 774 // Compute total probability. 775 BranchProbability DefaultProb = W.DefaultProb; 776 BranchProbability UnhandledProbs = DefaultProb; 777 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 778 UnhandledProbs += I->Prob; 779 780 MachineBasicBlock *CurMBB = W.MBB; 781 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 782 bool FallthroughUnreachable = false; 783 MachineBasicBlock *Fallthrough; 784 if (I == W.LastCluster) { 785 // For the last cluster, fall through to the default destination. 786 Fallthrough = DefaultMBB; 787 FallthroughUnreachable = isa<UnreachableInst>( 788 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 789 } else { 790 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 791 CurMF->insert(BBI, Fallthrough); 792 } 793 UnhandledProbs -= I->Prob; 794 795 switch (I->Kind) { 796 case CC_BitTests: { 797 LLVM_DEBUG(dbgs() << "Switch to bit test optimization unimplemented"); 798 return false; // Bit tests currently unimplemented. 799 } 800 case CC_JumpTable: { 801 if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI, 802 UnhandledProbs, I, Fallthrough, 803 FallthroughUnreachable)) { 804 LLVM_DEBUG(dbgs() << "Failed to lower jump table"); 805 return false; 806 } 807 break; 808 } 809 case CC_Range: { 810 if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough, 811 FallthroughUnreachable, UnhandledProbs, 812 CurMBB, MIB, SwitchMBB)) { 813 LLVM_DEBUG(dbgs() << "Failed to lower switch range"); 814 return false; 815 } 816 break; 817 } 818 } 819 CurMBB = Fallthrough; 820 } 821 822 return true; 823 } 824 825 bool IRTranslator::translateIndirectBr(const User &U, 826 MachineIRBuilder &MIRBuilder) { 827 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U); 828 829 const Register Tgt = getOrCreateVReg(*BrInst.getAddress()); 830 MIRBuilder.buildBrIndirect(Tgt); 831 832 // Link successors. 833 SmallPtrSet<const BasicBlock *, 32> AddedSuccessors; 834 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 835 for (const BasicBlock *Succ : successors(&BrInst)) { 836 // It's legal for indirectbr instructions to have duplicate blocks in the 837 // destination list. We don't allow this in MIR. Skip anything that's 838 // already a successor. 839 if (!AddedSuccessors.insert(Succ).second) 840 continue; 841 CurBB.addSuccessor(&getMBB(*Succ)); 842 } 843 844 return true; 845 } 846 847 static bool isSwiftError(const Value *V) { 848 if (auto Arg = dyn_cast<Argument>(V)) 849 return Arg->hasSwiftErrorAttr(); 850 if (auto AI = dyn_cast<AllocaInst>(V)) 851 return AI->isSwiftError(); 852 return false; 853 } 854 855 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) { 856 const LoadInst &LI = cast<LoadInst>(U); 857 if (DL->getTypeStoreSize(LI.getType()) == 0) 858 return true; 859 860 ArrayRef<Register> Regs = getOrCreateVRegs(LI); 861 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI); 862 Register Base = getOrCreateVReg(*LI.getPointerOperand()); 863 864 Type *OffsetIRTy = DL->getIntPtrType(LI.getPointerOperandType()); 865 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 866 867 if (CLI->supportSwiftError() && isSwiftError(LI.getPointerOperand())) { 868 assert(Regs.size() == 1 && "swifterror should be single pointer"); 869 Register VReg = SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(), 870 LI.getPointerOperand()); 871 MIRBuilder.buildCopy(Regs[0], VReg); 872 return true; 873 } 874 875 auto &TLI = *MF->getSubtarget().getTargetLowering(); 876 MachineMemOperand::Flags Flags = TLI.getLoadMemOperandFlags(LI, *DL); 877 878 const MDNode *Ranges = 879 Regs.size() == 1 ? LI.getMetadata(LLVMContext::MD_range) : nullptr; 880 for (unsigned i = 0; i < Regs.size(); ++i) { 881 Register Addr; 882 MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8); 883 884 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8); 885 Align BaseAlign = getMemOpAlign(LI); 886 AAMDNodes AAMetadata; 887 LI.getAAMetadata(AAMetadata); 888 auto MMO = MF->getMachineMemOperand( 889 Ptr, Flags, MRI->getType(Regs[i]).getSizeInBytes(), 890 commonAlignment(BaseAlign, Offsets[i] / 8), AAMetadata, Ranges, 891 LI.getSyncScopeID(), LI.getOrdering()); 892 MIRBuilder.buildLoad(Regs[i], Addr, *MMO); 893 } 894 895 return true; 896 } 897 898 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) { 899 const StoreInst &SI = cast<StoreInst>(U); 900 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0) 901 return true; 902 903 ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand()); 904 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand()); 905 Register Base = getOrCreateVReg(*SI.getPointerOperand()); 906 907 Type *OffsetIRTy = DL->getIntPtrType(SI.getPointerOperandType()); 908 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 909 910 if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) { 911 assert(Vals.size() == 1 && "swifterror should be single pointer"); 912 913 Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(), 914 SI.getPointerOperand()); 915 MIRBuilder.buildCopy(VReg, Vals[0]); 916 return true; 917 } 918 919 auto &TLI = *MF->getSubtarget().getTargetLowering(); 920 MachineMemOperand::Flags Flags = TLI.getStoreMemOperandFlags(SI, *DL); 921 922 for (unsigned i = 0; i < Vals.size(); ++i) { 923 Register Addr; 924 MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8); 925 926 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8); 927 Align BaseAlign = getMemOpAlign(SI); 928 AAMDNodes AAMetadata; 929 SI.getAAMetadata(AAMetadata); 930 auto MMO = MF->getMachineMemOperand( 931 Ptr, Flags, MRI->getType(Vals[i]).getSizeInBytes(), 932 commonAlignment(BaseAlign, Offsets[i] / 8), AAMetadata, nullptr, 933 SI.getSyncScopeID(), SI.getOrdering()); 934 MIRBuilder.buildStore(Vals[i], Addr, *MMO); 935 } 936 return true; 937 } 938 939 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) { 940 const Value *Src = U.getOperand(0); 941 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 942 943 // getIndexedOffsetInType is designed for GEPs, so the first index is the 944 // usual array element rather than looking into the actual aggregate. 945 SmallVector<Value *, 1> Indices; 946 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 947 948 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) { 949 for (auto Idx : EVI->indices()) 950 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 951 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) { 952 for (auto Idx : IVI->indices()) 953 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 954 } else { 955 for (unsigned i = 1; i < U.getNumOperands(); ++i) 956 Indices.push_back(U.getOperand(i)); 957 } 958 959 return 8 * static_cast<uint64_t>( 960 DL.getIndexedOffsetInType(Src->getType(), Indices)); 961 } 962 963 bool IRTranslator::translateExtractValue(const User &U, 964 MachineIRBuilder &MIRBuilder) { 965 const Value *Src = U.getOperand(0); 966 uint64_t Offset = getOffsetFromIndices(U, *DL); 967 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src); 968 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src); 969 unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin(); 970 auto &DstRegs = allocateVRegs(U); 971 972 for (unsigned i = 0; i < DstRegs.size(); ++i) 973 DstRegs[i] = SrcRegs[Idx++]; 974 975 return true; 976 } 977 978 bool IRTranslator::translateInsertValue(const User &U, 979 MachineIRBuilder &MIRBuilder) { 980 const Value *Src = U.getOperand(0); 981 uint64_t Offset = getOffsetFromIndices(U, *DL); 982 auto &DstRegs = allocateVRegs(U); 983 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U); 984 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src); 985 ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1)); 986 auto InsertedIt = InsertedRegs.begin(); 987 988 for (unsigned i = 0; i < DstRegs.size(); ++i) { 989 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end()) 990 DstRegs[i] = *InsertedIt++; 991 else 992 DstRegs[i] = SrcRegs[i]; 993 } 994 995 return true; 996 } 997 998 bool IRTranslator::translateSelect(const User &U, 999 MachineIRBuilder &MIRBuilder) { 1000 Register Tst = getOrCreateVReg(*U.getOperand(0)); 1001 ArrayRef<Register> ResRegs = getOrCreateVRegs(U); 1002 ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1)); 1003 ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2)); 1004 1005 uint16_t Flags = 0; 1006 if (const SelectInst *SI = dyn_cast<SelectInst>(&U)) 1007 Flags = MachineInstr::copyFlagsFromInstruction(*SI); 1008 1009 for (unsigned i = 0; i < ResRegs.size(); ++i) { 1010 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags); 1011 } 1012 1013 return true; 1014 } 1015 1016 bool IRTranslator::translateCopy(const User &U, const Value &V, 1017 MachineIRBuilder &MIRBuilder) { 1018 Register Src = getOrCreateVReg(V); 1019 auto &Regs = *VMap.getVRegs(U); 1020 if (Regs.empty()) { 1021 Regs.push_back(Src); 1022 VMap.getOffsets(U)->push_back(0); 1023 } else { 1024 // If we already assigned a vreg for this instruction, we can't change that. 1025 // Emit a copy to satisfy the users we already emitted. 1026 MIRBuilder.buildCopy(Regs[0], Src); 1027 } 1028 return true; 1029 } 1030 1031 bool IRTranslator::translateBitCast(const User &U, 1032 MachineIRBuilder &MIRBuilder) { 1033 // If we're bitcasting to the source type, we can reuse the source vreg. 1034 if (getLLTForType(*U.getOperand(0)->getType(), *DL) == 1035 getLLTForType(*U.getType(), *DL)) 1036 return translateCopy(U, *U.getOperand(0), MIRBuilder); 1037 1038 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder); 1039 } 1040 1041 bool IRTranslator::translateCast(unsigned Opcode, const User &U, 1042 MachineIRBuilder &MIRBuilder) { 1043 Register Op = getOrCreateVReg(*U.getOperand(0)); 1044 Register Res = getOrCreateVReg(U); 1045 MIRBuilder.buildInstr(Opcode, {Res}, {Op}); 1046 return true; 1047 } 1048 1049 bool IRTranslator::translateGetElementPtr(const User &U, 1050 MachineIRBuilder &MIRBuilder) { 1051 Value &Op0 = *U.getOperand(0); 1052 Register BaseReg = getOrCreateVReg(Op0); 1053 Type *PtrIRTy = Op0.getType(); 1054 LLT PtrTy = getLLTForType(*PtrIRTy, *DL); 1055 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy); 1056 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 1057 1058 // Normalize Vector GEP - all scalar operands should be converted to the 1059 // splat vector. 1060 unsigned VectorWidth = 0; 1061 if (auto *VT = dyn_cast<VectorType>(U.getType())) 1062 VectorWidth = cast<FixedVectorType>(VT)->getNumElements(); 1063 1064 // We might need to splat the base pointer into a vector if the offsets 1065 // are vectors. 1066 if (VectorWidth && !PtrTy.isVector()) { 1067 BaseReg = 1068 MIRBuilder.buildSplatVector(LLT::vector(VectorWidth, PtrTy), BaseReg) 1069 .getReg(0); 1070 PtrIRTy = FixedVectorType::get(PtrIRTy, VectorWidth); 1071 PtrTy = getLLTForType(*PtrIRTy, *DL); 1072 OffsetIRTy = DL->getIntPtrType(PtrIRTy); 1073 OffsetTy = getLLTForType(*OffsetIRTy, *DL); 1074 } 1075 1076 int64_t Offset = 0; 1077 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U); 1078 GTI != E; ++GTI) { 1079 const Value *Idx = GTI.getOperand(); 1080 if (StructType *StTy = GTI.getStructTypeOrNull()) { 1081 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 1082 Offset += DL->getStructLayout(StTy)->getElementOffset(Field); 1083 continue; 1084 } else { 1085 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 1086 1087 // If this is a scalar constant or a splat vector of constants, 1088 // handle it quickly. 1089 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 1090 Offset += ElementSize * CI->getSExtValue(); 1091 continue; 1092 } 1093 1094 if (Offset != 0) { 1095 auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset); 1096 BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0)) 1097 .getReg(0); 1098 Offset = 0; 1099 } 1100 1101 Register IdxReg = getOrCreateVReg(*Idx); 1102 LLT IdxTy = MRI->getType(IdxReg); 1103 if (IdxTy != OffsetTy) { 1104 if (!IdxTy.isVector() && VectorWidth) { 1105 IdxReg = MIRBuilder.buildSplatVector( 1106 OffsetTy.changeElementType(IdxTy), IdxReg).getReg(0); 1107 } 1108 1109 IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0); 1110 } 1111 1112 // N = N + Idx * ElementSize; 1113 // Avoid doing it for ElementSize of 1. 1114 Register GepOffsetReg; 1115 if (ElementSize != 1) { 1116 auto ElementSizeMIB = MIRBuilder.buildConstant( 1117 getLLTForType(*OffsetIRTy, *DL), ElementSize); 1118 GepOffsetReg = 1119 MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB).getReg(0); 1120 } else 1121 GepOffsetReg = IdxReg; 1122 1123 BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg).getReg(0); 1124 } 1125 } 1126 1127 if (Offset != 0) { 1128 auto OffsetMIB = 1129 MIRBuilder.buildConstant(OffsetTy, Offset); 1130 MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0)); 1131 return true; 1132 } 1133 1134 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg); 1135 return true; 1136 } 1137 1138 bool IRTranslator::translateMemFunc(const CallInst &CI, 1139 MachineIRBuilder &MIRBuilder, 1140 Intrinsic::ID ID) { 1141 1142 // If the source is undef, then just emit a nop. 1143 if (isa<UndefValue>(CI.getArgOperand(1))) 1144 return true; 1145 1146 ArrayRef<Register> Res; 1147 auto ICall = MIRBuilder.buildIntrinsic(ID, Res, true); 1148 for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI) 1149 ICall.addUse(getOrCreateVReg(**AI)); 1150 1151 Align DstAlign; 1152 Align SrcAlign; 1153 unsigned IsVol = 1154 cast<ConstantInt>(CI.getArgOperand(CI.getNumArgOperands() - 1)) 1155 ->getZExtValue(); 1156 1157 if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) { 1158 DstAlign = MCI->getDestAlign().valueOrOne(); 1159 SrcAlign = MCI->getSourceAlign().valueOrOne(); 1160 } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) { 1161 DstAlign = MMI->getDestAlign().valueOrOne(); 1162 SrcAlign = MMI->getSourceAlign().valueOrOne(); 1163 } else { 1164 auto *MSI = cast<MemSetInst>(&CI); 1165 DstAlign = MSI->getDestAlign().valueOrOne(); 1166 } 1167 1168 // We need to propagate the tail call flag from the IR inst as an argument. 1169 // Otherwise, we have to pessimize and assume later that we cannot tail call 1170 // any memory intrinsics. 1171 ICall.addImm(CI.isTailCall() ? 1 : 0); 1172 1173 // Create mem operands to store the alignment and volatile info. 1174 auto VolFlag = IsVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 1175 ICall.addMemOperand(MF->getMachineMemOperand( 1176 MachinePointerInfo(CI.getArgOperand(0)), 1177 MachineMemOperand::MOStore | VolFlag, 1, DstAlign)); 1178 if (ID != Intrinsic::memset) 1179 ICall.addMemOperand(MF->getMachineMemOperand( 1180 MachinePointerInfo(CI.getArgOperand(1)), 1181 MachineMemOperand::MOLoad | VolFlag, 1, SrcAlign)); 1182 1183 return true; 1184 } 1185 1186 void IRTranslator::getStackGuard(Register DstReg, 1187 MachineIRBuilder &MIRBuilder) { 1188 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 1189 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF)); 1190 auto MIB = 1191 MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {}); 1192 1193 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1194 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent()); 1195 if (!Global) 1196 return; 1197 1198 MachinePointerInfo MPInfo(Global); 1199 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 1200 MachineMemOperand::MODereferenceable; 1201 MachineMemOperand *MemRef = 1202 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8, 1203 DL->getPointerABIAlignment(0)); 1204 MIB.setMemRefs({MemRef}); 1205 } 1206 1207 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op, 1208 MachineIRBuilder &MIRBuilder) { 1209 ArrayRef<Register> ResRegs = getOrCreateVRegs(CI); 1210 MIRBuilder.buildInstr( 1211 Op, {ResRegs[0], ResRegs[1]}, 1212 {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))}); 1213 1214 return true; 1215 } 1216 1217 bool IRTranslator::translateFixedPointIntrinsic(unsigned Op, const CallInst &CI, 1218 MachineIRBuilder &MIRBuilder) { 1219 Register Dst = getOrCreateVReg(CI); 1220 Register Src0 = getOrCreateVReg(*CI.getOperand(0)); 1221 Register Src1 = getOrCreateVReg(*CI.getOperand(1)); 1222 uint64_t Scale = cast<ConstantInt>(CI.getOperand(2))->getZExtValue(); 1223 MIRBuilder.buildInstr(Op, {Dst}, { Src0, Src1, Scale }); 1224 return true; 1225 } 1226 1227 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) { 1228 switch (ID) { 1229 default: 1230 break; 1231 case Intrinsic::bswap: 1232 return TargetOpcode::G_BSWAP; 1233 case Intrinsic::bitreverse: 1234 return TargetOpcode::G_BITREVERSE; 1235 case Intrinsic::fshl: 1236 return TargetOpcode::G_FSHL; 1237 case Intrinsic::fshr: 1238 return TargetOpcode::G_FSHR; 1239 case Intrinsic::ceil: 1240 return TargetOpcode::G_FCEIL; 1241 case Intrinsic::cos: 1242 return TargetOpcode::G_FCOS; 1243 case Intrinsic::ctpop: 1244 return TargetOpcode::G_CTPOP; 1245 case Intrinsic::exp: 1246 return TargetOpcode::G_FEXP; 1247 case Intrinsic::exp2: 1248 return TargetOpcode::G_FEXP2; 1249 case Intrinsic::fabs: 1250 return TargetOpcode::G_FABS; 1251 case Intrinsic::copysign: 1252 return TargetOpcode::G_FCOPYSIGN; 1253 case Intrinsic::minnum: 1254 return TargetOpcode::G_FMINNUM; 1255 case Intrinsic::maxnum: 1256 return TargetOpcode::G_FMAXNUM; 1257 case Intrinsic::minimum: 1258 return TargetOpcode::G_FMINIMUM; 1259 case Intrinsic::maximum: 1260 return TargetOpcode::G_FMAXIMUM; 1261 case Intrinsic::canonicalize: 1262 return TargetOpcode::G_FCANONICALIZE; 1263 case Intrinsic::floor: 1264 return TargetOpcode::G_FFLOOR; 1265 case Intrinsic::fma: 1266 return TargetOpcode::G_FMA; 1267 case Intrinsic::log: 1268 return TargetOpcode::G_FLOG; 1269 case Intrinsic::log2: 1270 return TargetOpcode::G_FLOG2; 1271 case Intrinsic::log10: 1272 return TargetOpcode::G_FLOG10; 1273 case Intrinsic::nearbyint: 1274 return TargetOpcode::G_FNEARBYINT; 1275 case Intrinsic::pow: 1276 return TargetOpcode::G_FPOW; 1277 case Intrinsic::powi: 1278 return TargetOpcode::G_FPOWI; 1279 case Intrinsic::rint: 1280 return TargetOpcode::G_FRINT; 1281 case Intrinsic::round: 1282 return TargetOpcode::G_INTRINSIC_ROUND; 1283 case Intrinsic::sin: 1284 return TargetOpcode::G_FSIN; 1285 case Intrinsic::sqrt: 1286 return TargetOpcode::G_FSQRT; 1287 case Intrinsic::trunc: 1288 return TargetOpcode::G_INTRINSIC_TRUNC; 1289 case Intrinsic::readcyclecounter: 1290 return TargetOpcode::G_READCYCLECOUNTER; 1291 case Intrinsic::ptrmask: 1292 return TargetOpcode::G_PTRMASK; 1293 } 1294 return Intrinsic::not_intrinsic; 1295 } 1296 1297 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI, 1298 Intrinsic::ID ID, 1299 MachineIRBuilder &MIRBuilder) { 1300 1301 unsigned Op = getSimpleIntrinsicOpcode(ID); 1302 1303 // Is this a simple intrinsic? 1304 if (Op == Intrinsic::not_intrinsic) 1305 return false; 1306 1307 // Yes. Let's translate it. 1308 SmallVector<llvm::SrcOp, 4> VRegs; 1309 for (auto &Arg : CI.arg_operands()) 1310 VRegs.push_back(getOrCreateVReg(*Arg)); 1311 1312 MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs, 1313 MachineInstr::copyFlagsFromInstruction(CI)); 1314 return true; 1315 } 1316 1317 // TODO: Include ConstainedOps.def when all strict instructions are defined. 1318 static unsigned getConstrainedOpcode(Intrinsic::ID ID) { 1319 switch (ID) { 1320 case Intrinsic::experimental_constrained_fadd: 1321 return TargetOpcode::G_STRICT_FADD; 1322 case Intrinsic::experimental_constrained_fsub: 1323 return TargetOpcode::G_STRICT_FSUB; 1324 case Intrinsic::experimental_constrained_fmul: 1325 return TargetOpcode::G_STRICT_FMUL; 1326 case Intrinsic::experimental_constrained_fdiv: 1327 return TargetOpcode::G_STRICT_FDIV; 1328 case Intrinsic::experimental_constrained_frem: 1329 return TargetOpcode::G_STRICT_FREM; 1330 case Intrinsic::experimental_constrained_fma: 1331 return TargetOpcode::G_STRICT_FMA; 1332 case Intrinsic::experimental_constrained_sqrt: 1333 return TargetOpcode::G_STRICT_FSQRT; 1334 default: 1335 return 0; 1336 } 1337 } 1338 1339 bool IRTranslator::translateConstrainedFPIntrinsic( 1340 const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) { 1341 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 1342 1343 unsigned Opcode = getConstrainedOpcode(FPI.getIntrinsicID()); 1344 if (!Opcode) 1345 return false; 1346 1347 unsigned Flags = MachineInstr::copyFlagsFromInstruction(FPI); 1348 if (EB == fp::ExceptionBehavior::ebIgnore) 1349 Flags |= MachineInstr::NoFPExcept; 1350 1351 SmallVector<llvm::SrcOp, 4> VRegs; 1352 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(0))); 1353 if (!FPI.isUnaryOp()) 1354 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(1))); 1355 if (FPI.isTernaryOp()) 1356 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(2))); 1357 1358 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(FPI)}, VRegs, Flags); 1359 return true; 1360 } 1361 1362 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID, 1363 MachineIRBuilder &MIRBuilder) { 1364 1365 // If this is a simple intrinsic (that is, we just need to add a def of 1366 // a vreg, and uses for each arg operand, then translate it. 1367 if (translateSimpleIntrinsic(CI, ID, MIRBuilder)) 1368 return true; 1369 1370 switch (ID) { 1371 default: 1372 break; 1373 case Intrinsic::lifetime_start: 1374 case Intrinsic::lifetime_end: { 1375 // No stack colouring in O0, discard region information. 1376 if (MF->getTarget().getOptLevel() == CodeGenOpt::None) 1377 return true; 1378 1379 unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START 1380 : TargetOpcode::LIFETIME_END; 1381 1382 // Get the underlying objects for the location passed on the lifetime 1383 // marker. 1384 SmallVector<const Value *, 4> Allocas; 1385 GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL); 1386 1387 // Iterate over each underlying object, creating lifetime markers for each 1388 // static alloca. Quit if we find a non-static alloca. 1389 for (const Value *V : Allocas) { 1390 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 1391 if (!AI) 1392 continue; 1393 1394 if (!AI->isStaticAlloca()) 1395 return true; 1396 1397 MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI)); 1398 } 1399 return true; 1400 } 1401 case Intrinsic::dbg_declare: { 1402 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI); 1403 assert(DI.getVariable() && "Missing variable"); 1404 1405 const Value *Address = DI.getAddress(); 1406 if (!Address || isa<UndefValue>(Address)) { 1407 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 1408 return true; 1409 } 1410 1411 assert(DI.getVariable()->isValidLocationForIntrinsic( 1412 MIRBuilder.getDebugLoc()) && 1413 "Expected inlined-at fields to agree"); 1414 auto AI = dyn_cast<AllocaInst>(Address); 1415 if (AI && AI->isStaticAlloca()) { 1416 // Static allocas are tracked at the MF level, no need for DBG_VALUE 1417 // instructions (in fact, they get ignored if they *do* exist). 1418 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(), 1419 getOrCreateFrameIndex(*AI), DI.getDebugLoc()); 1420 } else { 1421 // A dbg.declare describes the address of a source variable, so lower it 1422 // into an indirect DBG_VALUE. 1423 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address), 1424 DI.getVariable(), DI.getExpression()); 1425 } 1426 return true; 1427 } 1428 case Intrinsic::dbg_label: { 1429 const DbgLabelInst &DI = cast<DbgLabelInst>(CI); 1430 assert(DI.getLabel() && "Missing label"); 1431 1432 assert(DI.getLabel()->isValidLocationForIntrinsic( 1433 MIRBuilder.getDebugLoc()) && 1434 "Expected inlined-at fields to agree"); 1435 1436 MIRBuilder.buildDbgLabel(DI.getLabel()); 1437 return true; 1438 } 1439 case Intrinsic::vaend: 1440 // No target I know of cares about va_end. Certainly no in-tree target 1441 // does. Simplest intrinsic ever! 1442 return true; 1443 case Intrinsic::vastart: { 1444 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1445 Value *Ptr = CI.getArgOperand(0); 1446 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8; 1447 1448 // FIXME: Get alignment 1449 MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)}) 1450 .addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Ptr), 1451 MachineMemOperand::MOStore, 1452 ListSize, Align(1))); 1453 return true; 1454 } 1455 case Intrinsic::dbg_value: { 1456 // This form of DBG_VALUE is target-independent. 1457 const DbgValueInst &DI = cast<DbgValueInst>(CI); 1458 const Value *V = DI.getValue(); 1459 assert(DI.getVariable()->isValidLocationForIntrinsic( 1460 MIRBuilder.getDebugLoc()) && 1461 "Expected inlined-at fields to agree"); 1462 if (!V) { 1463 // Currently the optimizer can produce this; insert an undef to 1464 // help debugging. Probably the optimizer should not do this. 1465 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression()); 1466 } else if (const auto *CI = dyn_cast<Constant>(V)) { 1467 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression()); 1468 } else { 1469 for (Register Reg : getOrCreateVRegs(*V)) { 1470 // FIXME: This does not handle register-indirect values at offset 0. The 1471 // direct/indirect thing shouldn't really be handled by something as 1472 // implicit as reg+noreg vs reg+imm in the first place, but it seems 1473 // pretty baked in right now. 1474 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression()); 1475 } 1476 } 1477 return true; 1478 } 1479 case Intrinsic::uadd_with_overflow: 1480 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder); 1481 case Intrinsic::sadd_with_overflow: 1482 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder); 1483 case Intrinsic::usub_with_overflow: 1484 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder); 1485 case Intrinsic::ssub_with_overflow: 1486 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder); 1487 case Intrinsic::umul_with_overflow: 1488 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder); 1489 case Intrinsic::smul_with_overflow: 1490 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder); 1491 case Intrinsic::uadd_sat: 1492 return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder); 1493 case Intrinsic::sadd_sat: 1494 return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder); 1495 case Intrinsic::usub_sat: 1496 return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder); 1497 case Intrinsic::ssub_sat: 1498 return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder); 1499 case Intrinsic::umin: 1500 return translateBinaryOp(TargetOpcode::G_UMIN, CI, MIRBuilder); 1501 case Intrinsic::umax: 1502 return translateBinaryOp(TargetOpcode::G_UMAX, CI, MIRBuilder); 1503 case Intrinsic::smin: 1504 return translateBinaryOp(TargetOpcode::G_SMIN, CI, MIRBuilder); 1505 case Intrinsic::smax: 1506 return translateBinaryOp(TargetOpcode::G_SMAX, CI, MIRBuilder); 1507 case Intrinsic::smul_fix: 1508 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIX, CI, MIRBuilder); 1509 case Intrinsic::umul_fix: 1510 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIX, CI, MIRBuilder); 1511 case Intrinsic::smul_fix_sat: 1512 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder); 1513 case Intrinsic::umul_fix_sat: 1514 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder); 1515 case Intrinsic::sdiv_fix: 1516 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIX, CI, MIRBuilder); 1517 case Intrinsic::udiv_fix: 1518 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIX, CI, MIRBuilder); 1519 case Intrinsic::sdiv_fix_sat: 1520 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder); 1521 case Intrinsic::udiv_fix_sat: 1522 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder); 1523 case Intrinsic::fmuladd: { 1524 const TargetMachine &TM = MF->getTarget(); 1525 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering(); 1526 Register Dst = getOrCreateVReg(CI); 1527 Register Op0 = getOrCreateVReg(*CI.getArgOperand(0)); 1528 Register Op1 = getOrCreateVReg(*CI.getArgOperand(1)); 1529 Register Op2 = getOrCreateVReg(*CI.getArgOperand(2)); 1530 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 1531 TLI.isFMAFasterThanFMulAndFAdd(*MF, 1532 TLI.getValueType(*DL, CI.getType()))) { 1533 // TODO: Revisit this to see if we should move this part of the 1534 // lowering to the combiner. 1535 MIRBuilder.buildFMA(Dst, Op0, Op1, Op2, 1536 MachineInstr::copyFlagsFromInstruction(CI)); 1537 } else { 1538 LLT Ty = getLLTForType(*CI.getType(), *DL); 1539 auto FMul = MIRBuilder.buildFMul( 1540 Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI)); 1541 MIRBuilder.buildFAdd(Dst, FMul, Op2, 1542 MachineInstr::copyFlagsFromInstruction(CI)); 1543 } 1544 return true; 1545 } 1546 case Intrinsic::convert_from_fp16: 1547 // FIXME: This intrinsic should probably be removed from the IR. 1548 MIRBuilder.buildFPExt(getOrCreateVReg(CI), 1549 getOrCreateVReg(*CI.getArgOperand(0)), 1550 MachineInstr::copyFlagsFromInstruction(CI)); 1551 return true; 1552 case Intrinsic::convert_to_fp16: 1553 // FIXME: This intrinsic should probably be removed from the IR. 1554 MIRBuilder.buildFPTrunc(getOrCreateVReg(CI), 1555 getOrCreateVReg(*CI.getArgOperand(0)), 1556 MachineInstr::copyFlagsFromInstruction(CI)); 1557 return true; 1558 case Intrinsic::memcpy: 1559 case Intrinsic::memmove: 1560 case Intrinsic::memset: 1561 return translateMemFunc(CI, MIRBuilder, ID); 1562 case Intrinsic::eh_typeid_for: { 1563 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0)); 1564 Register Reg = getOrCreateVReg(CI); 1565 unsigned TypeID = MF->getTypeIDFor(GV); 1566 MIRBuilder.buildConstant(Reg, TypeID); 1567 return true; 1568 } 1569 case Intrinsic::objectsize: 1570 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 1571 1572 case Intrinsic::is_constant: 1573 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 1574 1575 case Intrinsic::stackguard: 1576 getStackGuard(getOrCreateVReg(CI), MIRBuilder); 1577 return true; 1578 case Intrinsic::stackprotector: { 1579 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 1580 Register GuardVal = MRI->createGenericVirtualRegister(PtrTy); 1581 getStackGuard(GuardVal, MIRBuilder); 1582 1583 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1)); 1584 int FI = getOrCreateFrameIndex(*Slot); 1585 MF->getFrameInfo().setStackProtectorIndex(FI); 1586 1587 MIRBuilder.buildStore( 1588 GuardVal, getOrCreateVReg(*Slot), 1589 *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 1590 MachineMemOperand::MOStore | 1591 MachineMemOperand::MOVolatile, 1592 PtrTy.getSizeInBits() / 8, Align(8))); 1593 return true; 1594 } 1595 case Intrinsic::stacksave: { 1596 // Save the stack pointer to the location provided by the intrinsic. 1597 Register Reg = getOrCreateVReg(CI); 1598 Register StackPtr = MF->getSubtarget() 1599 .getTargetLowering() 1600 ->getStackPointerRegisterToSaveRestore(); 1601 1602 // If the target doesn't specify a stack pointer, then fall back. 1603 if (!StackPtr) 1604 return false; 1605 1606 MIRBuilder.buildCopy(Reg, StackPtr); 1607 return true; 1608 } 1609 case Intrinsic::stackrestore: { 1610 // Restore the stack pointer from the location provided by the intrinsic. 1611 Register Reg = getOrCreateVReg(*CI.getArgOperand(0)); 1612 Register StackPtr = MF->getSubtarget() 1613 .getTargetLowering() 1614 ->getStackPointerRegisterToSaveRestore(); 1615 1616 // If the target doesn't specify a stack pointer, then fall back. 1617 if (!StackPtr) 1618 return false; 1619 1620 MIRBuilder.buildCopy(StackPtr, Reg); 1621 return true; 1622 } 1623 case Intrinsic::cttz: 1624 case Intrinsic::ctlz: { 1625 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1)); 1626 bool isTrailing = ID == Intrinsic::cttz; 1627 unsigned Opcode = isTrailing 1628 ? Cst->isZero() ? TargetOpcode::G_CTTZ 1629 : TargetOpcode::G_CTTZ_ZERO_UNDEF 1630 : Cst->isZero() ? TargetOpcode::G_CTLZ 1631 : TargetOpcode::G_CTLZ_ZERO_UNDEF; 1632 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)}, 1633 {getOrCreateVReg(*CI.getArgOperand(0))}); 1634 return true; 1635 } 1636 case Intrinsic::invariant_start: { 1637 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 1638 Register Undef = MRI->createGenericVirtualRegister(PtrTy); 1639 MIRBuilder.buildUndef(Undef); 1640 return true; 1641 } 1642 case Intrinsic::invariant_end: 1643 return true; 1644 case Intrinsic::assume: 1645 case Intrinsic::var_annotation: 1646 case Intrinsic::sideeffect: 1647 // Discard annotate attributes, assumptions, and artificial side-effects. 1648 return true; 1649 case Intrinsic::read_volatile_register: 1650 case Intrinsic::read_register: { 1651 Value *Arg = CI.getArgOperand(0); 1652 MIRBuilder 1653 .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {}) 1654 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata())); 1655 return true; 1656 } 1657 case Intrinsic::write_register: { 1658 Value *Arg = CI.getArgOperand(0); 1659 MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER) 1660 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata())) 1661 .addUse(getOrCreateVReg(*CI.getArgOperand(1))); 1662 return true; 1663 } 1664 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 1665 case Intrinsic::INTRINSIC: 1666 #include "llvm/IR/ConstrainedOps.def" 1667 return translateConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(CI), 1668 MIRBuilder); 1669 1670 } 1671 return false; 1672 } 1673 1674 bool IRTranslator::translateInlineAsm(const CallBase &CB, 1675 MachineIRBuilder &MIRBuilder) { 1676 1677 const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering(); 1678 1679 if (!ALI) { 1680 LLVM_DEBUG( 1681 dbgs() << "Inline asm lowering is not supported for this target yet\n"); 1682 return false; 1683 } 1684 1685 return ALI->lowerInlineAsm( 1686 MIRBuilder, CB, [&](const Value &Val) { return getOrCreateVRegs(Val); }); 1687 } 1688 1689 bool IRTranslator::translateCallBase(const CallBase &CB, 1690 MachineIRBuilder &MIRBuilder) { 1691 ArrayRef<Register> Res = getOrCreateVRegs(CB); 1692 1693 SmallVector<ArrayRef<Register>, 8> Args; 1694 Register SwiftInVReg = 0; 1695 Register SwiftErrorVReg = 0; 1696 for (auto &Arg : CB.args()) { 1697 if (CLI->supportSwiftError() && isSwiftError(Arg)) { 1698 assert(SwiftInVReg == 0 && "Expected only one swift error argument"); 1699 LLT Ty = getLLTForType(*Arg->getType(), *DL); 1700 SwiftInVReg = MRI->createGenericVirtualRegister(Ty); 1701 MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt( 1702 &CB, &MIRBuilder.getMBB(), Arg)); 1703 Args.emplace_back(makeArrayRef(SwiftInVReg)); 1704 SwiftErrorVReg = 1705 SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg); 1706 continue; 1707 } 1708 Args.push_back(getOrCreateVRegs(*Arg)); 1709 } 1710 1711 // We don't set HasCalls on MFI here yet because call lowering may decide to 1712 // optimize into tail calls. Instead, we defer that to selection where a final 1713 // scan is done to check if any instructions are calls. 1714 bool Success = 1715 CLI->lowerCall(MIRBuilder, CB, Res, Args, SwiftErrorVReg, 1716 [&]() { return getOrCreateVReg(*CB.getCalledOperand()); }); 1717 1718 // Check if we just inserted a tail call. 1719 if (Success) { 1720 assert(!HasTailCall && "Can't tail call return twice from block?"); 1721 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1722 HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt())); 1723 } 1724 1725 return Success; 1726 } 1727 1728 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) { 1729 const CallInst &CI = cast<CallInst>(U); 1730 auto TII = MF->getTarget().getIntrinsicInfo(); 1731 const Function *F = CI.getCalledFunction(); 1732 1733 // FIXME: support Windows dllimport function calls. 1734 if (F && (F->hasDLLImportStorageClass() || 1735 (MF->getTarget().getTargetTriple().isOSWindows() && 1736 F->hasExternalWeakLinkage()))) 1737 return false; 1738 1739 // FIXME: support control flow guard targets. 1740 if (CI.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget)) 1741 return false; 1742 1743 if (CI.isInlineAsm()) 1744 return translateInlineAsm(CI, MIRBuilder); 1745 1746 Intrinsic::ID ID = Intrinsic::not_intrinsic; 1747 if (F && F->isIntrinsic()) { 1748 ID = F->getIntrinsicID(); 1749 if (TII && ID == Intrinsic::not_intrinsic) 1750 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F)); 1751 } 1752 1753 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) 1754 return translateCallBase(CI, MIRBuilder); 1755 1756 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic"); 1757 1758 if (translateKnownIntrinsic(CI, ID, MIRBuilder)) 1759 return true; 1760 1761 ArrayRef<Register> ResultRegs; 1762 if (!CI.getType()->isVoidTy()) 1763 ResultRegs = getOrCreateVRegs(CI); 1764 1765 // Ignore the callsite attributes. Backend code is most likely not expecting 1766 // an intrinsic to sometimes have side effects and sometimes not. 1767 MachineInstrBuilder MIB = 1768 MIRBuilder.buildIntrinsic(ID, ResultRegs, !F->doesNotAccessMemory()); 1769 if (isa<FPMathOperator>(CI)) 1770 MIB->copyIRFlags(CI); 1771 1772 for (auto &Arg : enumerate(CI.arg_operands())) { 1773 // If this is required to be an immediate, don't materialize it in a 1774 // register. 1775 if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) { 1776 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) { 1777 // imm arguments are more convenient than cimm (and realistically 1778 // probably sufficient), so use them. 1779 assert(CI->getBitWidth() <= 64 && 1780 "large intrinsic immediates not handled"); 1781 MIB.addImm(CI->getSExtValue()); 1782 } else { 1783 MIB.addFPImm(cast<ConstantFP>(Arg.value())); 1784 } 1785 } else if (auto MD = dyn_cast<MetadataAsValue>(Arg.value())) { 1786 auto *MDN = dyn_cast<MDNode>(MD->getMetadata()); 1787 if (!MDN) // This was probably an MDString. 1788 return false; 1789 MIB.addMetadata(MDN); 1790 } else { 1791 ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value()); 1792 if (VRegs.size() > 1) 1793 return false; 1794 MIB.addUse(VRegs[0]); 1795 } 1796 } 1797 1798 // Add a MachineMemOperand if it is a target mem intrinsic. 1799 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering(); 1800 TargetLowering::IntrinsicInfo Info; 1801 // TODO: Add a GlobalISel version of getTgtMemIntrinsic. 1802 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) { 1803 Align Alignment = Info.align.getValueOr( 1804 DL->getABITypeAlign(Info.memVT.getTypeForEVT(F->getContext()))); 1805 1806 uint64_t Size = Info.memVT.getStoreSize(); 1807 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal), 1808 Info.flags, Size, Alignment)); 1809 } 1810 1811 return true; 1812 } 1813 1814 bool IRTranslator::translateInvoke(const User &U, 1815 MachineIRBuilder &MIRBuilder) { 1816 const InvokeInst &I = cast<InvokeInst>(U); 1817 MCContext &Context = MF->getContext(); 1818 1819 const BasicBlock *ReturnBB = I.getSuccessor(0); 1820 const BasicBlock *EHPadBB = I.getSuccessor(1); 1821 1822 const Function *Fn = I.getCalledFunction(); 1823 if (I.isInlineAsm()) 1824 return false; 1825 1826 // FIXME: support invoking patchpoint and statepoint intrinsics. 1827 if (Fn && Fn->isIntrinsic()) 1828 return false; 1829 1830 // FIXME: support whatever these are. 1831 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 1832 return false; 1833 1834 // FIXME: support control flow guard targets. 1835 if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget)) 1836 return false; 1837 1838 // FIXME: support Windows exception handling. 1839 if (!isa<LandingPadInst>(EHPadBB->front())) 1840 return false; 1841 1842 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about 1843 // the region covered by the try. 1844 MCSymbol *BeginSymbol = Context.createTempSymbol(); 1845 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol); 1846 1847 if (!translateCallBase(I, MIRBuilder)) 1848 return false; 1849 1850 MCSymbol *EndSymbol = Context.createTempSymbol(); 1851 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol); 1852 1853 // FIXME: track probabilities. 1854 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB), 1855 &ReturnMBB = getMBB(*ReturnBB); 1856 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol); 1857 MIRBuilder.getMBB().addSuccessor(&ReturnMBB); 1858 MIRBuilder.getMBB().addSuccessor(&EHPadMBB); 1859 MIRBuilder.buildBr(ReturnMBB); 1860 1861 return true; 1862 } 1863 1864 bool IRTranslator::translateCallBr(const User &U, 1865 MachineIRBuilder &MIRBuilder) { 1866 // FIXME: Implement this. 1867 return false; 1868 } 1869 1870 bool IRTranslator::translateLandingPad(const User &U, 1871 MachineIRBuilder &MIRBuilder) { 1872 const LandingPadInst &LP = cast<LandingPadInst>(U); 1873 1874 MachineBasicBlock &MBB = MIRBuilder.getMBB(); 1875 1876 MBB.setIsEHPad(); 1877 1878 // If there aren't registers to copy the values into (e.g., during SjLj 1879 // exceptions), then don't bother. 1880 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1881 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn(); 1882 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 1883 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 1884 return true; 1885 1886 // If landingpad's return type is token type, we don't create DAG nodes 1887 // for its exception pointer and selector value. The extraction of exception 1888 // pointer or selector value from token type landingpads is not currently 1889 // supported. 1890 if (LP.getType()->isTokenTy()) 1891 return true; 1892 1893 // Add a label to mark the beginning of the landing pad. Deletion of the 1894 // landing pad can thus be detected via the MachineModuleInfo. 1895 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL) 1896 .addSym(MF->addLandingPad(&MBB)); 1897 1898 LLT Ty = getLLTForType(*LP.getType(), *DL); 1899 Register Undef = MRI->createGenericVirtualRegister(Ty); 1900 MIRBuilder.buildUndef(Undef); 1901 1902 SmallVector<LLT, 2> Tys; 1903 for (Type *Ty : cast<StructType>(LP.getType())->elements()) 1904 Tys.push_back(getLLTForType(*Ty, *DL)); 1905 assert(Tys.size() == 2 && "Only two-valued landingpads are supported"); 1906 1907 // Mark exception register as live in. 1908 Register ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn); 1909 if (!ExceptionReg) 1910 return false; 1911 1912 MBB.addLiveIn(ExceptionReg); 1913 ArrayRef<Register> ResRegs = getOrCreateVRegs(LP); 1914 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg); 1915 1916 Register SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn); 1917 if (!SelectorReg) 1918 return false; 1919 1920 MBB.addLiveIn(SelectorReg); 1921 Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]); 1922 MIRBuilder.buildCopy(PtrVReg, SelectorReg); 1923 MIRBuilder.buildCast(ResRegs[1], PtrVReg); 1924 1925 return true; 1926 } 1927 1928 bool IRTranslator::translateAlloca(const User &U, 1929 MachineIRBuilder &MIRBuilder) { 1930 auto &AI = cast<AllocaInst>(U); 1931 1932 if (AI.isSwiftError()) 1933 return true; 1934 1935 if (AI.isStaticAlloca()) { 1936 Register Res = getOrCreateVReg(AI); 1937 int FI = getOrCreateFrameIndex(AI); 1938 MIRBuilder.buildFrameIndex(Res, FI); 1939 return true; 1940 } 1941 1942 // FIXME: support stack probing for Windows. 1943 if (MF->getTarget().getTargetTriple().isOSWindows()) 1944 return false; 1945 1946 // Now we're in the harder dynamic case. 1947 Register NumElts = getOrCreateVReg(*AI.getArraySize()); 1948 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType()); 1949 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL); 1950 if (MRI->getType(NumElts) != IntPtrTy) { 1951 Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy); 1952 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts); 1953 NumElts = ExtElts; 1954 } 1955 1956 Type *Ty = AI.getAllocatedType(); 1957 1958 Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy); 1959 Register TySize = 1960 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty))); 1961 MIRBuilder.buildMul(AllocSize, NumElts, TySize); 1962 1963 // Round the size of the allocation up to the stack alignment size 1964 // by add SA-1 to the size. This doesn't overflow because we're computing 1965 // an address inside an alloca. 1966 Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign(); 1967 auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign.value() - 1); 1968 auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne, 1969 MachineInstr::NoUWrap); 1970 auto AlignCst = 1971 MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign.value() - 1)); 1972 auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst); 1973 1974 Align Alignment = std::max(AI.getAlign(), DL->getPrefTypeAlign(Ty)); 1975 if (Alignment <= StackAlign) 1976 Alignment = Align(1); 1977 MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Alignment); 1978 1979 MF->getFrameInfo().CreateVariableSizedObject(Alignment, &AI); 1980 assert(MF->getFrameInfo().hasVarSizedObjects()); 1981 return true; 1982 } 1983 1984 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) { 1985 // FIXME: We may need more info about the type. Because of how LLT works, 1986 // we're completely discarding the i64/double distinction here (amongst 1987 // others). Fortunately the ABIs I know of where that matters don't use va_arg 1988 // anyway but that's not guaranteed. 1989 MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)}, 1990 {getOrCreateVReg(*U.getOperand(0)), 1991 DL->getABITypeAlign(U.getType()).value()}); 1992 return true; 1993 } 1994 1995 bool IRTranslator::translateInsertElement(const User &U, 1996 MachineIRBuilder &MIRBuilder) { 1997 // If it is a <1 x Ty> vector, use the scalar as it is 1998 // not a legal vector type in LLT. 1999 if (cast<FixedVectorType>(U.getType())->getNumElements() == 1) 2000 return translateCopy(U, *U.getOperand(1), MIRBuilder); 2001 2002 Register Res = getOrCreateVReg(U); 2003 Register Val = getOrCreateVReg(*U.getOperand(0)); 2004 Register Elt = getOrCreateVReg(*U.getOperand(1)); 2005 Register Idx = getOrCreateVReg(*U.getOperand(2)); 2006 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx); 2007 return true; 2008 } 2009 2010 bool IRTranslator::translateExtractElement(const User &U, 2011 MachineIRBuilder &MIRBuilder) { 2012 // If it is a <1 x Ty> vector, use the scalar as it is 2013 // not a legal vector type in LLT. 2014 if (cast<FixedVectorType>(U.getOperand(0)->getType())->getNumElements() == 1) 2015 return translateCopy(U, *U.getOperand(0), MIRBuilder); 2016 2017 Register Res = getOrCreateVReg(U); 2018 Register Val = getOrCreateVReg(*U.getOperand(0)); 2019 const auto &TLI = *MF->getSubtarget().getTargetLowering(); 2020 unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits(); 2021 Register Idx; 2022 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) { 2023 if (CI->getBitWidth() != PreferredVecIdxWidth) { 2024 APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth); 2025 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx); 2026 Idx = getOrCreateVReg(*NewIdxCI); 2027 } 2028 } 2029 if (!Idx) 2030 Idx = getOrCreateVReg(*U.getOperand(1)); 2031 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) { 2032 const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth); 2033 Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx).getReg(0); 2034 } 2035 MIRBuilder.buildExtractVectorElement(Res, Val, Idx); 2036 return true; 2037 } 2038 2039 bool IRTranslator::translateShuffleVector(const User &U, 2040 MachineIRBuilder &MIRBuilder) { 2041 ArrayRef<int> Mask; 2042 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&U)) 2043 Mask = SVI->getShuffleMask(); 2044 else 2045 Mask = cast<ConstantExpr>(U).getShuffleMask(); 2046 ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask); 2047 MIRBuilder 2048 .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)}, 2049 {getOrCreateVReg(*U.getOperand(0)), 2050 getOrCreateVReg(*U.getOperand(1))}) 2051 .addShuffleMask(MaskAlloc); 2052 return true; 2053 } 2054 2055 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) { 2056 const PHINode &PI = cast<PHINode>(U); 2057 2058 SmallVector<MachineInstr *, 4> Insts; 2059 for (auto Reg : getOrCreateVRegs(PI)) { 2060 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {}); 2061 Insts.push_back(MIB.getInstr()); 2062 } 2063 2064 PendingPHIs.emplace_back(&PI, std::move(Insts)); 2065 return true; 2066 } 2067 2068 bool IRTranslator::translateAtomicCmpXchg(const User &U, 2069 MachineIRBuilder &MIRBuilder) { 2070 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U); 2071 2072 auto &TLI = *MF->getSubtarget().getTargetLowering(); 2073 auto Flags = TLI.getAtomicMemOperandFlags(I, *DL); 2074 2075 Type *ResType = I.getType(); 2076 Type *ValType = ResType->Type::getStructElementType(0); 2077 2078 auto Res = getOrCreateVRegs(I); 2079 Register OldValRes = Res[0]; 2080 Register SuccessRes = Res[1]; 2081 Register Addr = getOrCreateVReg(*I.getPointerOperand()); 2082 Register Cmp = getOrCreateVReg(*I.getCompareOperand()); 2083 Register NewVal = getOrCreateVReg(*I.getNewValOperand()); 2084 2085 AAMDNodes AAMetadata; 2086 I.getAAMetadata(AAMetadata); 2087 2088 MIRBuilder.buildAtomicCmpXchgWithSuccess( 2089 OldValRes, SuccessRes, Addr, Cmp, NewVal, 2090 *MF->getMachineMemOperand( 2091 MachinePointerInfo(I.getPointerOperand()), Flags, 2092 DL->getTypeStoreSize(ValType), getMemOpAlign(I), AAMetadata, nullptr, 2093 I.getSyncScopeID(), I.getSuccessOrdering(), I.getFailureOrdering())); 2094 return true; 2095 } 2096 2097 bool IRTranslator::translateAtomicRMW(const User &U, 2098 MachineIRBuilder &MIRBuilder) { 2099 const AtomicRMWInst &I = cast<AtomicRMWInst>(U); 2100 auto &TLI = *MF->getSubtarget().getTargetLowering(); 2101 auto Flags = TLI.getAtomicMemOperandFlags(I, *DL); 2102 2103 Type *ResType = I.getType(); 2104 2105 Register Res = getOrCreateVReg(I); 2106 Register Addr = getOrCreateVReg(*I.getPointerOperand()); 2107 Register Val = getOrCreateVReg(*I.getValOperand()); 2108 2109 unsigned Opcode = 0; 2110 switch (I.getOperation()) { 2111 default: 2112 return false; 2113 case AtomicRMWInst::Xchg: 2114 Opcode = TargetOpcode::G_ATOMICRMW_XCHG; 2115 break; 2116 case AtomicRMWInst::Add: 2117 Opcode = TargetOpcode::G_ATOMICRMW_ADD; 2118 break; 2119 case AtomicRMWInst::Sub: 2120 Opcode = TargetOpcode::G_ATOMICRMW_SUB; 2121 break; 2122 case AtomicRMWInst::And: 2123 Opcode = TargetOpcode::G_ATOMICRMW_AND; 2124 break; 2125 case AtomicRMWInst::Nand: 2126 Opcode = TargetOpcode::G_ATOMICRMW_NAND; 2127 break; 2128 case AtomicRMWInst::Or: 2129 Opcode = TargetOpcode::G_ATOMICRMW_OR; 2130 break; 2131 case AtomicRMWInst::Xor: 2132 Opcode = TargetOpcode::G_ATOMICRMW_XOR; 2133 break; 2134 case AtomicRMWInst::Max: 2135 Opcode = TargetOpcode::G_ATOMICRMW_MAX; 2136 break; 2137 case AtomicRMWInst::Min: 2138 Opcode = TargetOpcode::G_ATOMICRMW_MIN; 2139 break; 2140 case AtomicRMWInst::UMax: 2141 Opcode = TargetOpcode::G_ATOMICRMW_UMAX; 2142 break; 2143 case AtomicRMWInst::UMin: 2144 Opcode = TargetOpcode::G_ATOMICRMW_UMIN; 2145 break; 2146 case AtomicRMWInst::FAdd: 2147 Opcode = TargetOpcode::G_ATOMICRMW_FADD; 2148 break; 2149 case AtomicRMWInst::FSub: 2150 Opcode = TargetOpcode::G_ATOMICRMW_FSUB; 2151 break; 2152 } 2153 2154 AAMDNodes AAMetadata; 2155 I.getAAMetadata(AAMetadata); 2156 2157 MIRBuilder.buildAtomicRMW( 2158 Opcode, Res, Addr, Val, 2159 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 2160 Flags, DL->getTypeStoreSize(ResType), 2161 getMemOpAlign(I), AAMetadata, nullptr, 2162 I.getSyncScopeID(), I.getOrdering())); 2163 return true; 2164 } 2165 2166 bool IRTranslator::translateFence(const User &U, 2167 MachineIRBuilder &MIRBuilder) { 2168 const FenceInst &Fence = cast<FenceInst>(U); 2169 MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()), 2170 Fence.getSyncScopeID()); 2171 return true; 2172 } 2173 2174 bool IRTranslator::translateFreeze(const User &U, 2175 MachineIRBuilder &MIRBuilder) { 2176 const ArrayRef<Register> DstRegs = getOrCreateVRegs(U); 2177 const ArrayRef<Register> SrcRegs = getOrCreateVRegs(*U.getOperand(0)); 2178 2179 assert(DstRegs.size() == SrcRegs.size() && 2180 "Freeze with different source and destination type?"); 2181 2182 for (unsigned I = 0; I < DstRegs.size(); ++I) { 2183 MIRBuilder.buildFreeze(DstRegs[I], SrcRegs[I]); 2184 } 2185 2186 return true; 2187 } 2188 2189 void IRTranslator::finishPendingPhis() { 2190 #ifndef NDEBUG 2191 DILocationVerifier Verifier; 2192 GISelObserverWrapper WrapperObserver(&Verifier); 2193 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver); 2194 #endif // ifndef NDEBUG 2195 for (auto &Phi : PendingPHIs) { 2196 const PHINode *PI = Phi.first; 2197 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second; 2198 MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent(); 2199 EntryBuilder->setDebugLoc(PI->getDebugLoc()); 2200 #ifndef NDEBUG 2201 Verifier.setCurrentInst(PI); 2202 #endif // ifndef NDEBUG 2203 2204 SmallSet<const MachineBasicBlock *, 16> SeenPreds; 2205 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) { 2206 auto IRPred = PI->getIncomingBlock(i); 2207 ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i)); 2208 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) { 2209 if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred)) 2210 continue; 2211 SeenPreds.insert(Pred); 2212 for (unsigned j = 0; j < ValRegs.size(); ++j) { 2213 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]); 2214 MIB.addUse(ValRegs[j]); 2215 MIB.addMBB(Pred); 2216 } 2217 } 2218 } 2219 } 2220 } 2221 2222 bool IRTranslator::valueIsSplit(const Value &V, 2223 SmallVectorImpl<uint64_t> *Offsets) { 2224 SmallVector<LLT, 4> SplitTys; 2225 if (Offsets && !Offsets->empty()) 2226 Offsets->clear(); 2227 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets); 2228 return SplitTys.size() > 1; 2229 } 2230 2231 bool IRTranslator::translate(const Instruction &Inst) { 2232 CurBuilder->setDebugLoc(Inst.getDebugLoc()); 2233 // We only emit constants into the entry block from here. To prevent jumpy 2234 // debug behaviour set the line to 0. 2235 if (const DebugLoc &DL = Inst.getDebugLoc()) 2236 EntryBuilder->setDebugLoc( 2237 DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt())); 2238 else 2239 EntryBuilder->setDebugLoc(DebugLoc()); 2240 2241 auto &TLI = *MF->getSubtarget().getTargetLowering(); 2242 if (TLI.fallBackToDAGISel(Inst)) 2243 return false; 2244 2245 switch (Inst.getOpcode()) { 2246 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 2247 case Instruction::OPCODE: \ 2248 return translate##OPCODE(Inst, *CurBuilder.get()); 2249 #include "llvm/IR/Instruction.def" 2250 default: 2251 return false; 2252 } 2253 } 2254 2255 bool IRTranslator::translate(const Constant &C, Register Reg) { 2256 if (auto CI = dyn_cast<ConstantInt>(&C)) 2257 EntryBuilder->buildConstant(Reg, *CI); 2258 else if (auto CF = dyn_cast<ConstantFP>(&C)) 2259 EntryBuilder->buildFConstant(Reg, *CF); 2260 else if (isa<UndefValue>(C)) 2261 EntryBuilder->buildUndef(Reg); 2262 else if (isa<ConstantPointerNull>(C)) 2263 EntryBuilder->buildConstant(Reg, 0); 2264 else if (auto GV = dyn_cast<GlobalValue>(&C)) 2265 EntryBuilder->buildGlobalValue(Reg, GV); 2266 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) { 2267 if (!CAZ->getType()->isVectorTy()) 2268 return false; 2269 // Return the scalar if it is a <1 x Ty> vector. 2270 if (CAZ->getNumElements() == 1) 2271 return translateCopy(C, *CAZ->getElementValue(0u), *EntryBuilder.get()); 2272 SmallVector<Register, 4> Ops; 2273 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) { 2274 Constant &Elt = *CAZ->getElementValue(i); 2275 Ops.push_back(getOrCreateVReg(Elt)); 2276 } 2277 EntryBuilder->buildBuildVector(Reg, Ops); 2278 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) { 2279 // Return the scalar if it is a <1 x Ty> vector. 2280 if (CV->getNumElements() == 1) 2281 return translateCopy(C, *CV->getElementAsConstant(0), 2282 *EntryBuilder.get()); 2283 SmallVector<Register, 4> Ops; 2284 for (unsigned i = 0; i < CV->getNumElements(); ++i) { 2285 Constant &Elt = *CV->getElementAsConstant(i); 2286 Ops.push_back(getOrCreateVReg(Elt)); 2287 } 2288 EntryBuilder->buildBuildVector(Reg, Ops); 2289 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) { 2290 switch(CE->getOpcode()) { 2291 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 2292 case Instruction::OPCODE: \ 2293 return translate##OPCODE(*CE, *EntryBuilder.get()); 2294 #include "llvm/IR/Instruction.def" 2295 default: 2296 return false; 2297 } 2298 } else if (auto CV = dyn_cast<ConstantVector>(&C)) { 2299 if (CV->getNumOperands() == 1) 2300 return translateCopy(C, *CV->getOperand(0), *EntryBuilder.get()); 2301 SmallVector<Register, 4> Ops; 2302 for (unsigned i = 0; i < CV->getNumOperands(); ++i) { 2303 Ops.push_back(getOrCreateVReg(*CV->getOperand(i))); 2304 } 2305 EntryBuilder->buildBuildVector(Reg, Ops); 2306 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) { 2307 EntryBuilder->buildBlockAddress(Reg, BA); 2308 } else 2309 return false; 2310 2311 return true; 2312 } 2313 2314 void IRTranslator::finalizeBasicBlock() { 2315 for (auto &JTCase : SL->JTCases) { 2316 // Emit header first, if it wasn't already emitted. 2317 if (!JTCase.first.Emitted) 2318 emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB); 2319 2320 emitJumpTable(JTCase.second, JTCase.second.MBB); 2321 } 2322 SL->JTCases.clear(); 2323 } 2324 2325 void IRTranslator::finalizeFunction() { 2326 // Release the memory used by the different maps we 2327 // needed during the translation. 2328 PendingPHIs.clear(); 2329 VMap.reset(); 2330 FrameIndices.clear(); 2331 MachinePreds.clear(); 2332 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it 2333 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid 2334 // destroying it twice (in ~IRTranslator() and ~LLVMContext()) 2335 EntryBuilder.reset(); 2336 CurBuilder.reset(); 2337 FuncInfo.clear(); 2338 } 2339 2340 /// Returns true if a BasicBlock \p BB within a variadic function contains a 2341 /// variadic musttail call. 2342 static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) { 2343 if (!IsVarArg) 2344 return false; 2345 2346 // Walk the block backwards, because tail calls usually only appear at the end 2347 // of a block. 2348 return std::any_of(BB.rbegin(), BB.rend(), [](const Instruction &I) { 2349 const auto *CI = dyn_cast<CallInst>(&I); 2350 return CI && CI->isMustTailCall(); 2351 }); 2352 } 2353 2354 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) { 2355 MF = &CurMF; 2356 const Function &F = MF->getFunction(); 2357 if (F.empty()) 2358 return false; 2359 GISelCSEAnalysisWrapper &Wrapper = 2360 getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper(); 2361 // Set the CSEConfig and run the analysis. 2362 GISelCSEInfo *CSEInfo = nullptr; 2363 TPC = &getAnalysis<TargetPassConfig>(); 2364 bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences() 2365 ? EnableCSEInIRTranslator 2366 : TPC->isGISelCSEEnabled(); 2367 2368 if (EnableCSE) { 2369 EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF); 2370 CSEInfo = &Wrapper.get(TPC->getCSEConfig()); 2371 EntryBuilder->setCSEInfo(CSEInfo); 2372 CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF); 2373 CurBuilder->setCSEInfo(CSEInfo); 2374 } else { 2375 EntryBuilder = std::make_unique<MachineIRBuilder>(); 2376 CurBuilder = std::make_unique<MachineIRBuilder>(); 2377 } 2378 CLI = MF->getSubtarget().getCallLowering(); 2379 CurBuilder->setMF(*MF); 2380 EntryBuilder->setMF(*MF); 2381 MRI = &MF->getRegInfo(); 2382 DL = &F.getParent()->getDataLayout(); 2383 ORE = std::make_unique<OptimizationRemarkEmitter>(&F); 2384 FuncInfo.MF = MF; 2385 FuncInfo.BPI = nullptr; 2386 const auto &TLI = *MF->getSubtarget().getTargetLowering(); 2387 const TargetMachine &TM = MF->getTarget(); 2388 SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo); 2389 SL->init(TLI, TM, *DL); 2390 2391 EnableOpts = TM.getOptLevel() != CodeGenOpt::None && !skipFunction(F); 2392 2393 assert(PendingPHIs.empty() && "stale PHIs"); 2394 2395 if (!DL->isLittleEndian()) { 2396 // Currently we don't properly handle big endian code. 2397 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 2398 F.getSubprogram(), &F.getEntryBlock()); 2399 R << "unable to translate in big endian mode"; 2400 reportTranslationError(*MF, *TPC, *ORE, R); 2401 } 2402 2403 // Release the per-function state when we return, whether we succeeded or not. 2404 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); }); 2405 2406 // Setup a separate basic-block for the arguments and constants 2407 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock(); 2408 MF->push_back(EntryBB); 2409 EntryBuilder->setMBB(*EntryBB); 2410 2411 DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc(); 2412 SwiftError.setFunction(CurMF); 2413 SwiftError.createEntriesInEntryBlock(DbgLoc); 2414 2415 bool IsVarArg = F.isVarArg(); 2416 bool HasMustTailInVarArgFn = false; 2417 2418 // Create all blocks, in IR order, to preserve the layout. 2419 for (const BasicBlock &BB: F) { 2420 auto *&MBB = BBToMBB[&BB]; 2421 2422 MBB = MF->CreateMachineBasicBlock(&BB); 2423 MF->push_back(MBB); 2424 2425 if (BB.hasAddressTaken()) 2426 MBB->setHasAddressTaken(); 2427 2428 if (!HasMustTailInVarArgFn) 2429 HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB); 2430 } 2431 2432 MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn); 2433 2434 // Make our arguments/constants entry block fallthrough to the IR entry block. 2435 EntryBB->addSuccessor(&getMBB(F.front())); 2436 2437 if (CLI->fallBackToDAGISel(F)) { 2438 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 2439 F.getSubprogram(), &F.getEntryBlock()); 2440 R << "unable to lower function: " << ore::NV("Prototype", F.getType()); 2441 reportTranslationError(*MF, *TPC, *ORE, R); 2442 return false; 2443 } 2444 2445 // Lower the actual args into this basic block. 2446 SmallVector<ArrayRef<Register>, 8> VRegArgs; 2447 for (const Argument &Arg: F.args()) { 2448 if (DL->getTypeStoreSize(Arg.getType()).isZero()) 2449 continue; // Don't handle zero sized types. 2450 ArrayRef<Register> VRegs = getOrCreateVRegs(Arg); 2451 VRegArgs.push_back(VRegs); 2452 2453 if (Arg.hasSwiftErrorAttr()) { 2454 assert(VRegs.size() == 1 && "Too many vregs for Swift error"); 2455 SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]); 2456 } 2457 } 2458 2459 if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) { 2460 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 2461 F.getSubprogram(), &F.getEntryBlock()); 2462 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType()); 2463 reportTranslationError(*MF, *TPC, *ORE, R); 2464 return false; 2465 } 2466 2467 // Need to visit defs before uses when translating instructions. 2468 GISelObserverWrapper WrapperObserver; 2469 if (EnableCSE && CSEInfo) 2470 WrapperObserver.addObserver(CSEInfo); 2471 { 2472 ReversePostOrderTraversal<const Function *> RPOT(&F); 2473 #ifndef NDEBUG 2474 DILocationVerifier Verifier; 2475 WrapperObserver.addObserver(&Verifier); 2476 #endif // ifndef NDEBUG 2477 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver); 2478 RAIIMFObserverInstaller ObsInstall(*MF, WrapperObserver); 2479 for (const BasicBlock *BB : RPOT) { 2480 MachineBasicBlock &MBB = getMBB(*BB); 2481 // Set the insertion point of all the following translations to 2482 // the end of this basic block. 2483 CurBuilder->setMBB(MBB); 2484 HasTailCall = false; 2485 for (const Instruction &Inst : *BB) { 2486 // If we translated a tail call in the last step, then we know 2487 // everything after the call is either a return, or something that is 2488 // handled by the call itself. (E.g. a lifetime marker or assume 2489 // intrinsic.) In this case, we should stop translating the block and 2490 // move on. 2491 if (HasTailCall) 2492 break; 2493 #ifndef NDEBUG 2494 Verifier.setCurrentInst(&Inst); 2495 #endif // ifndef NDEBUG 2496 if (translate(Inst)) 2497 continue; 2498 2499 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 2500 Inst.getDebugLoc(), BB); 2501 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst); 2502 2503 if (ORE->allowExtraAnalysis("gisel-irtranslator")) { 2504 std::string InstStrStorage; 2505 raw_string_ostream InstStr(InstStrStorage); 2506 InstStr << Inst; 2507 2508 R << ": '" << InstStr.str() << "'"; 2509 } 2510 2511 reportTranslationError(*MF, *TPC, *ORE, R); 2512 return false; 2513 } 2514 2515 finalizeBasicBlock(); 2516 } 2517 #ifndef NDEBUG 2518 WrapperObserver.removeObserver(&Verifier); 2519 #endif 2520 } 2521 2522 finishPendingPhis(); 2523 2524 SwiftError.propagateVRegs(); 2525 2526 // Merge the argument lowering and constants block with its single 2527 // successor, the LLVM-IR entry block. We want the basic block to 2528 // be maximal. 2529 assert(EntryBB->succ_size() == 1 && 2530 "Custom BB used for lowering should have only one successor"); 2531 // Get the successor of the current entry block. 2532 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin(); 2533 assert(NewEntryBB.pred_size() == 1 && 2534 "LLVM-IR entry block has a predecessor!?"); 2535 // Move all the instruction from the current entry block to the 2536 // new entry block. 2537 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(), 2538 EntryBB->end()); 2539 2540 // Update the live-in information for the new entry block. 2541 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins()) 2542 NewEntryBB.addLiveIn(LiveIn); 2543 NewEntryBB.sortUniqueLiveIns(); 2544 2545 // Get rid of the now empty basic block. 2546 EntryBB->removeSuccessor(&NewEntryBB); 2547 MF->remove(EntryBB); 2548 MF->DeleteMachineBasicBlock(EntryBB); 2549 2550 assert(&MF->front() == &NewEntryBB && 2551 "New entry wasn't next in the list of basic block!"); 2552 2553 // Initialize stack protector information. 2554 StackProtector &SP = getAnalysis<StackProtector>(); 2555 SP.copyToMachineFrameInfo(MF->getFrameInfo()); 2556 2557 return false; 2558 } 2559