LLVM API Documentation

Thumb2SizeReduction.cpp

Go to the documentation of this file.
00001 //===-- Thumb2SizeReduction.cpp - Thumb2 code size reduction pass -*- C++ -*-=//
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 #define DEBUG_TYPE "t2-reduce-size"
00011 #include "ARM.h"
00012 #include "ARMAddressingModes.h"
00013 #include "ARMBaseRegisterInfo.h"
00014 #include "ARMBaseInstrInfo.h"
00015 #include "Thumb2InstrInfo.h"
00016 #include "llvm/CodeGen/MachineInstr.h"
00017 #include "llvm/CodeGen/MachineInstrBuilder.h"
00018 #include "llvm/CodeGen/MachineFunctionPass.h"
00019 #include "llvm/Support/CommandLine.h"
00020 #include "llvm/Support/Compiler.h"
00021 #include "llvm/Support/Debug.h"
00022 #include "llvm/ADT/DenseMap.h"
00023 #include "llvm/ADT/Statistic.h"
00024 using namespace llvm;
00025 
00026 STATISTIC(NumNarrows,  "Number of 32-bit instrs reduced to 16-bit ones");
00027 STATISTIC(Num2Addrs,   "Number of 32-bit instrs reduced to 2addr 16-bit ones");
00028 STATISTIC(NumLdSts,    "Number of 32-bit load / store reduced to 16-bit ones");
00029 
00030 static cl::opt<int> ReduceLimit("t2-reduce-limit",
00031                                 cl::init(-1), cl::Hidden);
00032 static cl::opt<int> ReduceLimit2Addr("t2-reduce-limit2",
00033                                      cl::init(-1), cl::Hidden);
00034 static cl::opt<int> ReduceLimitLdSt("t2-reduce-limit3",
00035                                      cl::init(-1), cl::Hidden);
00036 
00037 namespace {
00038   /// ReduceTable - A static table with information on mapping from wide
00039   /// opcodes to narrow
00040   struct ReduceEntry {
00041     unsigned WideOpc;      // Wide opcode
00042     unsigned NarrowOpc1;   // Narrow opcode to transform to
00043     unsigned NarrowOpc2;   // Narrow opcode when it's two-address
00044     uint8_t  Imm1Limit;    // Limit of immediate field (bits)
00045     uint8_t  Imm2Limit;    // Limit of immediate field when it's two-address
00046     unsigned LowRegs1 : 1; // Only possible if low-registers are used
00047     unsigned LowRegs2 : 1; // Only possible if low-registers are used (2addr)
00048     unsigned PredCC1  : 2; // 0 - If predicated, cc is on and vice versa.
00049                            // 1 - No cc field.
00050                            // 2 - Always set CPSR.
00051     unsigned PredCC2  : 2;
00052     unsigned Special  : 1; // Needs to be dealt with specially
00053   };
00054 
00055   static const ReduceEntry ReduceTable[] = {
00056     // Wide,        Narrow1,      Narrow2,     imm1,imm2,  lo1, lo2, P/C, S
00057     { ARM::t2ADCrr, 0,            ARM::tADC,     0,   0,    0,   1,  0,0, 0 },
00058     { ARM::t2ADDri, ARM::tADDi3,  ARM::tADDi8,   3,   8,    1,   1,  0,0, 0 },
00059     { ARM::t2ADDrr, ARM::tADDrr,  ARM::tADDhirr, 0,   0,    1,   0,  0,1, 0 },
00060     // Note: immediate scale is 4.
00061     { ARM::t2ADDrSPi,ARM::tADDrSPi,0,            8,   0,    1,   0,  1,0, 0 },
00062     { ARM::t2ADDSri,ARM::tADDi3,  ARM::tADDi8,   3,   8,    1,   1,  2,2, 1 },
00063     { ARM::t2ADDSrr,ARM::tADDrr,  0,             0,   0,    1,   0,  2,0, 1 },
00064     { ARM::t2ANDrr, 0,            ARM::tAND,     0,   0,    0,   1,  0,0, 0 },
00065     { ARM::t2ASRri, ARM::tASRri,  0,             5,   0,    1,   0,  0,0, 0 },
00066     { ARM::t2ASRrr, 0,            ARM::tASRrr,   0,   0,    0,   1,  0,0, 0 },
00067     { ARM::t2BICrr, 0,            ARM::tBIC,     0,   0,    0,   1,  0,0, 0 },
00068     { ARM::t2CMNrr, ARM::tCMN,    0,             0,   0,    1,   0,  2,0, 0 },
00069     { ARM::t2CMPri, ARM::tCMPi8,  0,             8,   0,    1,   0,  2,0, 0 },
00070     { ARM::t2CMPrr, ARM::tCMPhir, 0,             0,   0,    0,   0,  2,0, 0 },
00071     { ARM::t2CMPzri,ARM::tCMPzi8, 0,             8,   0,    1,   0,  2,0, 0 },
00072     { ARM::t2CMPzrr,ARM::tCMPzhir,0,             0,   0,    0,   0,  2,0, 0 },
00073     { ARM::t2EORrr, 0,            ARM::tEOR,     0,   0,    0,   1,  0,0, 0 },
00074     // FIXME: adr.n immediate offset must be multiple of 4.
00075     //{ ARM::t2LEApcrelJT,ARM::tLEApcrelJT, 0,     0,   0,    1,   0,  1,0, 0 },
00076     { ARM::t2LSLri, ARM::tLSLri,  0,             5,   0,    1,   0,  0,0, 0 },
00077     { ARM::t2LSLrr, 0,            ARM::tLSLrr,   0,   0,    0,   1,  0,0, 0 },
00078     { ARM::t2LSRri, ARM::tLSRri,  0,             5,   0,    1,   0,  0,0, 0 },
00079     { ARM::t2LSRrr, 0,            ARM::tLSRrr,   0,   0,    0,   1,  0,0, 0 },
00080     { ARM::t2MOVi,  ARM::tMOVi8,  0,             8,   0,    1,   0,  0,0, 0 },
00081     // FIXME: Do we need the 16-bit 'S' variant?
00082     { ARM::t2MOVr,ARM::tMOVgpr2gpr,0,            0,   0,    0,   0,  1,0, 0 },
00083     { ARM::t2MOVCCr,0,            ARM::tMOVCCr,  0,   0,    0,   0,  0,1, 0 },
00084     { ARM::t2MOVCCi,0,            ARM::tMOVCCi,  0,   8,    0,   0,  0,1, 0 },
00085     { ARM::t2MUL,   0,            ARM::tMUL,     0,   0,    0,   1,  0,0, 0 },
00086     { ARM::t2MVNr,  ARM::tMVN,    0,             0,   0,    1,   0,  0,0, 0 },
00087     { ARM::t2ORRrr, 0,            ARM::tORR,     0,   0,    0,   1,  0,0, 0 },
00088     { ARM::t2REV,   ARM::tREV,    0,             0,   0,    1,   0,  1,0, 0 },
00089     { ARM::t2REV16, ARM::tREV16,  0,             0,   0,    1,   0,  1,0, 0 },
00090     { ARM::t2REVSH, ARM::tREVSH,  0,             0,   0,    1,   0,  1,0, 0 },
00091     { ARM::t2RORrr, 0,            ARM::tROR,     0,   0,    0,   1,  0,0, 0 },
00092     { ARM::t2RSBri, ARM::tRSB,    0,             0,   0,    1,   0,  0,0, 1 },
00093     { ARM::t2RSBSri,ARM::tRSB,    0,             0,   0,    1,   0,  2,0, 1 },
00094     { ARM::t2SBCrr, 0,            ARM::tSBC,     0,   0,    0,   1,  0,0, 0 },
00095     { ARM::t2SUBri, ARM::tSUBi3,  ARM::tSUBi8,   3,   8,    1,   1,  0,0, 0 },
00096     { ARM::t2SUBrr, ARM::tSUBrr,  0,             0,   0,    1,   0,  0,0, 0 },
00097     { ARM::t2SUBSri,ARM::tSUBi3,  ARM::tSUBi8,   3,   8,    1,   1,  2,2, 0 },
00098     { ARM::t2SUBSrr,ARM::tSUBrr,  0,             0,   0,    1,   0,  2,0, 0 },
00099     { ARM::t2SXTBr, ARM::tSXTB,   0,             0,   0,    1,   0,  1,0, 0 },
00100     { ARM::t2SXTHr, ARM::tSXTH,   0,             0,   0,    1,   0,  1,0, 0 },
00101     { ARM::t2TSTrr, ARM::tTST,    0,             0,   0,    1,   0,  2,0, 0 },
00102     { ARM::t2UXTBr, ARM::tUXTB,   0,             0,   0,    1,   0,  1,0, 0 },
00103     { ARM::t2UXTHr, ARM::tUXTH,   0,             0,   0,    1,   0,  1,0, 0 },
00104 
00105     // FIXME: Clean this up after splitting each Thumb load / store opcode
00106     // into multiple ones.
00107     { ARM::t2LDRi12,ARM::tLDR,    0,             5,   0,    1,   0,  0,0, 1 },
00108     { ARM::t2LDRs,  ARM::tLDR,    0,             0,   0,    1,   0,  0,0, 1 },
00109     { ARM::t2LDRBi12,ARM::tLDRB,  0,             5,   0,    1,   0,  0,0, 1 },
00110     { ARM::t2LDRBs, ARM::tLDRB,   0,             0,   0,    1,   0,  0,0, 1 },
00111     { ARM::t2LDRHi12,ARM::tLDRH,  0,             5,   0,    1,   0,  0,0, 1 },
00112     { ARM::t2LDRHs, ARM::tLDRH,   0,             0,   0,    1,   0,  0,0, 1 },
00113     { ARM::t2LDRSBs,ARM::tLDRSB,  0,             0,   0,    1,   0,  0,0, 1 },
00114     { ARM::t2LDRSHs,ARM::tLDRSH,  0,             0,   0,    1,   0,  0,0, 1 },
00115     { ARM::t2STRi12,ARM::tSTR,    0,             5,   0,    1,   0,  0,0, 1 },
00116     { ARM::t2STRs,  ARM::tSTR,    0,             0,   0,    1,   0,  0,0, 1 },
00117     { ARM::t2STRBi12,ARM::tSTRB,  0,             5,   0,    1,   0,  0,0, 1 },
00118     { ARM::t2STRBs, ARM::tSTRB,   0,             0,   0,    1,   0,  0,0, 1 },
00119     { ARM::t2STRHi12,ARM::tSTRH,  0,             5,   0,    1,   0,  0,0, 1 },
00120     { ARM::t2STRHs, ARM::tSTRH,   0,             0,   0,    1,   0,  0,0, 1 },
00121 
00122     { ARM::t2LDM_RET,0,           ARM::tPOP_RET, 0,   0,    1,   1,  1,1, 1 },
00123     { ARM::t2LDM,   ARM::tLDM,    ARM::tPOP,     0,   0,    1,   1,  1,1, 1 },
00124     { ARM::t2STM,   ARM::tSTM,    ARM::tPUSH,    0,   0,    1,   1,  1,1, 1 },
00125   };
00126 
00127   class VISIBILITY_HIDDEN Thumb2SizeReduce : public MachineFunctionPass {
00128   public:
00129     static char ID;
00130     Thumb2SizeReduce();
00131 
00132     const Thumb2InstrInfo *TII;
00133 
00134     virtual bool runOnMachineFunction(MachineFunction &MF);
00135 
00136     virtual const char *getPassName() const {
00137       return "Thumb2 instruction size reduction pass";
00138     }
00139 
00140   private:
00141     /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTable.
00142     DenseMap<unsigned, unsigned> ReduceOpcodeMap;
00143 
00144     bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
00145                          bool is2Addr, ARMCC::CondCodes Pred,
00146                          bool LiveCPSR, bool &HasCC, bool &CCDead);
00147 
00148     bool ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
00149                          const ReduceEntry &Entry);
00150 
00151     bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
00152                        const ReduceEntry &Entry, bool LiveCPSR);
00153 
00154     /// ReduceTo2Addr - Reduce a 32-bit instruction to a 16-bit two-address
00155     /// instruction.
00156     bool ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
00157                        const ReduceEntry &Entry,
00158                        bool LiveCPSR);
00159 
00160     /// ReduceToNarrow - Reduce a 32-bit instruction to a 16-bit
00161     /// non-two-address instruction.
00162     bool ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
00163                         const ReduceEntry &Entry,
00164                         bool LiveCPSR);
00165 
00166     /// ReduceMBB - Reduce width of instructions in the specified basic block.
00167     bool ReduceMBB(MachineBasicBlock &MBB);
00168   };
00169   char Thumb2SizeReduce::ID = 0;
00170 }
00171 
00172 Thumb2SizeReduce::Thumb2SizeReduce() : MachineFunctionPass(&ID) {
00173   for (unsigned i = 0, e = array_lengthof(ReduceTable); i != e; ++i) {
00174     unsigned FromOpc = ReduceTable[i].WideOpc;
00175     if (!ReduceOpcodeMap.insert(std::make_pair(FromOpc, i)).second)
00176       assert(false && "Duplicated entries?");
00177   }
00178 }
00179 
00180 static bool HasImplicitCPSRDef(const TargetInstrDesc &TID) {
00181   for (const unsigned *Regs = TID.ImplicitDefs; *Regs; ++Regs)
00182     if (*Regs == ARM::CPSR)
00183       return true;
00184   return false;
00185 }
00186 
00187 bool
00188 Thumb2SizeReduce::VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
00189                                   bool is2Addr, ARMCC::CondCodes Pred,
00190                                   bool LiveCPSR, bool &HasCC, bool &CCDead) {
00191   if ((is2Addr  && Entry.PredCC2 == 0) ||
00192       (!is2Addr && Entry.PredCC1 == 0)) {
00193     if (Pred == ARMCC::AL) {
00194       // Not predicated, must set CPSR.
00195       if (!HasCC) {
00196         // Original instruction was not setting CPSR, but CPSR is not
00197         // currently live anyway. It's ok to set it. The CPSR def is
00198         // dead though.
00199         if (!LiveCPSR) {
00200           HasCC = true;
00201           CCDead = true;
00202           return true;
00203         }
00204         return false;
00205       }
00206     } else {
00207       // Predicated, must not set CPSR.
00208       if (HasCC)
00209         return false;
00210     }
00211   } else if ((is2Addr  && Entry.PredCC2 == 2) ||
00212              (!is2Addr && Entry.PredCC1 == 2)) {
00213     /// Old opcode has an optional def of CPSR.
00214     if (HasCC)
00215       return true;
00216     // If both old opcode does not implicit CPSR def, then it's not ok since
00217     // these new opcodes CPSR def is not meant to be thrown away. e.g. CMP.
00218     if (!HasImplicitCPSRDef(MI->getDesc()))
00219       return false;
00220     HasCC = true;
00221   } else {
00222     // 16-bit instruction does not set CPSR.
00223     if (HasCC)
00224       return false;
00225   }
00226 
00227   return true;
00228 }
00229 
00230 static bool VerifyLowRegs(MachineInstr *MI) {
00231   unsigned Opc = MI->getOpcode();
00232   bool isPCOk = (Opc == ARM::t2LDM_RET) || (Opc == ARM::t2LDM);
00233   bool isLROk = (Opc == ARM::t2STM);
00234   bool isSPOk = isPCOk || isLROk || (Opc == ARM::t2ADDrSPi);
00235   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00236     const MachineOperand &MO = MI->getOperand(i);
00237     if (!MO.isReg() || MO.isImplicit())
00238       continue;
00239     unsigned Reg = MO.getReg();
00240     if (Reg == 0 || Reg == ARM::CPSR)
00241       continue;
00242     if (isPCOk && Reg == ARM::PC)
00243       continue;
00244     if (isLROk && Reg == ARM::LR)
00245       continue;
00246     if (isSPOk && Reg == ARM::SP)
00247       continue;
00248     if (!isARMLowRegister(Reg))
00249       return false;
00250   }
00251   return true;
00252 }
00253 
00254 bool
00255 Thumb2SizeReduce::ReduceLoadStore(MachineBasicBlock &MBB, MachineInstr *MI,
00256                                   const ReduceEntry &Entry) {
00257   if (ReduceLimitLdSt != -1 && ((int)NumLdSts >= ReduceLimitLdSt))
00258     return false;
00259 
00260   unsigned Scale = 1;
00261   bool HasImmOffset = false;
00262   bool HasShift = false;
00263   bool isLdStMul = false;
00264   bool isPopPush = false;
00265   unsigned Opc = Entry.NarrowOpc1;
00266   unsigned OpNum = 3; // First 'rest' of operands.
00267   switch (Entry.WideOpc) {
00268   default:
00269     llvm_unreachable("Unexpected Thumb2 load / store opcode!");
00270   case ARM::t2LDRi12:
00271   case ARM::t2STRi12:
00272     Scale = 4;
00273     HasImmOffset = true;
00274     break;
00275   case ARM::t2LDRBi12:
00276   case ARM::t2STRBi12:
00277     HasImmOffset = true;
00278     break;
00279   case ARM::t2LDRHi12:
00280   case ARM::t2STRHi12:
00281     Scale = 2;
00282     HasImmOffset = true;
00283     break;
00284   case ARM::t2LDRs:
00285   case ARM::t2LDRBs:
00286   case ARM::t2LDRHs:
00287   case ARM::t2LDRSBs:
00288   case ARM::t2LDRSHs:
00289   case ARM::t2STRs:
00290   case ARM::t2STRBs:
00291   case ARM::t2STRHs:
00292     HasShift = true;
00293     OpNum = 4;
00294     break;
00295   case ARM::t2LDM_RET:
00296   case ARM::t2LDM:
00297   case ARM::t2STM: {
00298     OpNum = 0;
00299     unsigned BaseReg = MI->getOperand(0).getReg();
00300     unsigned Mode = MI->getOperand(1).getImm();
00301     if (BaseReg == ARM::SP && ARM_AM::getAM4WBFlag(Mode)) {
00302       Opc = Entry.NarrowOpc2;
00303       isPopPush = true;
00304       OpNum = 2;
00305     } else if (Entry.WideOpc == ARM::t2LDM_RET ||
00306                !isARMLowRegister(BaseReg) ||
00307                !ARM_AM::getAM4WBFlag(Mode) ||
00308                ARM_AM::getAM4SubMode(Mode) != ARM_AM::ia) {
00309       return false;
00310     }
00311     isLdStMul = true;
00312     break;
00313   }
00314   }
00315 
00316   unsigned OffsetReg = 0;
00317   bool OffsetKill = false;
00318   if (HasShift) {
00319     OffsetReg  = MI->getOperand(2).getReg();
00320     OffsetKill = MI->getOperand(2).isKill();
00321     if (MI->getOperand(3).getImm())
00322       // Thumb1 addressing mode doesn't support shift.
00323       return false;
00324   }
00325 
00326   unsigned OffsetImm = 0;
00327   if (HasImmOffset) {
00328     OffsetImm = MI->getOperand(2).getImm();
00329     unsigned MaxOffset = ((1 << Entry.Imm1Limit) - 1) * Scale;
00330     if ((OffsetImm & (Scale-1)) || OffsetImm > MaxOffset)
00331       // Make sure the immediate field fits.
00332       return false;
00333   }
00334 
00335   // Add the 16-bit load / store instruction.
00336   // FIXME: Thumb1 addressing mode encode both immediate and register offset.
00337   DebugLoc dl = MI->getDebugLoc();
00338   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, TII->get(Opc));
00339   if (!isLdStMul) {
00340     MIB.addOperand(MI->getOperand(0)).addOperand(MI->getOperand(1));
00341     if (Entry.NarrowOpc1 != ARM::tLDRSB && Entry.NarrowOpc1 != ARM::tLDRSH) {
00342       // tLDRSB and tLDRSH do not have an immediate offset field. On the other
00343       // hand, it must have an offset register.
00344       // FIXME: Remove this special case.
00345       MIB.addImm(OffsetImm/Scale);
00346     }
00347     assert((!HasShift || OffsetReg) && "Invalid so_reg load / store address!");
00348 
00349     MIB.addReg(OffsetReg, getKillRegState(OffsetKill));
00350   }
00351 
00352   // Transfer the rest of operands.
00353   for (unsigned e = MI->getNumOperands(); OpNum != e; ++OpNum)
00354     MIB.addOperand(MI->getOperand(OpNum));
00355 
00356   DOUT << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB;
00357 
00358   MBB.erase(MI);
00359   ++NumLdSts;
00360   return true;
00361 }
00362 
00363 bool
00364 Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
00365                                 const ReduceEntry &Entry,
00366                                 bool LiveCPSR) {
00367   if (Entry.LowRegs1 && !VerifyLowRegs(MI))
00368     return false;
00369 
00370   const TargetInstrDesc &TID = MI->getDesc();
00371   if (TID.mayLoad() || TID.mayStore())
00372     return ReduceLoadStore(MBB, MI, Entry);
00373 
00374   unsigned Opc = MI->getOpcode();
00375   switch (Opc) {
00376   default: break;
00377   case ARM::t2ADDSri: 
00378   case ARM::t2ADDSrr: {
00379     unsigned PredReg = 0;
00380     if (getInstrPredicate(MI, PredReg) == ARMCC::AL) {
00381       switch (Opc) {
00382       default: break;
00383       case ARM::t2ADDSri: {
00384         if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR))
00385           return true;
00386         // fallthrough
00387       }
00388       case ARM::t2ADDSrr:
00389         return ReduceToNarrow(MBB, MI, Entry, LiveCPSR);
00390       }
00391     }
00392     break;
00393   }
00394   case ARM::t2RSBri:
00395   case ARM::t2RSBSri:
00396     if (MI->getOperand(2).getImm() == 0)
00397       return ReduceToNarrow(MBB, MI, Entry, LiveCPSR);
00398     break;
00399   }
00400   return false;
00401 }
00402 
00403 bool
00404 Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
00405                                 const ReduceEntry &Entry,
00406                                 bool LiveCPSR) {
00407 
00408   if (ReduceLimit2Addr != -1 && ((int)Num2Addrs >= ReduceLimit2Addr))
00409     return false;
00410 
00411   const TargetInstrDesc &TID = MI->getDesc();
00412   unsigned Reg0 = MI->getOperand(0).getReg();
00413   unsigned Reg1 = MI->getOperand(1).getReg();
00414   if (Reg0 != Reg1)
00415     return false;
00416   if (Entry.LowRegs2 && !isARMLowRegister(Reg0))
00417     return false;
00418   if (Entry.Imm2Limit) {
00419     unsigned Imm = MI->getOperand(2).getImm();
00420     unsigned Limit = (1 << Entry.Imm2Limit) - 1;
00421     if (Imm > Limit)
00422       return false;
00423   } else {
00424     unsigned Reg2 = MI->getOperand(2).getReg();
00425     if (Entry.LowRegs2 && !isARMLowRegister(Reg2))
00426       return false;
00427   }
00428 
00429   // Check if it's possible / necessary to transfer the predicate.
00430   const TargetInstrDesc &NewTID = TII->get(Entry.NarrowOpc2);
00431   unsigned PredReg = 0;
00432   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
00433   bool SkipPred = false;
00434   if (Pred != ARMCC::AL) {
00435     if (!NewTID.isPredicable())
00436       // Can't transfer predicate, fail.
00437       return false;
00438   } else {
00439     SkipPred = !NewTID.isPredicable();
00440   }
00441 
00442   bool HasCC = false;
00443   bool CCDead = false;
00444   if (TID.hasOptionalDef()) {
00445     unsigned NumOps = TID.getNumOperands();
00446     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
00447     if (HasCC && MI->getOperand(NumOps-1).isDead())
00448       CCDead = true;
00449   }
00450   if (!VerifyPredAndCC(MI, Entry, true, Pred, LiveCPSR, HasCC, CCDead))
00451     return false;
00452 
00453   // Add the 16-bit instruction.
00454   DebugLoc dl = MI->getDebugLoc();
00455   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, NewTID);
00456   MIB.addOperand(MI->getOperand(0));
00457   if (NewTID.hasOptionalDef()) {
00458     if (HasCC)
00459       AddDefaultT1CC(MIB, CCDead);
00460     else
00461       AddNoT1CC(MIB);
00462   }
00463 
00464   // Transfer the rest of operands.
00465   unsigned NumOps = TID.getNumOperands();
00466   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
00467     if (i < NumOps && TID.OpInfo[i].isOptionalDef())
00468       continue;
00469     if (SkipPred && TID.OpInfo[i].isPredicate())
00470       continue;
00471     MIB.addOperand(MI->getOperand(i));
00472   }
00473 
00474   DOUT << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB;
00475 
00476   MBB.erase(MI);
00477   ++Num2Addrs;
00478   return true;
00479 }
00480 
00481 bool
00482 Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
00483                                  const ReduceEntry &Entry,
00484                                  bool LiveCPSR) {
00485   if (ReduceLimit != -1 && ((int)NumNarrows >= ReduceLimit))
00486     return false;
00487 
00488   unsigned Limit = ~0U;
00489   unsigned Scale = (Entry.WideOpc == ARM::t2ADDrSPi) ? 4 : 1;
00490   if (Entry.Imm1Limit)
00491     Limit = ((1 << Entry.Imm1Limit) - 1) * Scale;
00492 
00493   const TargetInstrDesc &TID = MI->getDesc();
00494   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
00495     if (TID.OpInfo[i].isPredicate())
00496       continue;
00497     const MachineOperand &MO = MI->getOperand(i);
00498     if (MO.isReg()) {
00499       unsigned Reg = MO.getReg();
00500       if (!Reg || Reg == ARM::CPSR)
00501         continue;
00502       if (Entry.WideOpc == ARM::t2ADDrSPi && Reg == ARM::SP)
00503         continue;
00504       if (Entry.LowRegs1 && !isARMLowRegister(Reg))
00505         return false;
00506     } else if (MO.isImm() &&
00507                !TID.OpInfo[i].isPredicate()) {
00508       if (MO.getImm() > Limit || (MO.getImm() & (Scale-1)) != 0)
00509         return false;
00510     }
00511   }
00512 
00513   // Check if it's possible / necessary to transfer the predicate.
00514   const TargetInstrDesc &NewTID = TII->get(Entry.NarrowOpc1);
00515   unsigned PredReg = 0;
00516   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
00517   bool SkipPred = false;
00518   if (Pred != ARMCC::AL) {
00519     if (!NewTID.isPredicable())
00520       // Can't transfer predicate, fail.
00521       return false;
00522   } else {
00523     SkipPred = !NewTID.isPredicable();
00524   }
00525 
00526   bool HasCC = false;
00527   bool CCDead = false;
00528   if (TID.hasOptionalDef()) {
00529     unsigned NumOps = TID.getNumOperands();
00530     HasCC = (MI->getOperand(NumOps-1).getReg() == ARM::CPSR);
00531     if (HasCC && MI->getOperand(NumOps-1).isDead())
00532       CCDead = true;
00533   }
00534   if (!VerifyPredAndCC(MI, Entry, false, Pred, LiveCPSR, HasCC, CCDead))
00535     return false;
00536 
00537   // Add the 16-bit instruction.
00538   DebugLoc dl = MI->getDebugLoc();
00539   MachineInstrBuilder MIB = BuildMI(MBB, *MI, dl, NewTID);
00540   MIB.addOperand(MI->getOperand(0));
00541   if (NewTID.hasOptionalDef()) {
00542     if (HasCC)
00543       AddDefaultT1CC(MIB, CCDead);
00544     else
00545       AddNoT1CC(MIB);
00546   }
00547 
00548   // Transfer the rest of operands.
00549   unsigned NumOps = TID.getNumOperands();
00550   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
00551     if (i < NumOps && TID.OpInfo[i].isOptionalDef())
00552       continue;
00553     if ((TID.getOpcode() == ARM::t2RSBSri ||
00554          TID.getOpcode() == ARM::t2RSBri) && i == 2)
00555       // Skip the zero immediate operand, it's now implicit.
00556       continue;
00557     bool isPred = (i < NumOps && TID.OpInfo[i].isPredicate());
00558     if (SkipPred && isPred)
00559         continue;
00560     const MachineOperand &MO = MI->getOperand(i);
00561     if (Scale > 1 && !isPred && MO.isImm())
00562       MIB.addImm(MO.getImm() / Scale);
00563     else {
00564       if (MO.isReg() && MO.isImplicit() && MO.getReg() == ARM::CPSR)
00565         // Skip implicit def of CPSR. Either it's modeled as an optional
00566         // def now or it's already an implicit def on the new instruction.
00567         continue;
00568       MIB.addOperand(MO);
00569     }
00570   }
00571   if (!TID.isPredicable() && NewTID.isPredicable())
00572     AddDefaultPred(MIB);
00573 
00574   DOUT << "Converted 32-bit: " << *MI << "       to 16-bit: " << *MIB;
00575 
00576   MBB.erase(MI);
00577   ++NumNarrows;
00578   return true;
00579 }
00580 
00581 static bool UpdateCPSRDef(MachineInstr &MI, bool LiveCPSR) {
00582   bool HasDef = false;
00583   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
00584     const MachineOperand &MO = MI.getOperand(i);
00585     if (!MO.isReg() || MO.isUndef() || MO.isUse())
00586       continue;
00587     if (MO.getReg() != ARM::CPSR)
00588       continue;
00589     if (!MO.isDead())
00590       HasDef = true;
00591   }
00592 
00593   return HasDef || LiveCPSR;
00594 }
00595 
00596 static bool UpdateCPSRUse(MachineInstr &MI, bool LiveCPSR) {
00597   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
00598     const MachineOperand &MO = MI.getOperand(i);
00599     if (!MO.isReg() || MO.isUndef() || MO.isDef())
00600       continue;
00601     if (MO.getReg() != ARM::CPSR)
00602       continue;
00603     assert(LiveCPSR && "CPSR liveness tracking is wrong!");
00604     if (MO.isKill()) {
00605       LiveCPSR = false;
00606       break;
00607     }
00608   }
00609 
00610   return LiveCPSR;
00611 }
00612 
00613 bool Thumb2SizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
00614   bool Modified = false;
00615 
00616   bool LiveCPSR = false;
00617   // Yes, CPSR could be livein.
00618   for (MachineBasicBlock::const_livein_iterator I = MBB.livein_begin(),
00619          E = MBB.livein_end(); I != E; ++I) {
00620     if (*I == ARM::CPSR) {
00621       LiveCPSR = true;
00622       break;
00623     }
00624   }
00625 
00626   MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
00627   MachineBasicBlock::iterator NextMII;
00628   for (; MII != E; MII = NextMII) {
00629     NextMII = next(MII);
00630 
00631     MachineInstr *MI = &*MII;
00632     LiveCPSR = UpdateCPSRUse(*MI, LiveCPSR);
00633 
00634     unsigned Opcode = MI->getOpcode();
00635     DenseMap<unsigned, unsigned>::iterator OPI = ReduceOpcodeMap.find(Opcode);
00636     if (OPI != ReduceOpcodeMap.end()) {
00637       const ReduceEntry &Entry = ReduceTable[OPI->second];
00638       // Ignore "special" cases for now.
00639       if (Entry.Special) {
00640         if (ReduceSpecial(MBB, MI, Entry, LiveCPSR)) {
00641           Modified = true;
00642           MachineBasicBlock::iterator I = prior(NextMII);
00643           MI = &*I;
00644         }
00645         goto ProcessNext;
00646       }
00647 
00648       // Try to transform to a 16-bit two-address instruction.
00649       if (Entry.NarrowOpc2 && ReduceTo2Addr(MBB, MI, Entry, LiveCPSR)) {
00650         Modified = true;
00651         MachineBasicBlock::iterator I = prior(NextMII);
00652         MI = &*I;
00653         goto ProcessNext;
00654       }
00655 
00656       // Try to transform ro a 16-bit non-two-address instruction.
00657       if (Entry.NarrowOpc1 && ReduceToNarrow(MBB, MI, Entry, LiveCPSR)) {
00658         Modified = true;
00659         MachineBasicBlock::iterator I = prior(NextMII);
00660         MI = &*I;
00661       }
00662     }
00663 
00664   ProcessNext:
00665     LiveCPSR = UpdateCPSRDef(*MI, LiveCPSR);
00666   }
00667 
00668   return Modified;
00669 }
00670 
00671 bool Thumb2SizeReduce::runOnMachineFunction(MachineFunction &MF) {
00672   const TargetMachine &TM = MF.getTarget();
00673   TII = static_cast<const Thumb2InstrInfo*>(TM.getInstrInfo());
00674 
00675   bool Modified = false;
00676   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
00677     Modified |= ReduceMBB(*I);
00678   return Modified;
00679 }
00680 
00681 /// createThumb2SizeReductionPass - Returns an instance of the Thumb2 size
00682 /// reduction pass.
00683 FunctionPass *llvm::createThumb2SizeReductionPass() {
00684   return new Thumb2SizeReduce();
00685 }