LLVM API Documentation
00001 //===-- AArch64ConditionalCompares.cpp --- CCMP formation for AArch64 -----===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the AArch64ConditionalCompares pass which reduces 00011 // branching and code size by using the conditional compare instructions CCMP, 00012 // CCMN, and FCMP. 00013 // 00014 // The CFG transformations for forming conditional compares are very similar to 00015 // if-conversion, and this pass should run immediately before the early 00016 // if-conversion pass. 00017 // 00018 //===----------------------------------------------------------------------===// 00019 00020 #include "AArch64.h" 00021 #include "llvm/ADT/BitVector.h" 00022 #include "llvm/ADT/DepthFirstIterator.h" 00023 #include "llvm/ADT/SetVector.h" 00024 #include "llvm/ADT/SmallPtrSet.h" 00025 #include "llvm/ADT/SparseSet.h" 00026 #include "llvm/ADT/Statistic.h" 00027 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 00028 #include "llvm/CodeGen/MachineDominators.h" 00029 #include "llvm/CodeGen/MachineFunction.h" 00030 #include "llvm/CodeGen/MachineFunctionPass.h" 00031 #include "llvm/CodeGen/MachineInstrBuilder.h" 00032 #include "llvm/CodeGen/MachineLoopInfo.h" 00033 #include "llvm/CodeGen/MachineRegisterInfo.h" 00034 #include "llvm/CodeGen/MachineTraceMetrics.h" 00035 #include "llvm/CodeGen/Passes.h" 00036 #include "llvm/Support/CommandLine.h" 00037 #include "llvm/Support/Debug.h" 00038 #include "llvm/Support/raw_ostream.h" 00039 #include "llvm/Target/TargetInstrInfo.h" 00040 #include "llvm/Target/TargetRegisterInfo.h" 00041 #include "llvm/Target/TargetSubtargetInfo.h" 00042 00043 using namespace llvm; 00044 00045 #define DEBUG_TYPE "aarch64-ccmp" 00046 00047 // Absolute maximum number of instructions allowed per speculated block. 00048 // This bypasses all other heuristics, so it should be set fairly high. 00049 static cl::opt<unsigned> BlockInstrLimit( 00050 "aarch64-ccmp-limit", cl::init(30), cl::Hidden, 00051 cl::desc("Maximum number of instructions per speculated block.")); 00052 00053 // Stress testing mode - disable heuristics. 00054 static cl::opt<bool> Stress("aarch64-stress-ccmp", cl::Hidden, 00055 cl::desc("Turn all knobs to 11")); 00056 00057 STATISTIC(NumConsidered, "Number of ccmps considered"); 00058 STATISTIC(NumPhiRejs, "Number of ccmps rejected (PHI)"); 00059 STATISTIC(NumPhysRejs, "Number of ccmps rejected (Physregs)"); 00060 STATISTIC(NumPhi2Rejs, "Number of ccmps rejected (PHI2)"); 00061 STATISTIC(NumHeadBranchRejs, "Number of ccmps rejected (Head branch)"); 00062 STATISTIC(NumCmpBranchRejs, "Number of ccmps rejected (CmpBB branch)"); 00063 STATISTIC(NumCmpTermRejs, "Number of ccmps rejected (CmpBB is cbz...)"); 00064 STATISTIC(NumImmRangeRejs, "Number of ccmps rejected (Imm out of range)"); 00065 STATISTIC(NumLiveDstRejs, "Number of ccmps rejected (Cmp dest live)"); 00066 STATISTIC(NumMultNZCVUses, "Number of ccmps rejected (NZCV used)"); 00067 STATISTIC(NumUnknNZCVDefs, "Number of ccmps rejected (NZCV def unknown)"); 00068 00069 STATISTIC(NumSpeculateRejs, "Number of ccmps rejected (Can't speculate)"); 00070 00071 STATISTIC(NumConverted, "Number of ccmp instructions created"); 00072 STATISTIC(NumCompBranches, "Number of cbz/cbnz branches converted"); 00073 00074 //===----------------------------------------------------------------------===// 00075 // SSACCmpConv 00076 //===----------------------------------------------------------------------===// 00077 // 00078 // The SSACCmpConv class performs ccmp-conversion on SSA form machine code 00079 // after determining if it is possible. The class contains no heuristics; 00080 // external code should be used to determine when ccmp-conversion is a good 00081 // idea. 00082 // 00083 // CCmp-formation works on a CFG representing chained conditions, typically 00084 // from C's short-circuit || and && operators: 00085 // 00086 // From: Head To: Head 00087 // / | CmpBB 00088 // / | / | 00089 // | CmpBB / | 00090 // | / | Tail | 00091 // | / | | | 00092 // Tail | | | 00093 // | | | | 00094 // ... ... ... ... 00095 // 00096 // The Head block is terminated by a br.cond instruction, and the CmpBB block 00097 // contains compare + br.cond. Tail must be a successor of both. 00098 // 00099 // The cmp-conversion turns the compare instruction in CmpBB into a conditional 00100 // compare, and merges CmpBB into Head, speculatively executing its 00101 // instructions. The AArch64 conditional compare instructions have an immediate 00102 // operand that specifies the NZCV flag values when the condition is false and 00103 // the compare isn't executed. This makes it possible to chain compares with 00104 // different condition codes. 00105 // 00106 // Example: 00107 // 00108 // if (a == 5 || b == 17) 00109 // foo(); 00110 // 00111 // Head: 00112 // cmp w0, #5 00113 // b.eq Tail 00114 // CmpBB: 00115 // cmp w1, #17 00116 // b.eq Tail 00117 // ... 00118 // Tail: 00119 // bl _foo 00120 // 00121 // Becomes: 00122 // 00123 // Head: 00124 // cmp w0, #5 00125 // ccmp w1, #17, 4, ne ; 4 = nZcv 00126 // b.eq Tail 00127 // ... 00128 // Tail: 00129 // bl _foo 00130 // 00131 // The ccmp condition code is the one that would cause the Head terminator to 00132 // branch to CmpBB. 00133 // 00134 // FIXME: It should also be possible to speculate a block on the critical edge 00135 // between Head and Tail, just like if-converting a diamond. 00136 // 00137 // FIXME: Handle PHIs in Tail by turning them into selects (if-conversion). 00138 00139 namespace { 00140 class SSACCmpConv { 00141 MachineFunction *MF; 00142 const TargetInstrInfo *TII; 00143 const TargetRegisterInfo *TRI; 00144 MachineRegisterInfo *MRI; 00145 00146 public: 00147 /// The first block containing a conditional branch, dominating everything 00148 /// else. 00149 MachineBasicBlock *Head; 00150 00151 /// The block containing cmp+br.cond with a successor shared with Head. 00152 MachineBasicBlock *CmpBB; 00153 00154 /// The common successor for Head and CmpBB. 00155 MachineBasicBlock *Tail; 00156 00157 /// The compare instruction in CmpBB that can be converted to a ccmp. 00158 MachineInstr *CmpMI; 00159 00160 private: 00161 /// The branch condition in Head as determined by AnalyzeBranch. 00162 SmallVector<MachineOperand, 4> HeadCond; 00163 00164 /// The condition code that makes Head branch to CmpBB. 00165 AArch64CC::CondCode HeadCmpBBCC; 00166 00167 /// The branch condition in CmpBB. 00168 SmallVector<MachineOperand, 4> CmpBBCond; 00169 00170 /// The condition code that makes CmpBB branch to Tail. 00171 AArch64CC::CondCode CmpBBTailCC; 00172 00173 /// Check if the Tail PHIs are trivially convertible. 00174 bool trivialTailPHIs(); 00175 00176 /// Remove CmpBB from the Tail PHIs. 00177 void updateTailPHIs(); 00178 00179 /// Check if an operand defining DstReg is dead. 00180 bool isDeadDef(unsigned DstReg); 00181 00182 /// Find the compare instruction in MBB that controls the conditional branch. 00183 /// Return NULL if a convertible instruction can't be found. 00184 MachineInstr *findConvertibleCompare(MachineBasicBlock *MBB); 00185 00186 /// Return true if all non-terminator instructions in MBB can be safely 00187 /// speculated. 00188 bool canSpeculateInstrs(MachineBasicBlock *MBB, const MachineInstr *CmpMI); 00189 00190 public: 00191 /// runOnMachineFunction - Initialize per-function data structures. 00192 void runOnMachineFunction(MachineFunction &MF) { 00193 this->MF = &MF; 00194 TII = MF.getSubtarget().getInstrInfo(); 00195 TRI = MF.getSubtarget().getRegisterInfo(); 00196 MRI = &MF.getRegInfo(); 00197 } 00198 00199 /// If the sub-CFG headed by MBB can be cmp-converted, initialize the 00200 /// internal state, and return true. 00201 bool canConvert(MachineBasicBlock *MBB); 00202 00203 /// Cmo-convert the last block passed to canConvertCmp(), assuming 00204 /// it is possible. Add any erased blocks to RemovedBlocks. 00205 void convert(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks); 00206 00207 /// Return the expected code size delta if the conversion into a 00208 /// conditional compare is performed. 00209 int expectedCodeSizeDelta() const; 00210 }; 00211 } // end anonymous namespace 00212 00213 // Check that all PHIs in Tail are selecting the same value from Head and CmpBB. 00214 // This means that no if-conversion is required when merging CmpBB into Head. 00215 bool SSACCmpConv::trivialTailPHIs() { 00216 for (auto &I : *Tail) { 00217 if (!I.isPHI()) 00218 break; 00219 unsigned HeadReg = 0, CmpBBReg = 0; 00220 // PHI operands come in (VReg, MBB) pairs. 00221 for (unsigned oi = 1, oe = I.getNumOperands(); oi != oe; oi += 2) { 00222 MachineBasicBlock *MBB = I.getOperand(oi + 1).getMBB(); 00223 unsigned Reg = I.getOperand(oi).getReg(); 00224 if (MBB == Head) { 00225 assert((!HeadReg || HeadReg == Reg) && "Inconsistent PHI operands"); 00226 HeadReg = Reg; 00227 } 00228 if (MBB == CmpBB) { 00229 assert((!CmpBBReg || CmpBBReg == Reg) && "Inconsistent PHI operands"); 00230 CmpBBReg = Reg; 00231 } 00232 } 00233 if (HeadReg != CmpBBReg) 00234 return false; 00235 } 00236 return true; 00237 } 00238 00239 // Assuming that trivialTailPHIs() is true, update the Tail PHIs by simply 00240 // removing the CmpBB operands. The Head operands will be identical. 00241 void SSACCmpConv::updateTailPHIs() { 00242 for (auto &I : *Tail) { 00243 if (!I.isPHI()) 00244 break; 00245 // I is a PHI. It can have multiple entries for CmpBB. 00246 for (unsigned oi = I.getNumOperands(); oi > 2; oi -= 2) { 00247 // PHI operands are (Reg, MBB) at (oi-2, oi-1). 00248 if (I.getOperand(oi - 1).getMBB() == CmpBB) { 00249 I.RemoveOperand(oi - 1); 00250 I.RemoveOperand(oi - 2); 00251 } 00252 } 00253 } 00254 } 00255 00256 // This pass runs before the AArch64DeadRegisterDefinitions pass, so compares 00257 // are still writing virtual registers without any uses. 00258 bool SSACCmpConv::isDeadDef(unsigned DstReg) { 00259 // Writes to the zero register are dead. 00260 if (DstReg == AArch64::WZR || DstReg == AArch64::XZR) 00261 return true; 00262 if (!TargetRegisterInfo::isVirtualRegister(DstReg)) 00263 return false; 00264 // A virtual register def without any uses will be marked dead later, and 00265 // eventually replaced by the zero register. 00266 return MRI->use_nodbg_empty(DstReg); 00267 } 00268 00269 // Parse a condition code returned by AnalyzeBranch, and compute the CondCode 00270 // corresponding to TBB. 00271 // Return 00272 static bool parseCond(ArrayRef<MachineOperand> Cond, AArch64CC::CondCode &CC) { 00273 // A normal br.cond simply has the condition code. 00274 if (Cond[0].getImm() != -1) { 00275 assert(Cond.size() == 1 && "Unknown Cond array format"); 00276 CC = (AArch64CC::CondCode)(int)Cond[0].getImm(); 00277 return true; 00278 } 00279 // For tbz and cbz instruction, the opcode is next. 00280 switch (Cond[1].getImm()) { 00281 default: 00282 // This includes tbz / tbnz branches which can't be converted to 00283 // ccmp + br.cond. 00284 return false; 00285 case AArch64::CBZW: 00286 case AArch64::CBZX: 00287 assert(Cond.size() == 3 && "Unknown Cond array format"); 00288 CC = AArch64CC::EQ; 00289 return true; 00290 case AArch64::CBNZW: 00291 case AArch64::CBNZX: 00292 assert(Cond.size() == 3 && "Unknown Cond array format"); 00293 CC = AArch64CC::NE; 00294 return true; 00295 } 00296 } 00297 00298 MachineInstr *SSACCmpConv::findConvertibleCompare(MachineBasicBlock *MBB) { 00299 MachineBasicBlock::iterator I = MBB->getFirstTerminator(); 00300 if (I == MBB->end()) 00301 return nullptr; 00302 // The terminator must be controlled by the flags. 00303 if (!I->readsRegister(AArch64::NZCV)) { 00304 switch (I->getOpcode()) { 00305 case AArch64::CBZW: 00306 case AArch64::CBZX: 00307 case AArch64::CBNZW: 00308 case AArch64::CBNZX: 00309 // These can be converted into a ccmp against #0. 00310 return I; 00311 } 00312 ++NumCmpTermRejs; 00313 DEBUG(dbgs() << "Flags not used by terminator: " << *I); 00314 return nullptr; 00315 } 00316 00317 // Now find the instruction controlling the terminator. 00318 for (MachineBasicBlock::iterator B = MBB->begin(); I != B;) { 00319 --I; 00320 assert(!I->isTerminator() && "Spurious terminator"); 00321 switch (I->getOpcode()) { 00322 // cmp is an alias for subs with a dead destination register. 00323 case AArch64::SUBSWri: 00324 case AArch64::SUBSXri: 00325 // cmn is an alias for adds with a dead destination register. 00326 case AArch64::ADDSWri: 00327 case AArch64::ADDSXri: 00328 // Check that the immediate operand is within range, ccmp wants a uimm5. 00329 // Rd = SUBSri Rn, imm, shift 00330 if (I->getOperand(3).getImm() || !isUInt<5>(I->getOperand(2).getImm())) { 00331 DEBUG(dbgs() << "Immediate out of range for ccmp: " << *I); 00332 ++NumImmRangeRejs; 00333 return nullptr; 00334 } 00335 // Fall through. 00336 case AArch64::SUBSWrr: 00337 case AArch64::SUBSXrr: 00338 case AArch64::ADDSWrr: 00339 case AArch64::ADDSXrr: 00340 if (isDeadDef(I->getOperand(0).getReg())) 00341 return I; 00342 DEBUG(dbgs() << "Can't convert compare with live destination: " << *I); 00343 ++NumLiveDstRejs; 00344 return nullptr; 00345 case AArch64::FCMPSrr: 00346 case AArch64::FCMPDrr: 00347 case AArch64::FCMPESrr: 00348 case AArch64::FCMPEDrr: 00349 return I; 00350 } 00351 00352 // Check for flag reads and clobbers. 00353 MIOperands::PhysRegInfo PRI = 00354 MIOperands(I).analyzePhysReg(AArch64::NZCV, TRI); 00355 00356 if (PRI.Reads) { 00357 // The ccmp doesn't produce exactly the same flags as the original 00358 // compare, so reject the transform if there are uses of the flags 00359 // besides the terminators. 00360 DEBUG(dbgs() << "Can't create ccmp with multiple uses: " << *I); 00361 ++NumMultNZCVUses; 00362 return nullptr; 00363 } 00364 00365 if (PRI.Clobbers) { 00366 DEBUG(dbgs() << "Not convertible compare: " << *I); 00367 ++NumUnknNZCVDefs; 00368 return nullptr; 00369 } 00370 } 00371 DEBUG(dbgs() << "Flags not defined in BB#" << MBB->getNumber() << '\n'); 00372 return nullptr; 00373 } 00374 00375 /// Determine if all the instructions in MBB can safely 00376 /// be speculated. The terminators are not considered. 00377 /// 00378 /// Only CmpMI is allowed to clobber the flags. 00379 /// 00380 bool SSACCmpConv::canSpeculateInstrs(MachineBasicBlock *MBB, 00381 const MachineInstr *CmpMI) { 00382 // Reject any live-in physregs. It's probably NZCV/EFLAGS, and very hard to 00383 // get right. 00384 if (!MBB->livein_empty()) { 00385 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n"); 00386 return false; 00387 } 00388 00389 unsigned InstrCount = 0; 00390 00391 // Check all instructions, except the terminators. It is assumed that 00392 // terminators never have side effects or define any used register values. 00393 for (auto &I : make_range(MBB->begin(), MBB->getFirstTerminator())) { 00394 if (I.isDebugValue()) 00395 continue; 00396 00397 if (++InstrCount > BlockInstrLimit && !Stress) { 00398 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than " 00399 << BlockInstrLimit << " instructions.\n"); 00400 return false; 00401 } 00402 00403 // There shouldn't normally be any phis in a single-predecessor block. 00404 if (I.isPHI()) { 00405 DEBUG(dbgs() << "Can't hoist: " << I); 00406 return false; 00407 } 00408 00409 // Don't speculate loads. Note that it may be possible and desirable to 00410 // speculate GOT or constant pool loads that are guaranteed not to trap, 00411 // but we don't support that for now. 00412 if (I.mayLoad()) { 00413 DEBUG(dbgs() << "Won't speculate load: " << I); 00414 return false; 00415 } 00416 00417 // We never speculate stores, so an AA pointer isn't necessary. 00418 bool DontMoveAcrossStore = true; 00419 if (!I.isSafeToMove(TII, nullptr, DontMoveAcrossStore)) { 00420 DEBUG(dbgs() << "Can't speculate: " << I); 00421 return false; 00422 } 00423 00424 // Only CmpMI is allowed to clobber the flags. 00425 if (&I != CmpMI && I.modifiesRegister(AArch64::NZCV, TRI)) { 00426 DEBUG(dbgs() << "Clobbers flags: " << I); 00427 return false; 00428 } 00429 } 00430 return true; 00431 } 00432 00433 /// Analyze the sub-cfg rooted in MBB, and return true if it is a potential 00434 /// candidate for cmp-conversion. Fill out the internal state. 00435 /// 00436 bool SSACCmpConv::canConvert(MachineBasicBlock *MBB) { 00437 Head = MBB; 00438 Tail = CmpBB = nullptr; 00439 00440 if (Head->succ_size() != 2) 00441 return false; 00442 MachineBasicBlock *Succ0 = Head->succ_begin()[0]; 00443 MachineBasicBlock *Succ1 = Head->succ_begin()[1]; 00444 00445 // CmpBB can only have a single predecessor. Tail is allowed many. 00446 if (Succ0->pred_size() != 1) 00447 std::swap(Succ0, Succ1); 00448 00449 // Succ0 is our candidate for CmpBB. 00450 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 2) 00451 return false; 00452 00453 CmpBB = Succ0; 00454 Tail = Succ1; 00455 00456 if (!CmpBB->isSuccessor(Tail)) 00457 return false; 00458 00459 // The CFG topology checks out. 00460 DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber() << " -> BB#" 00461 << CmpBB->getNumber() << " -> BB#" << Tail->getNumber() << '\n'); 00462 ++NumConsidered; 00463 00464 // Tail is allowed to have many predecessors, but we can't handle PHIs yet. 00465 // 00466 // FIXME: Real PHIs could be if-converted as long as the CmpBB values are 00467 // defined before The CmpBB cmp clobbers the flags. Alternatively, it should 00468 // always be safe to sink the ccmp down to immediately before the CmpBB 00469 // terminators. 00470 if (!trivialTailPHIs()) { 00471 DEBUG(dbgs() << "Can't handle phis in Tail.\n"); 00472 ++NumPhiRejs; 00473 return false; 00474 } 00475 00476 if (!Tail->livein_empty()) { 00477 DEBUG(dbgs() << "Can't handle live-in physregs in Tail.\n"); 00478 ++NumPhysRejs; 00479 return false; 00480 } 00481 00482 // CmpBB should never have PHIs since Head is its only predecessor. 00483 // FIXME: Clean them up if it happens. 00484 if (!CmpBB->empty() && CmpBB->front().isPHI()) { 00485 DEBUG(dbgs() << "Can't handle phis in CmpBB.\n"); 00486 ++NumPhi2Rejs; 00487 return false; 00488 } 00489 00490 if (!CmpBB->livein_empty()) { 00491 DEBUG(dbgs() << "Can't handle live-in physregs in CmpBB.\n"); 00492 ++NumPhysRejs; 00493 return false; 00494 } 00495 00496 // The branch we're looking to eliminate must be analyzable. 00497 HeadCond.clear(); 00498 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 00499 if (TII->AnalyzeBranch(*Head, TBB, FBB, HeadCond)) { 00500 DEBUG(dbgs() << "Head branch not analyzable.\n"); 00501 ++NumHeadBranchRejs; 00502 return false; 00503 } 00504 00505 // This is weird, probably some sort of degenerate CFG, or an edge to a 00506 // landing pad. 00507 if (!TBB || HeadCond.empty()) { 00508 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch in Head.\n"); 00509 ++NumHeadBranchRejs; 00510 return false; 00511 } 00512 00513 if (!parseCond(HeadCond, HeadCmpBBCC)) { 00514 DEBUG(dbgs() << "Unsupported branch type on Head\n"); 00515 ++NumHeadBranchRejs; 00516 return false; 00517 } 00518 00519 // Make sure the branch direction is right. 00520 if (TBB != CmpBB) { 00521 assert(TBB == Tail && "Unexpected TBB"); 00522 HeadCmpBBCC = AArch64CC::getInvertedCondCode(HeadCmpBBCC); 00523 } 00524 00525 CmpBBCond.clear(); 00526 TBB = FBB = nullptr; 00527 if (TII->AnalyzeBranch(*CmpBB, TBB, FBB, CmpBBCond)) { 00528 DEBUG(dbgs() << "CmpBB branch not analyzable.\n"); 00529 ++NumCmpBranchRejs; 00530 return false; 00531 } 00532 00533 if (!TBB || CmpBBCond.empty()) { 00534 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch in CmpBB.\n"); 00535 ++NumCmpBranchRejs; 00536 return false; 00537 } 00538 00539 if (!parseCond(CmpBBCond, CmpBBTailCC)) { 00540 DEBUG(dbgs() << "Unsupported branch type on CmpBB\n"); 00541 ++NumCmpBranchRejs; 00542 return false; 00543 } 00544 00545 if (TBB != Tail) 00546 CmpBBTailCC = AArch64CC::getInvertedCondCode(CmpBBTailCC); 00547 00548 DEBUG(dbgs() << "Head->CmpBB on " << AArch64CC::getCondCodeName(HeadCmpBBCC) 00549 << ", CmpBB->Tail on " << AArch64CC::getCondCodeName(CmpBBTailCC) 00550 << '\n'); 00551 00552 CmpMI = findConvertibleCompare(CmpBB); 00553 if (!CmpMI) 00554 return false; 00555 00556 if (!canSpeculateInstrs(CmpBB, CmpMI)) { 00557 ++NumSpeculateRejs; 00558 return false; 00559 } 00560 return true; 00561 } 00562 00563 void SSACCmpConv::convert(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks) { 00564 DEBUG(dbgs() << "Merging BB#" << CmpBB->getNumber() << " into BB#" 00565 << Head->getNumber() << ":\n" << *CmpBB); 00566 00567 // All CmpBB instructions are moved into Head, and CmpBB is deleted. 00568 // Update the CFG first. 00569 updateTailPHIs(); 00570 Head->removeSuccessor(CmpBB); 00571 CmpBB->removeSuccessor(Tail); 00572 Head->transferSuccessorsAndUpdatePHIs(CmpBB); 00573 DebugLoc TermDL = Head->getFirstTerminator()->getDebugLoc(); 00574 TII->RemoveBranch(*Head); 00575 00576 // If the Head terminator was one of the cbz / tbz branches with built-in 00577 // compare, we need to insert an explicit compare instruction in its place. 00578 if (HeadCond[0].getImm() == -1) { 00579 ++NumCompBranches; 00580 unsigned Opc = 0; 00581 switch (HeadCond[1].getImm()) { 00582 case AArch64::CBZW: 00583 case AArch64::CBNZW: 00584 Opc = AArch64::SUBSWri; 00585 break; 00586 case AArch64::CBZX: 00587 case AArch64::CBNZX: 00588 Opc = AArch64::SUBSXri; 00589 break; 00590 default: 00591 llvm_unreachable("Cannot convert Head branch"); 00592 } 00593 const MCInstrDesc &MCID = TII->get(Opc); 00594 // Create a dummy virtual register for the SUBS def. 00595 unsigned DestReg = 00596 MRI->createVirtualRegister(TII->getRegClass(MCID, 0, TRI, *MF)); 00597 // Insert a SUBS Rn, #0 instruction instead of the cbz / cbnz. 00598 BuildMI(*Head, Head->end(), TermDL, MCID) 00599 .addReg(DestReg, RegState::Define | RegState::Dead) 00600 .addOperand(HeadCond[2]) 00601 .addImm(0) 00602 .addImm(0); 00603 // SUBS uses the GPR*sp register classes. 00604 MRI->constrainRegClass(HeadCond[2].getReg(), 00605 TII->getRegClass(MCID, 1, TRI, *MF)); 00606 } 00607 00608 Head->splice(Head->end(), CmpBB, CmpBB->begin(), CmpBB->end()); 00609 00610 // Now replace CmpMI with a ccmp instruction that also considers the incoming 00611 // flags. 00612 unsigned Opc = 0; 00613 unsigned FirstOp = 1; // First CmpMI operand to copy. 00614 bool isZBranch = false; // CmpMI is a cbz/cbnz instruction. 00615 switch (CmpMI->getOpcode()) { 00616 default: 00617 llvm_unreachable("Unknown compare opcode"); 00618 case AArch64::SUBSWri: Opc = AArch64::CCMPWi; break; 00619 case AArch64::SUBSWrr: Opc = AArch64::CCMPWr; break; 00620 case AArch64::SUBSXri: Opc = AArch64::CCMPXi; break; 00621 case AArch64::SUBSXrr: Opc = AArch64::CCMPXr; break; 00622 case AArch64::ADDSWri: Opc = AArch64::CCMNWi; break; 00623 case AArch64::ADDSWrr: Opc = AArch64::CCMNWr; break; 00624 case AArch64::ADDSXri: Opc = AArch64::CCMNXi; break; 00625 case AArch64::ADDSXrr: Opc = AArch64::CCMNXr; break; 00626 case AArch64::FCMPSrr: Opc = AArch64::FCCMPSrr; FirstOp = 0; break; 00627 case AArch64::FCMPDrr: Opc = AArch64::FCCMPDrr; FirstOp = 0; break; 00628 case AArch64::FCMPESrr: Opc = AArch64::FCCMPESrr; FirstOp = 0; break; 00629 case AArch64::FCMPEDrr: Opc = AArch64::FCCMPEDrr; FirstOp = 0; break; 00630 case AArch64::CBZW: 00631 case AArch64::CBNZW: 00632 Opc = AArch64::CCMPWi; 00633 FirstOp = 0; 00634 isZBranch = true; 00635 break; 00636 case AArch64::CBZX: 00637 case AArch64::CBNZX: 00638 Opc = AArch64::CCMPXi; 00639 FirstOp = 0; 00640 isZBranch = true; 00641 break; 00642 } 00643 00644 // The ccmp instruction should set the flags according to the comparison when 00645 // Head would have branched to CmpBB. 00646 // The NZCV immediate operand should provide flags for the case where Head 00647 // would have branched to Tail. These flags should cause the new Head 00648 // terminator to branch to tail. 00649 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(CmpBBTailCC); 00650 const MCInstrDesc &MCID = TII->get(Opc); 00651 MRI->constrainRegClass(CmpMI->getOperand(FirstOp).getReg(), 00652 TII->getRegClass(MCID, 0, TRI, *MF)); 00653 if (CmpMI->getOperand(FirstOp + 1).isReg()) 00654 MRI->constrainRegClass(CmpMI->getOperand(FirstOp + 1).getReg(), 00655 TII->getRegClass(MCID, 1, TRI, *MF)); 00656 MachineInstrBuilder MIB = 00657 BuildMI(*Head, CmpMI, CmpMI->getDebugLoc(), MCID) 00658 .addOperand(CmpMI->getOperand(FirstOp)); // Register Rn 00659 if (isZBranch) 00660 MIB.addImm(0); // cbz/cbnz Rn -> ccmp Rn, #0 00661 else 00662 MIB.addOperand(CmpMI->getOperand(FirstOp + 1)); // Register Rm / Immediate 00663 MIB.addImm(NZCV).addImm(HeadCmpBBCC); 00664 00665 // If CmpMI was a terminator, we need a new conditional branch to replace it. 00666 // This now becomes a Head terminator. 00667 if (isZBranch) { 00668 bool isNZ = CmpMI->getOpcode() == AArch64::CBNZW || 00669 CmpMI->getOpcode() == AArch64::CBNZX; 00670 BuildMI(*Head, CmpMI, CmpMI->getDebugLoc(), TII->get(AArch64::Bcc)) 00671 .addImm(isNZ ? AArch64CC::NE : AArch64CC::EQ) 00672 .addOperand(CmpMI->getOperand(1)); // Branch target. 00673 } 00674 CmpMI->eraseFromParent(); 00675 Head->updateTerminator(); 00676 00677 RemovedBlocks.push_back(CmpBB); 00678 CmpBB->eraseFromParent(); 00679 DEBUG(dbgs() << "Result:\n" << *Head); 00680 ++NumConverted; 00681 } 00682 00683 int SSACCmpConv::expectedCodeSizeDelta() const { 00684 int delta = 0; 00685 // If the Head terminator was one of the cbz / tbz branches with built-in 00686 // compare, we need to insert an explicit compare instruction in its place 00687 // plus a branch instruction. 00688 if (HeadCond[0].getImm() == -1) { 00689 switch (HeadCond[1].getImm()) { 00690 case AArch64::CBZW: 00691 case AArch64::CBNZW: 00692 case AArch64::CBZX: 00693 case AArch64::CBNZX: 00694 // Therefore delta += 1 00695 delta = 1; 00696 break; 00697 default: 00698 llvm_unreachable("Cannot convert Head branch"); 00699 } 00700 } 00701 // If the Cmp terminator was one of the cbz / tbz branches with 00702 // built-in compare, it will be turned into a compare instruction 00703 // into Head, but we do not save any instruction. 00704 // Otherwise, we save the branch instruction. 00705 switch (CmpMI->getOpcode()) { 00706 default: 00707 --delta; 00708 break; 00709 case AArch64::CBZW: 00710 case AArch64::CBNZW: 00711 case AArch64::CBZX: 00712 case AArch64::CBNZX: 00713 break; 00714 } 00715 return delta; 00716 } 00717 00718 //===----------------------------------------------------------------------===// 00719 // AArch64ConditionalCompares Pass 00720 //===----------------------------------------------------------------------===// 00721 00722 namespace { 00723 class AArch64ConditionalCompares : public MachineFunctionPass { 00724 const TargetInstrInfo *TII; 00725 const TargetRegisterInfo *TRI; 00726 MCSchedModel SchedModel; 00727 // Does the proceeded function has Oz attribute. 00728 bool MinSize; 00729 MachineRegisterInfo *MRI; 00730 MachineDominatorTree *DomTree; 00731 MachineLoopInfo *Loops; 00732 MachineTraceMetrics *Traces; 00733 MachineTraceMetrics::Ensemble *MinInstr; 00734 SSACCmpConv CmpConv; 00735 00736 public: 00737 static char ID; 00738 AArch64ConditionalCompares() : MachineFunctionPass(ID) {} 00739 void getAnalysisUsage(AnalysisUsage &AU) const override; 00740 bool runOnMachineFunction(MachineFunction &MF) override; 00741 const char *getPassName() const override { 00742 return "AArch64 Conditional Compares"; 00743 } 00744 00745 private: 00746 bool tryConvert(MachineBasicBlock *); 00747 void updateDomTree(ArrayRef<MachineBasicBlock *> Removed); 00748 void updateLoops(ArrayRef<MachineBasicBlock *> Removed); 00749 void invalidateTraces(); 00750 bool shouldConvert(); 00751 }; 00752 } // end anonymous namespace 00753 00754 char AArch64ConditionalCompares::ID = 0; 00755 00756 namespace llvm { 00757 void initializeAArch64ConditionalComparesPass(PassRegistry &); 00758 } 00759 00760 INITIALIZE_PASS_BEGIN(AArch64ConditionalCompares, "aarch64-ccmp", 00761 "AArch64 CCMP Pass", false, false) 00762 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 00763 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 00764 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics) 00765 INITIALIZE_PASS_END(AArch64ConditionalCompares, "aarch64-ccmp", 00766 "AArch64 CCMP Pass", false, false) 00767 00768 FunctionPass *llvm::createAArch64ConditionalCompares() { 00769 return new AArch64ConditionalCompares(); 00770 } 00771 00772 void AArch64ConditionalCompares::getAnalysisUsage(AnalysisUsage &AU) const { 00773 AU.addRequired<MachineBranchProbabilityInfo>(); 00774 AU.addRequired<MachineDominatorTree>(); 00775 AU.addPreserved<MachineDominatorTree>(); 00776 AU.addRequired<MachineLoopInfo>(); 00777 AU.addPreserved<MachineLoopInfo>(); 00778 AU.addRequired<MachineTraceMetrics>(); 00779 AU.addPreserved<MachineTraceMetrics>(); 00780 MachineFunctionPass::getAnalysisUsage(AU); 00781 } 00782 00783 /// Update the dominator tree after if-conversion erased some blocks. 00784 void AArch64ConditionalCompares::updateDomTree( 00785 ArrayRef<MachineBasicBlock *> Removed) { 00786 // convert() removes CmpBB which was previously dominated by Head. 00787 // CmpBB children should be transferred to Head. 00788 MachineDomTreeNode *HeadNode = DomTree->getNode(CmpConv.Head); 00789 for (unsigned i = 0, e = Removed.size(); i != e; ++i) { 00790 MachineDomTreeNode *Node = DomTree->getNode(Removed[i]); 00791 assert(Node != HeadNode && "Cannot erase the head node"); 00792 assert(Node->getIDom() == HeadNode && "CmpBB should be dominated by Head"); 00793 while (Node->getNumChildren()) 00794 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode); 00795 DomTree->eraseNode(Removed[i]); 00796 } 00797 } 00798 00799 /// Update LoopInfo after if-conversion. 00800 void 00801 AArch64ConditionalCompares::updateLoops(ArrayRef<MachineBasicBlock *> Removed) { 00802 if (!Loops) 00803 return; 00804 for (unsigned i = 0, e = Removed.size(); i != e; ++i) 00805 Loops->removeBlock(Removed[i]); 00806 } 00807 00808 /// Invalidate MachineTraceMetrics before if-conversion. 00809 void AArch64ConditionalCompares::invalidateTraces() { 00810 Traces->invalidate(CmpConv.Head); 00811 Traces->invalidate(CmpConv.CmpBB); 00812 } 00813 00814 /// Apply cost model and heuristics to the if-conversion in IfConv. 00815 /// Return true if the conversion is a good idea. 00816 /// 00817 bool AArch64ConditionalCompares::shouldConvert() { 00818 // Stress testing mode disables all cost considerations. 00819 if (Stress) 00820 return true; 00821 if (!MinInstr) 00822 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount); 00823 00824 // Head dominates CmpBB, so it is always included in its trace. 00825 MachineTraceMetrics::Trace Trace = MinInstr->getTrace(CmpConv.CmpBB); 00826 00827 // If code size is the main concern 00828 if (MinSize) { 00829 int CodeSizeDelta = CmpConv.expectedCodeSizeDelta(); 00830 DEBUG(dbgs() << "Code size delta: " << CodeSizeDelta << '\n'); 00831 // If we are minimizing the code size, do the conversion whatever 00832 // the cost is. 00833 if (CodeSizeDelta < 0) 00834 return true; 00835 if (CodeSizeDelta > 0) { 00836 DEBUG(dbgs() << "Code size is increasing, give up on this one.\n"); 00837 return false; 00838 } 00839 // CodeSizeDelta == 0, continue with the regular heuristics 00840 } 00841 00842 // Heuristic: The compare conversion delays the execution of the branch 00843 // instruction because we must wait for the inputs to the second compare as 00844 // well. The branch has no dependent instructions, but delaying it increases 00845 // the cost of a misprediction. 00846 // 00847 // Set a limit on the delay we will accept. 00848 unsigned DelayLimit = SchedModel.MispredictPenalty * 3 / 4; 00849 00850 // Instruction depths can be computed for all trace instructions above CmpBB. 00851 unsigned HeadDepth = 00852 Trace.getInstrCycles(CmpConv.Head->getFirstTerminator()).Depth; 00853 unsigned CmpBBDepth = 00854 Trace.getInstrCycles(CmpConv.CmpBB->getFirstTerminator()).Depth; 00855 DEBUG(dbgs() << "Head depth: " << HeadDepth 00856 << "\nCmpBB depth: " << CmpBBDepth << '\n'); 00857 if (CmpBBDepth > HeadDepth + DelayLimit) { 00858 DEBUG(dbgs() << "Branch delay would be larger than " << DelayLimit 00859 << " cycles.\n"); 00860 return false; 00861 } 00862 00863 // Check the resource depth at the bottom of CmpBB - these instructions will 00864 // be speculated. 00865 unsigned ResDepth = Trace.getResourceDepth(true); 00866 DEBUG(dbgs() << "Resources: " << ResDepth << '\n'); 00867 00868 // Heuristic: The speculatively executed instructions must all be able to 00869 // merge into the Head block. The Head critical path should dominate the 00870 // resource cost of the speculated instructions. 00871 if (ResDepth > HeadDepth) { 00872 DEBUG(dbgs() << "Too many instructions to speculate.\n"); 00873 return false; 00874 } 00875 return true; 00876 } 00877 00878 bool AArch64ConditionalCompares::tryConvert(MachineBasicBlock *MBB) { 00879 bool Changed = false; 00880 while (CmpConv.canConvert(MBB) && shouldConvert()) { 00881 invalidateTraces(); 00882 SmallVector<MachineBasicBlock *, 4> RemovedBlocks; 00883 CmpConv.convert(RemovedBlocks); 00884 Changed = true; 00885 updateDomTree(RemovedBlocks); 00886 updateLoops(RemovedBlocks); 00887 } 00888 return Changed; 00889 } 00890 00891 bool AArch64ConditionalCompares::runOnMachineFunction(MachineFunction &MF) { 00892 DEBUG(dbgs() << "********** AArch64 Conditional Compares **********\n" 00893 << "********** Function: " << MF.getName() << '\n'); 00894 TII = MF.getSubtarget().getInstrInfo(); 00895 TRI = MF.getSubtarget().getRegisterInfo(); 00896 SchedModel = 00897 MF.getTarget().getSubtarget<TargetSubtargetInfo>().getSchedModel(); 00898 MRI = &MF.getRegInfo(); 00899 DomTree = &getAnalysis<MachineDominatorTree>(); 00900 Loops = getAnalysisIfAvailable<MachineLoopInfo>(); 00901 Traces = &getAnalysis<MachineTraceMetrics>(); 00902 MinInstr = nullptr; 00903 MinSize = MF.getFunction()->getAttributes().hasAttribute( 00904 AttributeSet::FunctionIndex, Attribute::MinSize); 00905 00906 bool Changed = false; 00907 CmpConv.runOnMachineFunction(MF); 00908 00909 // Visit blocks in dominator tree pre-order. The pre-order enables multiple 00910 // cmp-conversions from the same head block. 00911 // Note that updateDomTree() modifies the children of the DomTree node 00912 // currently being visited. The df_iterator supports that; it doesn't look at 00913 // child_begin() / child_end() until after a node has been visited. 00914 for (auto *I : depth_first(DomTree)) 00915 if (tryConvert(I->getBlock())) 00916 Changed = true; 00917 00918 return Changed; 00919 }