1 //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// \file 10 /// This file implements the IRTranslator class. 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 14 #include "llvm/ADT/PostOrderIterator.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/ScopeExit.h" 17 #include "llvm/ADT/SmallSet.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 20 #include "llvm/CodeGen/Analysis.h" 21 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 22 #include "llvm/CodeGen/LowLevelType.h" 23 #include "llvm/CodeGen/MachineBasicBlock.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineMemOperand.h" 28 #include "llvm/CodeGen/MachineOperand.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/StackProtector.h" 31 #include "llvm/CodeGen/TargetFrameLowering.h" 32 #include "llvm/CodeGen/TargetLowering.h" 33 #include "llvm/CodeGen/TargetPassConfig.h" 34 #include "llvm/CodeGen/TargetRegisterInfo.h" 35 #include "llvm/CodeGen/TargetSubtargetInfo.h" 36 #include "llvm/IR/BasicBlock.h" 37 #include "llvm/IR/CFG.h" 38 #include "llvm/IR/Constant.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/DebugInfo.h" 42 #include "llvm/IR/DerivedTypes.h" 43 #include "llvm/IR/Function.h" 44 #include "llvm/IR/GetElementPtrTypeIterator.h" 45 #include "llvm/IR/InlineAsm.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Instructions.h" 48 #include "llvm/IR/IntrinsicInst.h" 49 #include "llvm/IR/Intrinsics.h" 50 #include "llvm/IR/LLVMContext.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/IR/Type.h" 53 #include "llvm/IR/User.h" 54 #include "llvm/IR/Value.h" 55 #include "llvm/MC/MCContext.h" 56 #include "llvm/Pass.h" 57 #include "llvm/Support/Casting.h" 58 #include "llvm/Support/CodeGen.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/LowLevelTypeImpl.h" 62 #include "llvm/Support/MathExtras.h" 63 #include "llvm/Support/raw_ostream.h" 64 #include "llvm/Target/TargetIntrinsicInfo.h" 65 #include "llvm/Target/TargetMachine.h" 66 #include <algorithm> 67 #include <cassert> 68 #include <cstdint> 69 #include <iterator> 70 #include <string> 71 #include <utility> 72 #include <vector> 73 74 #define DEBUG_TYPE "irtranslator" 75 76 using namespace llvm; 77 78 char IRTranslator::ID = 0; 79 80 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 81 false, false) 82 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 83 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 84 false, false) 85 86 static void reportTranslationError(MachineFunction &MF, 87 const TargetPassConfig &TPC, 88 OptimizationRemarkEmitter &ORE, 89 OptimizationRemarkMissed &R) { 90 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 91 92 // Print the function name explicitly if we don't have a debug location (which 93 // makes the diagnostic less useful) or if we're going to emit a raw error. 94 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled()) 95 R << (" (in function: " + MF.getName() + ")").str(); 96 97 if (TPC.isGlobalISelAbortEnabled()) 98 report_fatal_error(R.getMsg()); 99 else 100 ORE.emit(R); 101 } 102 103 IRTranslator::IRTranslator() : MachineFunctionPass(ID) { 104 initializeIRTranslatorPass(*PassRegistry::getPassRegistry()); 105 } 106 107 #ifndef NDEBUG 108 /// Verify that every instruction created has the same DILocation as the 109 /// instruction being translated. 110 class DILocationVerifier : MachineFunction::Delegate { 111 MachineFunction &MF; 112 const Instruction *CurrInst = nullptr; 113 114 public: 115 DILocationVerifier(MachineFunction &MF) : MF(MF) { MF.setDelegate(this); } 116 ~DILocationVerifier() { MF.resetDelegate(this); } 117 118 const Instruction *getCurrentInst() const { return CurrInst; } 119 void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; } 120 121 void MF_HandleInsertion(const MachineInstr &MI) override { 122 assert(getCurrentInst() && "Inserted instruction without a current MI"); 123 124 // Only print the check message if we're actually checking it. 125 #ifndef NDEBUG 126 LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst 127 << " was copied to " << MI); 128 #endif 129 assert(CurrInst->getDebugLoc() == MI.getDebugLoc() && 130 "Line info was not transferred to all instructions"); 131 } 132 void MF_HandleRemoval(const MachineInstr &MI) override {} 133 }; 134 #endif // ifndef NDEBUG 135 136 137 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const { 138 AU.addRequired<StackProtector>(); 139 AU.addRequired<TargetPassConfig>(); 140 getSelectionDAGFallbackAnalysisUsage(AU); 141 MachineFunctionPass::getAnalysisUsage(AU); 142 } 143 144 static void computeValueLLTs(const DataLayout &DL, Type &Ty, 145 SmallVectorImpl<LLT> &ValueTys, 146 SmallVectorImpl<uint64_t> *Offsets = nullptr, 147 uint64_t StartingOffset = 0) { 148 // Given a struct type, recursively traverse the elements. 149 if (StructType *STy = dyn_cast<StructType>(&Ty)) { 150 const StructLayout *SL = DL.getStructLayout(STy); 151 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) 152 computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets, 153 StartingOffset + SL->getElementOffset(I)); 154 return; 155 } 156 // Given an array type, recursively traverse the elements. 157 if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) { 158 Type *EltTy = ATy->getElementType(); 159 uint64_t EltSize = DL.getTypeAllocSize(EltTy); 160 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) 161 computeValueLLTs(DL, *EltTy, ValueTys, Offsets, 162 StartingOffset + i * EltSize); 163 return; 164 } 165 // Interpret void as zero return values. 166 if (Ty.isVoidTy()) 167 return; 168 // Base case: we can get an LLT for this LLVM IR type. 169 ValueTys.push_back(getLLTForType(Ty, DL)); 170 if (Offsets != nullptr) 171 Offsets->push_back(StartingOffset * 8); 172 } 173 174 IRTranslator::ValueToVRegInfo::VRegListT & 175 IRTranslator::allocateVRegs(const Value &Val) { 176 assert(!VMap.contains(Val) && "Value already allocated in VMap"); 177 auto *Regs = VMap.getVRegs(Val); 178 auto *Offsets = VMap.getOffsets(Val); 179 SmallVector<LLT, 4> SplitTys; 180 computeValueLLTs(*DL, *Val.getType(), SplitTys, 181 Offsets->empty() ? Offsets : nullptr); 182 for (unsigned i = 0; i < SplitTys.size(); ++i) 183 Regs->push_back(0); 184 return *Regs; 185 } 186 187 ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) { 188 auto VRegsIt = VMap.findVRegs(Val); 189 if (VRegsIt != VMap.vregs_end()) 190 return *VRegsIt->second; 191 192 if (Val.getType()->isVoidTy()) 193 return *VMap.getVRegs(Val); 194 195 // Create entry for this type. 196 auto *VRegs = VMap.getVRegs(Val); 197 auto *Offsets = VMap.getOffsets(Val); 198 199 assert(Val.getType()->isSized() && 200 "Don't know how to create an empty vreg"); 201 202 SmallVector<LLT, 4> SplitTys; 203 computeValueLLTs(*DL, *Val.getType(), SplitTys, 204 Offsets->empty() ? Offsets : nullptr); 205 206 if (!isa<Constant>(Val)) { 207 for (auto Ty : SplitTys) 208 VRegs->push_back(MRI->createGenericVirtualRegister(Ty)); 209 return *VRegs; 210 } 211 212 if (Val.getType()->isAggregateType()) { 213 // UndefValue, ConstantAggregateZero 214 auto &C = cast<Constant>(Val); 215 unsigned Idx = 0; 216 while (auto Elt = C.getAggregateElement(Idx++)) { 217 auto EltRegs = getOrCreateVRegs(*Elt); 218 llvm::copy(EltRegs, std::back_inserter(*VRegs)); 219 } 220 } else { 221 assert(SplitTys.size() == 1 && "unexpectedly split LLT"); 222 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0])); 223 bool Success = translate(cast<Constant>(Val), VRegs->front()); 224 if (!Success) { 225 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 226 MF->getFunction().getSubprogram(), 227 &MF->getFunction().getEntryBlock()); 228 R << "unable to translate constant: " << ore::NV("Type", Val.getType()); 229 reportTranslationError(*MF, *TPC, *ORE, R); 230 return *VRegs; 231 } 232 } 233 234 return *VRegs; 235 } 236 237 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) { 238 if (FrameIndices.find(&AI) != FrameIndices.end()) 239 return FrameIndices[&AI]; 240 241 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType()); 242 unsigned Size = 243 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue(); 244 245 // Always allocate at least one byte. 246 Size = std::max(Size, 1u); 247 248 unsigned Alignment = AI.getAlignment(); 249 if (!Alignment) 250 Alignment = DL->getABITypeAlignment(AI.getAllocatedType()); 251 252 int &FI = FrameIndices[&AI]; 253 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI); 254 return FI; 255 } 256 257 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) { 258 unsigned Alignment = 0; 259 Type *ValTy = nullptr; 260 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 261 Alignment = SI->getAlignment(); 262 ValTy = SI->getValueOperand()->getType(); 263 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 264 Alignment = LI->getAlignment(); 265 ValTy = LI->getType(); 266 } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) { 267 // TODO(PR27168): This instruction has no alignment attribute, but unlike 268 // the default alignment for load/store, the default here is to assume 269 // it has NATURAL alignment, not DataLayout-specified alignment. 270 const DataLayout &DL = AI->getModule()->getDataLayout(); 271 Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType()); 272 ValTy = AI->getCompareOperand()->getType(); 273 } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) { 274 // TODO(PR27168): This instruction has no alignment attribute, but unlike 275 // the default alignment for load/store, the default here is to assume 276 // it has NATURAL alignment, not DataLayout-specified alignment. 277 const DataLayout &DL = AI->getModule()->getDataLayout(); 278 Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType()); 279 ValTy = AI->getType(); 280 } else { 281 OptimizationRemarkMissed R("gisel-irtranslator", "", &I); 282 R << "unable to translate memop: " << ore::NV("Opcode", &I); 283 reportTranslationError(*MF, *TPC, *ORE, R); 284 return 1; 285 } 286 287 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy); 288 } 289 290 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) { 291 MachineBasicBlock *&MBB = BBToMBB[&BB]; 292 assert(MBB && "BasicBlock was not encountered before"); 293 return *MBB; 294 } 295 296 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) { 297 assert(NewPred && "new predecessor must be a real MachineBasicBlock"); 298 MachinePreds[Edge].push_back(NewPred); 299 } 300 301 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U, 302 MachineIRBuilder &MIRBuilder) { 303 // FIXME: handle signed/unsigned wrapping flags. 304 305 // Get or create a virtual register for each value. 306 // Unless the value is a Constant => loadimm cst? 307 // or inline constant each time? 308 // Creation of a virtual register needs to have a size. 309 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 310 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 311 unsigned Res = getOrCreateVReg(U); 312 auto FBinOp = MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1); 313 if (isa<Instruction>(U)) { 314 MachineInstr *FBinOpMI = FBinOp.getInstr(); 315 const Instruction &I = cast<Instruction>(U); 316 FBinOpMI->copyIRFlags(I); 317 } 318 return true; 319 } 320 321 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) { 322 // -0.0 - X --> G_FNEG 323 if (isa<Constant>(U.getOperand(0)) && 324 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) { 325 MIRBuilder.buildInstr(TargetOpcode::G_FNEG) 326 .addDef(getOrCreateVReg(U)) 327 .addUse(getOrCreateVReg(*U.getOperand(1))); 328 return true; 329 } 330 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder); 331 } 332 333 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) { 334 MIRBuilder.buildInstr(TargetOpcode::G_FNEG) 335 .addDef(getOrCreateVReg(U)) 336 .addUse(getOrCreateVReg(*U.getOperand(1))); 337 return true; 338 } 339 340 bool IRTranslator::translateCompare(const User &U, 341 MachineIRBuilder &MIRBuilder) { 342 const CmpInst *CI = dyn_cast<CmpInst>(&U); 343 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 344 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 345 unsigned Res = getOrCreateVReg(U); 346 CmpInst::Predicate Pred = 347 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>( 348 cast<ConstantExpr>(U).getPredicate()); 349 if (CmpInst::isIntPredicate(Pred)) 350 MIRBuilder.buildICmp(Pred, Res, Op0, Op1); 351 else if (Pred == CmpInst::FCMP_FALSE) 352 MIRBuilder.buildCopy( 353 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType()))); 354 else if (Pred == CmpInst::FCMP_TRUE) 355 MIRBuilder.buildCopy( 356 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType()))); 357 else 358 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1); 359 360 return true; 361 } 362 363 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) { 364 const ReturnInst &RI = cast<ReturnInst>(U); 365 const Value *Ret = RI.getReturnValue(); 366 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0) 367 Ret = nullptr; 368 369 ArrayRef<unsigned> VRegs; 370 if (Ret) 371 VRegs = getOrCreateVRegs(*Ret); 372 373 // The target may mess up with the insertion point, but 374 // this is not important as a return is the last instruction 375 // of the block anyway. 376 377 return CLI->lowerReturn(MIRBuilder, Ret, VRegs); 378 } 379 380 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) { 381 const BranchInst &BrInst = cast<BranchInst>(U); 382 unsigned Succ = 0; 383 if (!BrInst.isUnconditional()) { 384 // We want a G_BRCOND to the true BB followed by an unconditional branch. 385 unsigned Tst = getOrCreateVReg(*BrInst.getCondition()); 386 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++)); 387 MachineBasicBlock &TrueBB = getMBB(TrueTgt); 388 MIRBuilder.buildBrCond(Tst, TrueBB); 389 } 390 391 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ)); 392 MachineBasicBlock &TgtBB = getMBB(BrTgt); 393 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 394 395 // If the unconditional target is the layout successor, fallthrough. 396 if (!CurBB.isLayoutSuccessor(&TgtBB)) 397 MIRBuilder.buildBr(TgtBB); 398 399 // Link successors. 400 for (const BasicBlock *Succ : successors(&BrInst)) 401 CurBB.addSuccessor(&getMBB(*Succ)); 402 return true; 403 } 404 405 bool IRTranslator::translateSwitch(const User &U, 406 MachineIRBuilder &MIRBuilder) { 407 // For now, just translate as a chain of conditional branches. 408 // FIXME: could we share most of the logic/code in 409 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel? 410 // At first sight, it seems most of the logic in there is independent of 411 // SelectionDAG-specifics and a lot of work went in to optimize switch 412 // lowering in there. 413 414 const SwitchInst &SwInst = cast<SwitchInst>(U); 415 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition()); 416 const BasicBlock *OrigBB = SwInst.getParent(); 417 418 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL); 419 for (auto &CaseIt : SwInst.cases()) { 420 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue()); 421 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1); 422 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue); 423 MachineBasicBlock &CurMBB = MIRBuilder.getMBB(); 424 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor(); 425 MachineBasicBlock &TrueMBB = getMBB(*TrueBB); 426 427 MIRBuilder.buildBrCond(Tst, TrueMBB); 428 CurMBB.addSuccessor(&TrueMBB); 429 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB); 430 431 MachineBasicBlock *FalseMBB = 432 MF->CreateMachineBasicBlock(SwInst.getParent()); 433 // Insert the comparison blocks one after the other. 434 MF->insert(std::next(CurMBB.getIterator()), FalseMBB); 435 MIRBuilder.buildBr(*FalseMBB); 436 CurMBB.addSuccessor(FalseMBB); 437 438 MIRBuilder.setMBB(*FalseMBB); 439 } 440 // handle default case 441 const BasicBlock *DefaultBB = SwInst.getDefaultDest(); 442 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB); 443 MIRBuilder.buildBr(DefaultMBB); 444 MachineBasicBlock &CurMBB = MIRBuilder.getMBB(); 445 CurMBB.addSuccessor(&DefaultMBB); 446 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB); 447 448 return true; 449 } 450 451 bool IRTranslator::translateIndirectBr(const User &U, 452 MachineIRBuilder &MIRBuilder) { 453 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U); 454 455 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress()); 456 MIRBuilder.buildBrIndirect(Tgt); 457 458 // Link successors. 459 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 460 for (const BasicBlock *Succ : successors(&BrInst)) 461 CurBB.addSuccessor(&getMBB(*Succ)); 462 463 return true; 464 } 465 466 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) { 467 const LoadInst &LI = cast<LoadInst>(U); 468 469 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile 470 : MachineMemOperand::MONone; 471 Flags |= MachineMemOperand::MOLoad; 472 473 if (DL->getTypeStoreSize(LI.getType()) == 0) 474 return true; 475 476 ArrayRef<unsigned> Regs = getOrCreateVRegs(LI); 477 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI); 478 unsigned Base = getOrCreateVReg(*LI.getPointerOperand()); 479 480 for (unsigned i = 0; i < Regs.size(); ++i) { 481 unsigned Addr = 0; 482 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8); 483 484 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8); 485 unsigned BaseAlign = getMemOpAlignment(LI); 486 auto MMO = MF->getMachineMemOperand( 487 Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8, 488 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr, 489 LI.getSyncScopeID(), LI.getOrdering()); 490 MIRBuilder.buildLoad(Regs[i], Addr, *MMO); 491 } 492 493 return true; 494 } 495 496 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) { 497 const StoreInst &SI = cast<StoreInst>(U); 498 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile 499 : MachineMemOperand::MONone; 500 Flags |= MachineMemOperand::MOStore; 501 502 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0) 503 return true; 504 505 ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand()); 506 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand()); 507 unsigned Base = getOrCreateVReg(*SI.getPointerOperand()); 508 509 for (unsigned i = 0; i < Vals.size(); ++i) { 510 unsigned Addr = 0; 511 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8); 512 513 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8); 514 unsigned BaseAlign = getMemOpAlignment(SI); 515 auto MMO = MF->getMachineMemOperand( 516 Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8, 517 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr, 518 SI.getSyncScopeID(), SI.getOrdering()); 519 MIRBuilder.buildStore(Vals[i], Addr, *MMO); 520 } 521 return true; 522 } 523 524 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) { 525 const Value *Src = U.getOperand(0); 526 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 527 528 // getIndexedOffsetInType is designed for GEPs, so the first index is the 529 // usual array element rather than looking into the actual aggregate. 530 SmallVector<Value *, 1> Indices; 531 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 532 533 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) { 534 for (auto Idx : EVI->indices()) 535 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 536 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) { 537 for (auto Idx : IVI->indices()) 538 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 539 } else { 540 for (unsigned i = 1; i < U.getNumOperands(); ++i) 541 Indices.push_back(U.getOperand(i)); 542 } 543 544 return 8 * static_cast<uint64_t>( 545 DL.getIndexedOffsetInType(Src->getType(), Indices)); 546 } 547 548 bool IRTranslator::translateExtractValue(const User &U, 549 MachineIRBuilder &MIRBuilder) { 550 const Value *Src = U.getOperand(0); 551 uint64_t Offset = getOffsetFromIndices(U, *DL); 552 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src); 553 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src); 554 unsigned Idx = std::lower_bound(Offsets.begin(), Offsets.end(), Offset) - 555 Offsets.begin(); 556 auto &DstRegs = allocateVRegs(U); 557 558 for (unsigned i = 0; i < DstRegs.size(); ++i) 559 DstRegs[i] = SrcRegs[Idx++]; 560 561 return true; 562 } 563 564 bool IRTranslator::translateInsertValue(const User &U, 565 MachineIRBuilder &MIRBuilder) { 566 const Value *Src = U.getOperand(0); 567 uint64_t Offset = getOffsetFromIndices(U, *DL); 568 auto &DstRegs = allocateVRegs(U); 569 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U); 570 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src); 571 ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1)); 572 auto InsertedIt = InsertedRegs.begin(); 573 574 for (unsigned i = 0; i < DstRegs.size(); ++i) { 575 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end()) 576 DstRegs[i] = *InsertedIt++; 577 else 578 DstRegs[i] = SrcRegs[i]; 579 } 580 581 return true; 582 } 583 584 bool IRTranslator::translateSelect(const User &U, 585 MachineIRBuilder &MIRBuilder) { 586 unsigned Tst = getOrCreateVReg(*U.getOperand(0)); 587 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U); 588 ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1)); 589 ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2)); 590 591 for (unsigned i = 0; i < ResRegs.size(); ++i) 592 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i]); 593 594 return true; 595 } 596 597 bool IRTranslator::translateBitCast(const User &U, 598 MachineIRBuilder &MIRBuilder) { 599 // If we're bitcasting to the source type, we can reuse the source vreg. 600 if (getLLTForType(*U.getOperand(0)->getType(), *DL) == 601 getLLTForType(*U.getType(), *DL)) { 602 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0)); 603 auto &Regs = *VMap.getVRegs(U); 604 // If we already assigned a vreg for this bitcast, we can't change that. 605 // Emit a copy to satisfy the users we already emitted. 606 if (!Regs.empty()) 607 MIRBuilder.buildCopy(Regs[0], SrcReg); 608 else { 609 Regs.push_back(SrcReg); 610 VMap.getOffsets(U)->push_back(0); 611 } 612 return true; 613 } 614 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder); 615 } 616 617 bool IRTranslator::translateCast(unsigned Opcode, const User &U, 618 MachineIRBuilder &MIRBuilder) { 619 unsigned Op = getOrCreateVReg(*U.getOperand(0)); 620 unsigned Res = getOrCreateVReg(U); 621 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op); 622 return true; 623 } 624 625 bool IRTranslator::translateGetElementPtr(const User &U, 626 MachineIRBuilder &MIRBuilder) { 627 // FIXME: support vector GEPs. 628 if (U.getType()->isVectorTy()) 629 return false; 630 631 Value &Op0 = *U.getOperand(0); 632 unsigned BaseReg = getOrCreateVReg(Op0); 633 Type *PtrIRTy = Op0.getType(); 634 LLT PtrTy = getLLTForType(*PtrIRTy, *DL); 635 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy); 636 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 637 638 int64_t Offset = 0; 639 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U); 640 GTI != E; ++GTI) { 641 const Value *Idx = GTI.getOperand(); 642 if (StructType *StTy = GTI.getStructTypeOrNull()) { 643 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 644 Offset += DL->getStructLayout(StTy)->getElementOffset(Field); 645 continue; 646 } else { 647 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 648 649 // If this is a scalar constant or a splat vector of constants, 650 // handle it quickly. 651 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 652 Offset += ElementSize * CI->getSExtValue(); 653 continue; 654 } 655 656 if (Offset != 0) { 657 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 658 unsigned OffsetReg = 659 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset)); 660 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 661 662 BaseReg = NewBaseReg; 663 Offset = 0; 664 } 665 666 unsigned IdxReg = getOrCreateVReg(*Idx); 667 if (MRI->getType(IdxReg) != OffsetTy) { 668 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy); 669 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg); 670 IdxReg = NewIdxReg; 671 } 672 673 // N = N + Idx * ElementSize; 674 // Avoid doing it for ElementSize of 1. 675 unsigned GepOffsetReg; 676 if (ElementSize != 1) { 677 unsigned ElementSizeReg = 678 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize)); 679 680 GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy); 681 MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg); 682 } else 683 GepOffsetReg = IdxReg; 684 685 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 686 MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg); 687 BaseReg = NewBaseReg; 688 } 689 } 690 691 if (Offset != 0) { 692 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset)); 693 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg); 694 return true; 695 } 696 697 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg); 698 return true; 699 } 700 701 bool IRTranslator::translateMemfunc(const CallInst &CI, 702 MachineIRBuilder &MIRBuilder, 703 unsigned ID) { 704 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL); 705 Type *DstTy = CI.getArgOperand(0)->getType(); 706 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 || 707 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0)) 708 return false; 709 710 SmallVector<CallLowering::ArgInfo, 8> Args; 711 for (int i = 0; i < 3; ++i) { 712 const auto &Arg = CI.getArgOperand(i); 713 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType()); 714 } 715 716 const char *Callee; 717 switch (ID) { 718 case Intrinsic::memmove: 719 case Intrinsic::memcpy: { 720 Type *SrcTy = CI.getArgOperand(1)->getType(); 721 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0) 722 return false; 723 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove"; 724 break; 725 } 726 case Intrinsic::memset: 727 Callee = "memset"; 728 break; 729 default: 730 return false; 731 } 732 733 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(), 734 MachineOperand::CreateES(Callee), 735 CallLowering::ArgInfo(0, CI.getType()), Args); 736 } 737 738 void IRTranslator::getStackGuard(unsigned DstReg, 739 MachineIRBuilder &MIRBuilder) { 740 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 741 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF)); 742 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD); 743 MIB.addDef(DstReg); 744 745 auto &TLI = *MF->getSubtarget().getTargetLowering(); 746 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent()); 747 if (!Global) 748 return; 749 750 MachinePointerInfo MPInfo(Global); 751 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 752 MachineMemOperand::MODereferenceable; 753 MachineMemOperand *MemRef = 754 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8, 755 DL->getPointerABIAlignment(0)); 756 MIB.setMemRefs({MemRef}); 757 } 758 759 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op, 760 MachineIRBuilder &MIRBuilder) { 761 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI); 762 MIRBuilder.buildInstr(Op) 763 .addDef(ResRegs[0]) 764 .addDef(ResRegs[1]) 765 .addUse(getOrCreateVReg(*CI.getOperand(0))) 766 .addUse(getOrCreateVReg(*CI.getOperand(1))); 767 768 return true; 769 } 770 771 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID, 772 MachineIRBuilder &MIRBuilder) { 773 switch (ID) { 774 default: 775 break; 776 case Intrinsic::lifetime_start: 777 case Intrinsic::lifetime_end: 778 // Stack coloring is not enabled in O0 (which we care about now) so we can 779 // drop these. Make sure someone notices when we start compiling at higher 780 // opts though. 781 if (MF->getTarget().getOptLevel() != CodeGenOpt::None) 782 return false; 783 return true; 784 case Intrinsic::dbg_declare: { 785 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI); 786 assert(DI.getVariable() && "Missing variable"); 787 788 const Value *Address = DI.getAddress(); 789 if (!Address || isa<UndefValue>(Address)) { 790 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 791 return true; 792 } 793 794 assert(DI.getVariable()->isValidLocationForIntrinsic( 795 MIRBuilder.getDebugLoc()) && 796 "Expected inlined-at fields to agree"); 797 auto AI = dyn_cast<AllocaInst>(Address); 798 if (AI && AI->isStaticAlloca()) { 799 // Static allocas are tracked at the MF level, no need for DBG_VALUE 800 // instructions (in fact, they get ignored if they *do* exist). 801 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(), 802 getOrCreateFrameIndex(*AI), DI.getDebugLoc()); 803 } else { 804 // A dbg.declare describes the address of a source variable, so lower it 805 // into an indirect DBG_VALUE. 806 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address), 807 DI.getVariable(), DI.getExpression()); 808 } 809 return true; 810 } 811 case Intrinsic::dbg_label: { 812 const DbgLabelInst &DI = cast<DbgLabelInst>(CI); 813 assert(DI.getLabel() && "Missing label"); 814 815 assert(DI.getLabel()->isValidLocationForIntrinsic( 816 MIRBuilder.getDebugLoc()) && 817 "Expected inlined-at fields to agree"); 818 819 MIRBuilder.buildDbgLabel(DI.getLabel()); 820 return true; 821 } 822 case Intrinsic::vaend: 823 // No target I know of cares about va_end. Certainly no in-tree target 824 // does. Simplest intrinsic ever! 825 return true; 826 case Intrinsic::vastart: { 827 auto &TLI = *MF->getSubtarget().getTargetLowering(); 828 Value *Ptr = CI.getArgOperand(0); 829 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8; 830 831 MIRBuilder.buildInstr(TargetOpcode::G_VASTART) 832 .addUse(getOrCreateVReg(*Ptr)) 833 .addMemOperand(MF->getMachineMemOperand( 834 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0)); 835 return true; 836 } 837 case Intrinsic::dbg_value: { 838 // This form of DBG_VALUE is target-independent. 839 const DbgValueInst &DI = cast<DbgValueInst>(CI); 840 const Value *V = DI.getValue(); 841 assert(DI.getVariable()->isValidLocationForIntrinsic( 842 MIRBuilder.getDebugLoc()) && 843 "Expected inlined-at fields to agree"); 844 if (!V) { 845 // Currently the optimizer can produce this; insert an undef to 846 // help debugging. Probably the optimizer should not do this. 847 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression()); 848 } else if (const auto *CI = dyn_cast<Constant>(V)) { 849 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression()); 850 } else { 851 unsigned Reg = getOrCreateVReg(*V); 852 // FIXME: This does not handle register-indirect values at offset 0. The 853 // direct/indirect thing shouldn't really be handled by something as 854 // implicit as reg+noreg vs reg+imm in the first palce, but it seems 855 // pretty baked in right now. 856 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression()); 857 } 858 return true; 859 } 860 case Intrinsic::uadd_with_overflow: 861 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder); 862 case Intrinsic::sadd_with_overflow: 863 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder); 864 case Intrinsic::usub_with_overflow: 865 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder); 866 case Intrinsic::ssub_with_overflow: 867 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder); 868 case Intrinsic::umul_with_overflow: 869 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder); 870 case Intrinsic::smul_with_overflow: 871 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder); 872 case Intrinsic::pow: 873 MIRBuilder.buildInstr(TargetOpcode::G_FPOW) 874 .addDef(getOrCreateVReg(CI)) 875 .addUse(getOrCreateVReg(*CI.getArgOperand(0))) 876 .addUse(getOrCreateVReg(*CI.getArgOperand(1))); 877 return true; 878 case Intrinsic::exp: 879 MIRBuilder.buildInstr(TargetOpcode::G_FEXP) 880 .addDef(getOrCreateVReg(CI)) 881 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 882 return true; 883 case Intrinsic::exp2: 884 MIRBuilder.buildInstr(TargetOpcode::G_FEXP2) 885 .addDef(getOrCreateVReg(CI)) 886 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 887 return true; 888 case Intrinsic::log: 889 MIRBuilder.buildInstr(TargetOpcode::G_FLOG) 890 .addDef(getOrCreateVReg(CI)) 891 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 892 return true; 893 case Intrinsic::log2: 894 MIRBuilder.buildInstr(TargetOpcode::G_FLOG2) 895 .addDef(getOrCreateVReg(CI)) 896 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 897 return true; 898 case Intrinsic::log10: 899 MIRBuilder.buildInstr(TargetOpcode::G_FLOG10) 900 .addDef(getOrCreateVReg(CI)) 901 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 902 return true; 903 case Intrinsic::fabs: 904 MIRBuilder.buildInstr(TargetOpcode::G_FABS) 905 .addDef(getOrCreateVReg(CI)) 906 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 907 return true; 908 case Intrinsic::trunc: 909 MIRBuilder.buildInstr(TargetOpcode::G_INTRINSIC_TRUNC) 910 .addDef(getOrCreateVReg(CI)) 911 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 912 return true; 913 case Intrinsic::round: 914 MIRBuilder.buildInstr(TargetOpcode::G_INTRINSIC_ROUND) 915 .addDef(getOrCreateVReg(CI)) 916 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 917 return true; 918 case Intrinsic::fma: 919 MIRBuilder.buildInstr(TargetOpcode::G_FMA) 920 .addDef(getOrCreateVReg(CI)) 921 .addUse(getOrCreateVReg(*CI.getArgOperand(0))) 922 .addUse(getOrCreateVReg(*CI.getArgOperand(1))) 923 .addUse(getOrCreateVReg(*CI.getArgOperand(2))); 924 return true; 925 case Intrinsic::fmuladd: { 926 const TargetMachine &TM = MF->getTarget(); 927 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering(); 928 unsigned Dst = getOrCreateVReg(CI); 929 unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0)); 930 unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1)); 931 unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2)); 932 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 933 TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) { 934 // TODO: Revisit this to see if we should move this part of the 935 // lowering to the combiner. 936 MIRBuilder.buildInstr(TargetOpcode::G_FMA, {Dst}, {Op0, Op1, Op2}); 937 } else { 938 LLT Ty = getLLTForType(*CI.getType(), *DL); 939 auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, {Ty}, {Op0, Op1}); 940 MIRBuilder.buildInstr(TargetOpcode::G_FADD, {Dst}, {FMul, Op2}); 941 } 942 return true; 943 } 944 case Intrinsic::memcpy: 945 case Intrinsic::memmove: 946 case Intrinsic::memset: 947 return translateMemfunc(CI, MIRBuilder, ID); 948 case Intrinsic::eh_typeid_for: { 949 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0)); 950 unsigned Reg = getOrCreateVReg(CI); 951 unsigned TypeID = MF->getTypeIDFor(GV); 952 MIRBuilder.buildConstant(Reg, TypeID); 953 return true; 954 } 955 case Intrinsic::objectsize: { 956 // If we don't know by now, we're never going to know. 957 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1)); 958 959 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0); 960 return true; 961 } 962 case Intrinsic::is_constant: 963 // If this wasn't constant-folded away by now, then it's not a 964 // constant. 965 MIRBuilder.buildConstant(getOrCreateVReg(CI), 0); 966 return true; 967 case Intrinsic::stackguard: 968 getStackGuard(getOrCreateVReg(CI), MIRBuilder); 969 return true; 970 case Intrinsic::stackprotector: { 971 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 972 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy); 973 getStackGuard(GuardVal, MIRBuilder); 974 975 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1)); 976 int FI = getOrCreateFrameIndex(*Slot); 977 MF->getFrameInfo().setStackProtectorIndex(FI); 978 979 MIRBuilder.buildStore( 980 GuardVal, getOrCreateVReg(*Slot), 981 *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 982 MachineMemOperand::MOStore | 983 MachineMemOperand::MOVolatile, 984 PtrTy.getSizeInBits() / 8, 8)); 985 return true; 986 } 987 case Intrinsic::cttz: 988 case Intrinsic::ctlz: { 989 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1)); 990 bool isTrailing = ID == Intrinsic::cttz; 991 unsigned Opcode = isTrailing 992 ? Cst->isZero() ? TargetOpcode::G_CTTZ 993 : TargetOpcode::G_CTTZ_ZERO_UNDEF 994 : Cst->isZero() ? TargetOpcode::G_CTLZ 995 : TargetOpcode::G_CTLZ_ZERO_UNDEF; 996 MIRBuilder.buildInstr(Opcode) 997 .addDef(getOrCreateVReg(CI)) 998 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 999 return true; 1000 } 1001 case Intrinsic::ctpop: { 1002 MIRBuilder.buildInstr(TargetOpcode::G_CTPOP) 1003 .addDef(getOrCreateVReg(CI)) 1004 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 1005 return true; 1006 } 1007 case Intrinsic::invariant_start: { 1008 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 1009 unsigned Undef = MRI->createGenericVirtualRegister(PtrTy); 1010 MIRBuilder.buildUndef(Undef); 1011 return true; 1012 } 1013 case Intrinsic::invariant_end: 1014 return true; 1015 } 1016 return false; 1017 } 1018 1019 bool IRTranslator::translateInlineAsm(const CallInst &CI, 1020 MachineIRBuilder &MIRBuilder) { 1021 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue()); 1022 if (!IA.getConstraintString().empty()) 1023 return false; 1024 1025 unsigned ExtraInfo = 0; 1026 if (IA.hasSideEffects()) 1027 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 1028 if (IA.getDialect() == InlineAsm::AD_Intel) 1029 ExtraInfo |= InlineAsm::Extra_AsmDialect; 1030 1031 MIRBuilder.buildInstr(TargetOpcode::INLINEASM) 1032 .addExternalSymbol(IA.getAsmString().c_str()) 1033 .addImm(ExtraInfo); 1034 1035 return true; 1036 } 1037 1038 unsigned IRTranslator::packRegs(const Value &V, 1039 MachineIRBuilder &MIRBuilder) { 1040 ArrayRef<unsigned> Regs = getOrCreateVRegs(V); 1041 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V); 1042 LLT BigTy = getLLTForType(*V.getType(), *DL); 1043 1044 if (Regs.size() == 1) 1045 return Regs[0]; 1046 1047 unsigned Dst = MRI->createGenericVirtualRegister(BigTy); 1048 MIRBuilder.buildUndef(Dst); 1049 for (unsigned i = 0; i < Regs.size(); ++i) { 1050 unsigned NewDst = MRI->createGenericVirtualRegister(BigTy); 1051 MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]); 1052 Dst = NewDst; 1053 } 1054 return Dst; 1055 } 1056 1057 void IRTranslator::unpackRegs(const Value &V, unsigned Src, 1058 MachineIRBuilder &MIRBuilder) { 1059 ArrayRef<unsigned> Regs = getOrCreateVRegs(V); 1060 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V); 1061 1062 for (unsigned i = 0; i < Regs.size(); ++i) 1063 MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]); 1064 } 1065 1066 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) { 1067 const CallInst &CI = cast<CallInst>(U); 1068 auto TII = MF->getTarget().getIntrinsicInfo(); 1069 const Function *F = CI.getCalledFunction(); 1070 1071 // FIXME: support Windows dllimport function calls. 1072 if (F && F->hasDLLImportStorageClass()) 1073 return false; 1074 1075 if (CI.isInlineAsm()) 1076 return translateInlineAsm(CI, MIRBuilder); 1077 1078 Intrinsic::ID ID = Intrinsic::not_intrinsic; 1079 if (F && F->isIntrinsic()) { 1080 ID = F->getIntrinsicID(); 1081 if (TII && ID == Intrinsic::not_intrinsic) 1082 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F)); 1083 } 1084 1085 bool IsSplitType = valueIsSplit(CI); 1086 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) { 1087 unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister( 1088 getLLTForType(*CI.getType(), *DL)) 1089 : getOrCreateVReg(CI); 1090 1091 SmallVector<unsigned, 8> Args; 1092 for (auto &Arg: CI.arg_operands()) 1093 Args.push_back(packRegs(*Arg, MIRBuilder)); 1094 1095 MF->getFrameInfo().setHasCalls(true); 1096 bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() { 1097 return getOrCreateVReg(*CI.getCalledValue()); 1098 }); 1099 1100 if (IsSplitType) 1101 unpackRegs(CI, Res, MIRBuilder); 1102 return Success; 1103 } 1104 1105 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic"); 1106 1107 if (translateKnownIntrinsic(CI, ID, MIRBuilder)) 1108 return true; 1109 1110 unsigned Res = 0; 1111 if (!CI.getType()->isVoidTy()) { 1112 if (IsSplitType) 1113 Res = 1114 MRI->createGenericVirtualRegister(getLLTForType(*CI.getType(), *DL)); 1115 else 1116 Res = getOrCreateVReg(CI); 1117 } 1118 MachineInstrBuilder MIB = 1119 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory()); 1120 1121 for (auto &Arg : CI.arg_operands()) { 1122 // Some intrinsics take metadata parameters. Reject them. 1123 if (isa<MetadataAsValue>(Arg)) 1124 return false; 1125 MIB.addUse(packRegs(*Arg, MIRBuilder)); 1126 } 1127 1128 if (IsSplitType) 1129 unpackRegs(CI, Res, MIRBuilder); 1130 1131 // Add a MachineMemOperand if it is a target mem intrinsic. 1132 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering(); 1133 TargetLowering::IntrinsicInfo Info; 1134 // TODO: Add a GlobalISel version of getTgtMemIntrinsic. 1135 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) { 1136 uint64_t Size = Info.memVT.getStoreSize(); 1137 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal), 1138 Info.flags, Size, Info.align)); 1139 } 1140 1141 return true; 1142 } 1143 1144 bool IRTranslator::translateInvoke(const User &U, 1145 MachineIRBuilder &MIRBuilder) { 1146 const InvokeInst &I = cast<InvokeInst>(U); 1147 MCContext &Context = MF->getContext(); 1148 1149 const BasicBlock *ReturnBB = I.getSuccessor(0); 1150 const BasicBlock *EHPadBB = I.getSuccessor(1); 1151 1152 const Value *Callee = I.getCalledValue(); 1153 const Function *Fn = dyn_cast<Function>(Callee); 1154 if (isa<InlineAsm>(Callee)) 1155 return false; 1156 1157 // FIXME: support invoking patchpoint and statepoint intrinsics. 1158 if (Fn && Fn->isIntrinsic()) 1159 return false; 1160 1161 // FIXME: support whatever these are. 1162 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 1163 return false; 1164 1165 // FIXME: support Windows exception handling. 1166 if (!isa<LandingPadInst>(EHPadBB->front())) 1167 return false; 1168 1169 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about 1170 // the region covered by the try. 1171 MCSymbol *BeginSymbol = Context.createTempSymbol(); 1172 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol); 1173 1174 unsigned Res = 1175 MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL)); 1176 SmallVector<unsigned, 8> Args; 1177 for (auto &Arg: I.arg_operands()) 1178 Args.push_back(packRegs(*Arg, MIRBuilder)); 1179 1180 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args, 1181 [&]() { return getOrCreateVReg(*I.getCalledValue()); })) 1182 return false; 1183 1184 unpackRegs(I, Res, MIRBuilder); 1185 1186 MCSymbol *EndSymbol = Context.createTempSymbol(); 1187 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol); 1188 1189 // FIXME: track probabilities. 1190 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB), 1191 &ReturnMBB = getMBB(*ReturnBB); 1192 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol); 1193 MIRBuilder.getMBB().addSuccessor(&ReturnMBB); 1194 MIRBuilder.getMBB().addSuccessor(&EHPadMBB); 1195 MIRBuilder.buildBr(ReturnMBB); 1196 1197 return true; 1198 } 1199 1200 bool IRTranslator::translateLandingPad(const User &U, 1201 MachineIRBuilder &MIRBuilder) { 1202 const LandingPadInst &LP = cast<LandingPadInst>(U); 1203 1204 MachineBasicBlock &MBB = MIRBuilder.getMBB(); 1205 1206 MBB.setIsEHPad(); 1207 1208 // If there aren't registers to copy the values into (e.g., during SjLj 1209 // exceptions), then don't bother. 1210 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1211 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn(); 1212 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 1213 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 1214 return true; 1215 1216 // If landingpad's return type is token type, we don't create DAG nodes 1217 // for its exception pointer and selector value. The extraction of exception 1218 // pointer or selector value from token type landingpads is not currently 1219 // supported. 1220 if (LP.getType()->isTokenTy()) 1221 return true; 1222 1223 // Add a label to mark the beginning of the landing pad. Deletion of the 1224 // landing pad can thus be detected via the MachineModuleInfo. 1225 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL) 1226 .addSym(MF->addLandingPad(&MBB)); 1227 1228 LLT Ty = getLLTForType(*LP.getType(), *DL); 1229 unsigned Undef = MRI->createGenericVirtualRegister(Ty); 1230 MIRBuilder.buildUndef(Undef); 1231 1232 SmallVector<LLT, 2> Tys; 1233 for (Type *Ty : cast<StructType>(LP.getType())->elements()) 1234 Tys.push_back(getLLTForType(*Ty, *DL)); 1235 assert(Tys.size() == 2 && "Only two-valued landingpads are supported"); 1236 1237 // Mark exception register as live in. 1238 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn); 1239 if (!ExceptionReg) 1240 return false; 1241 1242 MBB.addLiveIn(ExceptionReg); 1243 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP); 1244 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg); 1245 1246 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn); 1247 if (!SelectorReg) 1248 return false; 1249 1250 MBB.addLiveIn(SelectorReg); 1251 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]); 1252 MIRBuilder.buildCopy(PtrVReg, SelectorReg); 1253 MIRBuilder.buildCast(ResRegs[1], PtrVReg); 1254 1255 return true; 1256 } 1257 1258 bool IRTranslator::translateAlloca(const User &U, 1259 MachineIRBuilder &MIRBuilder) { 1260 auto &AI = cast<AllocaInst>(U); 1261 1262 if (AI.isSwiftError()) 1263 return false; 1264 1265 if (AI.isStaticAlloca()) { 1266 unsigned Res = getOrCreateVReg(AI); 1267 int FI = getOrCreateFrameIndex(AI); 1268 MIRBuilder.buildFrameIndex(Res, FI); 1269 return true; 1270 } 1271 1272 // FIXME: support stack probing for Windows. 1273 if (MF->getTarget().getTargetTriple().isOSWindows()) 1274 return false; 1275 1276 // Now we're in the harder dynamic case. 1277 Type *Ty = AI.getAllocatedType(); 1278 unsigned Align = 1279 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment()); 1280 1281 unsigned NumElts = getOrCreateVReg(*AI.getArraySize()); 1282 1283 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType()); 1284 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL); 1285 if (MRI->getType(NumElts) != IntPtrTy) { 1286 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy); 1287 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts); 1288 NumElts = ExtElts; 1289 } 1290 1291 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy); 1292 unsigned TySize = 1293 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty))); 1294 MIRBuilder.buildMul(AllocSize, NumElts, TySize); 1295 1296 LLT PtrTy = getLLTForType(*AI.getType(), *DL); 1297 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1298 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore(); 1299 1300 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy); 1301 MIRBuilder.buildCopy(SPTmp, SPReg); 1302 1303 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy); 1304 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize); 1305 1306 // Handle alignment. We have to realign if the allocation granule was smaller 1307 // than stack alignment, or the specific alloca requires more than stack 1308 // alignment. 1309 unsigned StackAlign = 1310 MF->getSubtarget().getFrameLowering()->getStackAlignment(); 1311 Align = std::max(Align, StackAlign); 1312 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) { 1313 // Round the size of the allocation up to the stack alignment size 1314 // by add SA-1 to the size. This doesn't overflow because we're computing 1315 // an address inside an alloca. 1316 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy); 1317 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align)); 1318 AllocTmp = AlignedAlloc; 1319 } 1320 1321 MIRBuilder.buildCopy(SPReg, AllocTmp); 1322 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp); 1323 1324 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI); 1325 assert(MF->getFrameInfo().hasVarSizedObjects()); 1326 return true; 1327 } 1328 1329 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) { 1330 // FIXME: We may need more info about the type. Because of how LLT works, 1331 // we're completely discarding the i64/double distinction here (amongst 1332 // others). Fortunately the ABIs I know of where that matters don't use va_arg 1333 // anyway but that's not guaranteed. 1334 MIRBuilder.buildInstr(TargetOpcode::G_VAARG) 1335 .addDef(getOrCreateVReg(U)) 1336 .addUse(getOrCreateVReg(*U.getOperand(0))) 1337 .addImm(DL->getABITypeAlignment(U.getType())); 1338 return true; 1339 } 1340 1341 bool IRTranslator::translateInsertElement(const User &U, 1342 MachineIRBuilder &MIRBuilder) { 1343 // If it is a <1 x Ty> vector, use the scalar as it is 1344 // not a legal vector type in LLT. 1345 if (U.getType()->getVectorNumElements() == 1) { 1346 unsigned Elt = getOrCreateVReg(*U.getOperand(1)); 1347 auto &Regs = *VMap.getVRegs(U); 1348 if (Regs.empty()) { 1349 Regs.push_back(Elt); 1350 VMap.getOffsets(U)->push_back(0); 1351 } else { 1352 MIRBuilder.buildCopy(Regs[0], Elt); 1353 } 1354 return true; 1355 } 1356 1357 unsigned Res = getOrCreateVReg(U); 1358 unsigned Val = getOrCreateVReg(*U.getOperand(0)); 1359 unsigned Elt = getOrCreateVReg(*U.getOperand(1)); 1360 unsigned Idx = getOrCreateVReg(*U.getOperand(2)); 1361 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx); 1362 return true; 1363 } 1364 1365 bool IRTranslator::translateExtractElement(const User &U, 1366 MachineIRBuilder &MIRBuilder) { 1367 // If it is a <1 x Ty> vector, use the scalar as it is 1368 // not a legal vector type in LLT. 1369 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) { 1370 unsigned Elt = getOrCreateVReg(*U.getOperand(0)); 1371 auto &Regs = *VMap.getVRegs(U); 1372 if (Regs.empty()) { 1373 Regs.push_back(Elt); 1374 VMap.getOffsets(U)->push_back(0); 1375 } else { 1376 MIRBuilder.buildCopy(Regs[0], Elt); 1377 } 1378 return true; 1379 } 1380 unsigned Res = getOrCreateVReg(U); 1381 unsigned Val = getOrCreateVReg(*U.getOperand(0)); 1382 const auto &TLI = *MF->getSubtarget().getTargetLowering(); 1383 unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits(); 1384 unsigned Idx = 0; 1385 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) { 1386 if (CI->getBitWidth() != PreferredVecIdxWidth) { 1387 APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth); 1388 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx); 1389 Idx = getOrCreateVReg(*NewIdxCI); 1390 } 1391 } 1392 if (!Idx) 1393 Idx = getOrCreateVReg(*U.getOperand(1)); 1394 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) { 1395 const LLT &VecIdxTy = LLT::scalar(PreferredVecIdxWidth); 1396 Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx)->getOperand(0).getReg(); 1397 } 1398 MIRBuilder.buildExtractVectorElement(Res, Val, Idx); 1399 return true; 1400 } 1401 1402 bool IRTranslator::translateShuffleVector(const User &U, 1403 MachineIRBuilder &MIRBuilder) { 1404 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR) 1405 .addDef(getOrCreateVReg(U)) 1406 .addUse(getOrCreateVReg(*U.getOperand(0))) 1407 .addUse(getOrCreateVReg(*U.getOperand(1))) 1408 .addUse(getOrCreateVReg(*U.getOperand(2))); 1409 return true; 1410 } 1411 1412 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) { 1413 const PHINode &PI = cast<PHINode>(U); 1414 1415 SmallVector<MachineInstr *, 4> Insts; 1416 for (auto Reg : getOrCreateVRegs(PI)) { 1417 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {}); 1418 Insts.push_back(MIB.getInstr()); 1419 } 1420 1421 PendingPHIs.emplace_back(&PI, std::move(Insts)); 1422 return true; 1423 } 1424 1425 bool IRTranslator::translateAtomicCmpXchg(const User &U, 1426 MachineIRBuilder &MIRBuilder) { 1427 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U); 1428 1429 if (I.isWeak()) 1430 return false; 1431 1432 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile 1433 : MachineMemOperand::MONone; 1434 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1435 1436 Type *ResType = I.getType(); 1437 Type *ValType = ResType->Type::getStructElementType(0); 1438 1439 auto Res = getOrCreateVRegs(I); 1440 unsigned OldValRes = Res[0]; 1441 unsigned SuccessRes = Res[1]; 1442 unsigned Addr = getOrCreateVReg(*I.getPointerOperand()); 1443 unsigned Cmp = getOrCreateVReg(*I.getCompareOperand()); 1444 unsigned NewVal = getOrCreateVReg(*I.getNewValOperand()); 1445 1446 MIRBuilder.buildAtomicCmpXchgWithSuccess( 1447 OldValRes, SuccessRes, Addr, Cmp, NewVal, 1448 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 1449 Flags, DL->getTypeStoreSize(ValType), 1450 getMemOpAlignment(I), AAMDNodes(), nullptr, 1451 I.getSyncScopeID(), I.getSuccessOrdering(), 1452 I.getFailureOrdering())); 1453 return true; 1454 } 1455 1456 bool IRTranslator::translateAtomicRMW(const User &U, 1457 MachineIRBuilder &MIRBuilder) { 1458 const AtomicRMWInst &I = cast<AtomicRMWInst>(U); 1459 1460 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile 1461 : MachineMemOperand::MONone; 1462 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1463 1464 Type *ResType = I.getType(); 1465 1466 unsigned Res = getOrCreateVReg(I); 1467 unsigned Addr = getOrCreateVReg(*I.getPointerOperand()); 1468 unsigned Val = getOrCreateVReg(*I.getValOperand()); 1469 1470 unsigned Opcode = 0; 1471 switch (I.getOperation()) { 1472 default: 1473 llvm_unreachable("Unknown atomicrmw op"); 1474 return false; 1475 case AtomicRMWInst::Xchg: 1476 Opcode = TargetOpcode::G_ATOMICRMW_XCHG; 1477 break; 1478 case AtomicRMWInst::Add: 1479 Opcode = TargetOpcode::G_ATOMICRMW_ADD; 1480 break; 1481 case AtomicRMWInst::Sub: 1482 Opcode = TargetOpcode::G_ATOMICRMW_SUB; 1483 break; 1484 case AtomicRMWInst::And: 1485 Opcode = TargetOpcode::G_ATOMICRMW_AND; 1486 break; 1487 case AtomicRMWInst::Nand: 1488 Opcode = TargetOpcode::G_ATOMICRMW_NAND; 1489 break; 1490 case AtomicRMWInst::Or: 1491 Opcode = TargetOpcode::G_ATOMICRMW_OR; 1492 break; 1493 case AtomicRMWInst::Xor: 1494 Opcode = TargetOpcode::G_ATOMICRMW_XOR; 1495 break; 1496 case AtomicRMWInst::Max: 1497 Opcode = TargetOpcode::G_ATOMICRMW_MAX; 1498 break; 1499 case AtomicRMWInst::Min: 1500 Opcode = TargetOpcode::G_ATOMICRMW_MIN; 1501 break; 1502 case AtomicRMWInst::UMax: 1503 Opcode = TargetOpcode::G_ATOMICRMW_UMAX; 1504 break; 1505 case AtomicRMWInst::UMin: 1506 Opcode = TargetOpcode::G_ATOMICRMW_UMIN; 1507 break; 1508 } 1509 1510 MIRBuilder.buildAtomicRMW( 1511 Opcode, Res, Addr, Val, 1512 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 1513 Flags, DL->getTypeStoreSize(ResType), 1514 getMemOpAlignment(I), AAMDNodes(), nullptr, 1515 I.getSyncScopeID(), I.getOrdering())); 1516 return true; 1517 } 1518 1519 void IRTranslator::finishPendingPhis() { 1520 #ifndef NDEBUG 1521 DILocationVerifier Verifier(*MF); 1522 #endif // ifndef NDEBUG 1523 for (auto &Phi : PendingPHIs) { 1524 const PHINode *PI = Phi.first; 1525 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second; 1526 EntryBuilder.setDebugLoc(PI->getDebugLoc()); 1527 #ifndef NDEBUG 1528 Verifier.setCurrentInst(PI); 1529 #endif // ifndef NDEBUG 1530 1531 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator 1532 // won't create extra control flow here, otherwise we need to find the 1533 // dominating predecessor here (or perhaps force the weirder IRTranslators 1534 // to provide a simple boundary). 1535 SmallSet<const BasicBlock *, 4> HandledPreds; 1536 1537 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) { 1538 auto IRPred = PI->getIncomingBlock(i); 1539 if (HandledPreds.count(IRPred)) 1540 continue; 1541 1542 HandledPreds.insert(IRPred); 1543 ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i)); 1544 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) { 1545 assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) && 1546 "incorrect CFG at MachineBasicBlock level"); 1547 for (unsigned j = 0; j < ValRegs.size(); ++j) { 1548 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]); 1549 MIB.addUse(ValRegs[j]); 1550 MIB.addMBB(Pred); 1551 } 1552 } 1553 } 1554 } 1555 } 1556 1557 bool IRTranslator::valueIsSplit(const Value &V, 1558 SmallVectorImpl<uint64_t> *Offsets) { 1559 SmallVector<LLT, 4> SplitTys; 1560 if (Offsets && !Offsets->empty()) 1561 Offsets->clear(); 1562 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets); 1563 return SplitTys.size() > 1; 1564 } 1565 1566 bool IRTranslator::translate(const Instruction &Inst) { 1567 CurBuilder.setDebugLoc(Inst.getDebugLoc()); 1568 EntryBuilder.setDebugLoc(Inst.getDebugLoc()); 1569 switch(Inst.getOpcode()) { 1570 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1571 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder); 1572 #include "llvm/IR/Instruction.def" 1573 default: 1574 return false; 1575 } 1576 } 1577 1578 bool IRTranslator::translate(const Constant &C, unsigned Reg) { 1579 if (auto CI = dyn_cast<ConstantInt>(&C)) 1580 EntryBuilder.buildConstant(Reg, *CI); 1581 else if (auto CF = dyn_cast<ConstantFP>(&C)) 1582 EntryBuilder.buildFConstant(Reg, *CF); 1583 else if (isa<UndefValue>(C)) 1584 EntryBuilder.buildUndef(Reg); 1585 else if (isa<ConstantPointerNull>(C)) { 1586 // As we are trying to build a constant val of 0 into a pointer, 1587 // insert a cast to make them correct with respect to types. 1588 unsigned NullSize = DL->getTypeSizeInBits(C.getType()); 1589 auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize); 1590 auto *ZeroVal = ConstantInt::get(ZeroTy, 0); 1591 unsigned ZeroReg = getOrCreateVReg(*ZeroVal); 1592 EntryBuilder.buildCast(Reg, ZeroReg); 1593 } else if (auto GV = dyn_cast<GlobalValue>(&C)) 1594 EntryBuilder.buildGlobalValue(Reg, GV); 1595 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) { 1596 if (!CAZ->getType()->isVectorTy()) 1597 return false; 1598 // Return the scalar if it is a <1 x Ty> vector. 1599 if (CAZ->getNumElements() == 1) 1600 return translate(*CAZ->getElementValue(0u), Reg); 1601 SmallVector<unsigned, 4> Ops; 1602 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) { 1603 Constant &Elt = *CAZ->getElementValue(i); 1604 Ops.push_back(getOrCreateVReg(Elt)); 1605 } 1606 EntryBuilder.buildBuildVector(Reg, Ops); 1607 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) { 1608 // Return the scalar if it is a <1 x Ty> vector. 1609 if (CV->getNumElements() == 1) 1610 return translate(*CV->getElementAsConstant(0), Reg); 1611 SmallVector<unsigned, 4> Ops; 1612 for (unsigned i = 0; i < CV->getNumElements(); ++i) { 1613 Constant &Elt = *CV->getElementAsConstant(i); 1614 Ops.push_back(getOrCreateVReg(Elt)); 1615 } 1616 EntryBuilder.buildBuildVector(Reg, Ops); 1617 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) { 1618 switch(CE->getOpcode()) { 1619 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1620 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder); 1621 #include "llvm/IR/Instruction.def" 1622 default: 1623 return false; 1624 } 1625 } else if (auto CV = dyn_cast<ConstantVector>(&C)) { 1626 if (CV->getNumOperands() == 1) 1627 return translate(*CV->getOperand(0), Reg); 1628 SmallVector<unsigned, 4> Ops; 1629 for (unsigned i = 0; i < CV->getNumOperands(); ++i) { 1630 Ops.push_back(getOrCreateVReg(*CV->getOperand(i))); 1631 } 1632 EntryBuilder.buildBuildVector(Reg, Ops); 1633 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) { 1634 EntryBuilder.buildBlockAddress(Reg, BA); 1635 } else 1636 return false; 1637 1638 return true; 1639 } 1640 1641 void IRTranslator::finalizeFunction() { 1642 // Release the memory used by the different maps we 1643 // needed during the translation. 1644 PendingPHIs.clear(); 1645 VMap.reset(); 1646 FrameIndices.clear(); 1647 MachinePreds.clear(); 1648 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it 1649 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid 1650 // destroying it twice (in ~IRTranslator() and ~LLVMContext()) 1651 EntryBuilder = MachineIRBuilder(); 1652 CurBuilder = MachineIRBuilder(); 1653 } 1654 1655 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) { 1656 MF = &CurMF; 1657 const Function &F = MF->getFunction(); 1658 if (F.empty()) 1659 return false; 1660 CLI = MF->getSubtarget().getCallLowering(); 1661 CurBuilder.setMF(*MF); 1662 EntryBuilder.setMF(*MF); 1663 MRI = &MF->getRegInfo(); 1664 DL = &F.getParent()->getDataLayout(); 1665 TPC = &getAnalysis<TargetPassConfig>(); 1666 ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F); 1667 1668 assert(PendingPHIs.empty() && "stale PHIs"); 1669 1670 if (!DL->isLittleEndian()) { 1671 // Currently we don't properly handle big endian code. 1672 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1673 F.getSubprogram(), &F.getEntryBlock()); 1674 R << "unable to translate in big endian mode"; 1675 reportTranslationError(*MF, *TPC, *ORE, R); 1676 } 1677 1678 // Release the per-function state when we return, whether we succeeded or not. 1679 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); }); 1680 1681 // Setup a separate basic-block for the arguments and constants 1682 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock(); 1683 MF->push_back(EntryBB); 1684 EntryBuilder.setMBB(*EntryBB); 1685 1686 // Create all blocks, in IR order, to preserve the layout. 1687 for (const BasicBlock &BB: F) { 1688 auto *&MBB = BBToMBB[&BB]; 1689 1690 MBB = MF->CreateMachineBasicBlock(&BB); 1691 MF->push_back(MBB); 1692 1693 if (BB.hasAddressTaken()) 1694 MBB->setHasAddressTaken(); 1695 } 1696 1697 // Make our arguments/constants entry block fallthrough to the IR entry block. 1698 EntryBB->addSuccessor(&getMBB(F.front())); 1699 1700 // Lower the actual args into this basic block. 1701 SmallVector<unsigned, 8> VRegArgs; 1702 for (const Argument &Arg: F.args()) { 1703 if (DL->getTypeStoreSize(Arg.getType()) == 0) 1704 continue; // Don't handle zero sized types. 1705 VRegArgs.push_back( 1706 MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL))); 1707 } 1708 1709 // We don't currently support translating swifterror or swiftself functions. 1710 for (auto &Arg : F.args()) { 1711 if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) { 1712 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1713 F.getSubprogram(), &F.getEntryBlock()); 1714 R << "unable to lower arguments due to swifterror/swiftself: " 1715 << ore::NV("Prototype", F.getType()); 1716 reportTranslationError(*MF, *TPC, *ORE, R); 1717 return false; 1718 } 1719 } 1720 1721 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) { 1722 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1723 F.getSubprogram(), &F.getEntryBlock()); 1724 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType()); 1725 reportTranslationError(*MF, *TPC, *ORE, R); 1726 return false; 1727 } 1728 1729 auto ArgIt = F.arg_begin(); 1730 for (auto &VArg : VRegArgs) { 1731 // If the argument is an unsplit scalar then don't use unpackRegs to avoid 1732 // creating redundant copies. 1733 if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) { 1734 auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt)); 1735 assert(VRegs.empty() && "VRegs already populated?"); 1736 VRegs.push_back(VArg); 1737 } else { 1738 unpackRegs(*ArgIt, VArg, EntryBuilder); 1739 } 1740 ArgIt++; 1741 } 1742 1743 // Need to visit defs before uses when translating instructions. 1744 { 1745 ReversePostOrderTraversal<const Function *> RPOT(&F); 1746 #ifndef NDEBUG 1747 DILocationVerifier Verifier(*MF); 1748 #endif // ifndef NDEBUG 1749 for (const BasicBlock *BB : RPOT) { 1750 MachineBasicBlock &MBB = getMBB(*BB); 1751 // Set the insertion point of all the following translations to 1752 // the end of this basic block. 1753 CurBuilder.setMBB(MBB); 1754 1755 for (const Instruction &Inst : *BB) { 1756 #ifndef NDEBUG 1757 Verifier.setCurrentInst(&Inst); 1758 #endif // ifndef NDEBUG 1759 if (translate(Inst)) 1760 continue; 1761 1762 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1763 Inst.getDebugLoc(), BB); 1764 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst); 1765 1766 if (ORE->allowExtraAnalysis("gisel-irtranslator")) { 1767 std::string InstStrStorage; 1768 raw_string_ostream InstStr(InstStrStorage); 1769 InstStr << Inst; 1770 1771 R << ": '" << InstStr.str() << "'"; 1772 } 1773 1774 reportTranslationError(*MF, *TPC, *ORE, R); 1775 return false; 1776 } 1777 } 1778 } 1779 1780 finishPendingPhis(); 1781 1782 // Merge the argument lowering and constants block with its single 1783 // successor, the LLVM-IR entry block. We want the basic block to 1784 // be maximal. 1785 assert(EntryBB->succ_size() == 1 && 1786 "Custom BB used for lowering should have only one successor"); 1787 // Get the successor of the current entry block. 1788 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin(); 1789 assert(NewEntryBB.pred_size() == 1 && 1790 "LLVM-IR entry block has a predecessor!?"); 1791 // Move all the instruction from the current entry block to the 1792 // new entry block. 1793 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(), 1794 EntryBB->end()); 1795 1796 // Update the live-in information for the new entry block. 1797 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins()) 1798 NewEntryBB.addLiveIn(LiveIn); 1799 NewEntryBB.sortUniqueLiveIns(); 1800 1801 // Get rid of the now empty basic block. 1802 EntryBB->removeSuccessor(&NewEntryBB); 1803 MF->remove(EntryBB); 1804 MF->DeleteMachineBasicBlock(EntryBB); 1805 1806 assert(&MF->front() == &NewEntryBB && 1807 "New entry wasn't next in the list of basic block!"); 1808 1809 // Initialize stack protector information. 1810 StackProtector &SP = getAnalysis<StackProtector>(); 1811 SP.copyToMachineFrameInfo(MF->getFrameInfo()); 1812 1813 return false; 1814 } 1815