InstCombineAddSub.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. //===- InstCombineAddSub.cpp ----------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the visit functions for add, fadd, sub, and fsub.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "InstCombineInternal.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/Analysis/InstructionSimplify.h"
  16. #include "llvm/IR/DataLayout.h"
  17. #include "llvm/IR/GetElementPtrTypeIterator.h"
  18. #include "llvm/IR/PatternMatch.h"
  19. using namespace llvm;
  20. using namespace PatternMatch;
  21. #define DEBUG_TYPE "instcombine"
  22. namespace {
  23. /// Class representing coefficient of floating-point addend.
  24. /// This class needs to be highly efficient, which is especially true for
  25. /// the constructor. As of I write this comment, the cost of the default
  26. /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
  27. /// perform write-merging).
  28. ///
  29. class FAddendCoef {
  30. public:
  31. // The constructor has to initialize a APFloat, which is unnecessary for
  32. // most addends which have coefficient either 1 or -1. So, the constructor
  33. // is expensive. In order to avoid the cost of the constructor, we should
  34. // reuse some instances whenever possible. The pre-created instances
  35. // FAddCombine::Add[0-5] embodies this idea.
  36. //
  37. FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
  38. ~FAddendCoef();
  39. void set(short C) {
  40. assert(!insaneIntVal(C) && "Insane coefficient");
  41. IsFp = false; IntVal = C;
  42. }
  43. void set(const APFloat& C);
  44. void negate();
  45. bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
  46. Value *getValue(Type *) const;
  47. // If possible, don't define operator+/operator- etc because these
  48. // operators inevitably call FAddendCoef's constructor which is not cheap.
  49. void operator=(const FAddendCoef &A);
  50. void operator+=(const FAddendCoef &A);
  51. void operator-=(const FAddendCoef &A);
  52. void operator*=(const FAddendCoef &S);
  53. bool isOne() const { return isInt() && IntVal == 1; }
  54. bool isTwo() const { return isInt() && IntVal == 2; }
  55. bool isMinusOne() const { return isInt() && IntVal == -1; }
  56. bool isMinusTwo() const { return isInt() && IntVal == -2; }
  57. private:
  58. bool insaneIntVal(int V) { return V > 4 || V < -4; }
  59. APFloat *getFpValPtr(void)
  60. { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
  61. const APFloat *getFpValPtr(void) const
  62. { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
  63. const APFloat &getFpVal(void) const {
  64. assert(IsFp && BufHasFpVal && "Incorret state");
  65. return *getFpValPtr();
  66. }
  67. APFloat &getFpVal(void) {
  68. assert(IsFp && BufHasFpVal && "Incorret state");
  69. return *getFpValPtr();
  70. }
  71. bool isInt() const { return !IsFp; }
  72. // If the coefficient is represented by an integer, promote it to a
  73. // floating point.
  74. void convertToFpType(const fltSemantics &Sem);
  75. // Construct an APFloat from a signed integer.
  76. // TODO: We should get rid of this function when APFloat can be constructed
  77. // from an *SIGNED* integer.
  78. APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
  79. private:
  80. bool IsFp;
  81. // True iff FpValBuf contains an instance of APFloat.
  82. bool BufHasFpVal;
  83. // The integer coefficient of an individual addend is either 1 or -1,
  84. // and we try to simplify at most 4 addends from neighboring at most
  85. // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
  86. // is overkill of this end.
  87. short IntVal;
  88. AlignedCharArrayUnion<APFloat> FpValBuf;
  89. };
  90. /// FAddend is used to represent floating-point addend. An addend is
  91. /// represented as <C, V>, where the V is a symbolic value, and C is a
  92. /// constant coefficient. A constant addend is represented as <C, 0>.
  93. ///
  94. class FAddend {
  95. public:
  96. FAddend() { Val = nullptr; }
  97. Value *getSymVal (void) const { return Val; }
  98. const FAddendCoef &getCoef(void) const { return Coeff; }
  99. bool isConstant() const { return Val == nullptr; }
  100. bool isZero() const { return Coeff.isZero(); }
  101. void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
  102. void set(const APFloat& Coefficient, Value *V)
  103. { Coeff.set(Coefficient); Val = V; }
  104. void set(const ConstantFP* Coefficient, Value *V)
  105. { Coeff.set(Coefficient->getValueAPF()); Val = V; }
  106. void negate() { Coeff.negate(); }
  107. /// Drill down the U-D chain one step to find the definition of V, and
  108. /// try to break the definition into one or two addends.
  109. static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
  110. /// Similar to FAddend::drillDownOneStep() except that the value being
  111. /// splitted is the addend itself.
  112. unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
  113. void operator+=(const FAddend &T) {
  114. assert((Val == T.Val) && "Symbolic-values disagree");
  115. Coeff += T.Coeff;
  116. }
  117. private:
  118. void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
  119. // This addend has the value of "Coeff * Val".
  120. Value *Val;
  121. FAddendCoef Coeff;
  122. };
  123. /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
  124. /// with its neighboring at most two instructions.
  125. ///
  126. class FAddCombine {
  127. public:
  128. FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(nullptr) {}
  129. Value *simplify(Instruction *FAdd);
  130. private:
  131. typedef SmallVector<const FAddend*, 4> AddendVect;
  132. Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
  133. Value *performFactorization(Instruction *I);
  134. /// Convert given addend to a Value
  135. Value *createAddendVal(const FAddend &A, bool& NeedNeg);
  136. /// Return the number of instructions needed to emit the N-ary addition.
  137. unsigned calcInstrNumber(const AddendVect& Vect);
  138. Value *createFSub(Value *Opnd0, Value *Opnd1);
  139. Value *createFAdd(Value *Opnd0, Value *Opnd1);
  140. Value *createFMul(Value *Opnd0, Value *Opnd1);
  141. Value *createFDiv(Value *Opnd0, Value *Opnd1);
  142. Value *createFNeg(Value *V);
  143. Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
  144. void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
  145. InstCombiner::BuilderTy *Builder;
  146. Instruction *Instr;
  147. private:
  148. // Debugging stuff are clustered here.
  149. #ifndef NDEBUG
  150. unsigned CreateInstrNum;
  151. void initCreateInstNum() { CreateInstrNum = 0; }
  152. void incCreateInstNum() { CreateInstrNum++; }
  153. #else
  154. void initCreateInstNum() {}
  155. void incCreateInstNum() {}
  156. #endif
  157. };
  158. }
  159. //===----------------------------------------------------------------------===//
  160. //
  161. // Implementation of
  162. // {FAddendCoef, FAddend, FAddition, FAddCombine}.
  163. //
  164. //===----------------------------------------------------------------------===//
  165. FAddendCoef::~FAddendCoef() {
  166. if (BufHasFpVal)
  167. getFpValPtr()->~APFloat();
  168. }
  169. void FAddendCoef::set(const APFloat& C) {
  170. APFloat *P = getFpValPtr();
  171. if (isInt()) {
  172. // As the buffer is meanless byte stream, we cannot call
  173. // APFloat::operator=().
  174. new(P) APFloat(C);
  175. } else
  176. *P = C;
  177. IsFp = BufHasFpVal = true;
  178. }
  179. void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
  180. if (!isInt())
  181. return;
  182. APFloat *P = getFpValPtr();
  183. if (IntVal > 0)
  184. new(P) APFloat(Sem, IntVal);
  185. else {
  186. new(P) APFloat(Sem, 0 - IntVal);
  187. P->changeSign();
  188. }
  189. IsFp = BufHasFpVal = true;
  190. }
  191. APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
  192. if (Val >= 0)
  193. return APFloat(Sem, Val);
  194. APFloat T(Sem, 0 - Val);
  195. T.changeSign();
  196. return T;
  197. }
  198. void FAddendCoef::operator=(const FAddendCoef &That) {
  199. if (That.isInt())
  200. set(That.IntVal);
  201. else
  202. set(That.getFpVal());
  203. }
  204. void FAddendCoef::operator+=(const FAddendCoef &That) {
  205. enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
  206. if (isInt() == That.isInt()) {
  207. if (isInt())
  208. IntVal += That.IntVal;
  209. else
  210. getFpVal().add(That.getFpVal(), RndMode);
  211. return;
  212. }
  213. if (isInt()) {
  214. const APFloat &T = That.getFpVal();
  215. convertToFpType(T.getSemantics());
  216. getFpVal().add(T, RndMode);
  217. return;
  218. }
  219. APFloat &T = getFpVal();
  220. T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
  221. }
  222. void FAddendCoef::operator-=(const FAddendCoef &That) {
  223. enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
  224. if (isInt() == That.isInt()) {
  225. if (isInt())
  226. IntVal -= That.IntVal;
  227. else
  228. getFpVal().subtract(That.getFpVal(), RndMode);
  229. return;
  230. }
  231. if (isInt()) {
  232. const APFloat &T = That.getFpVal();
  233. convertToFpType(T.getSemantics());
  234. getFpVal().subtract(T, RndMode);
  235. return;
  236. }
  237. APFloat &T = getFpVal();
  238. T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
  239. }
  240. void FAddendCoef::operator*=(const FAddendCoef &That) {
  241. if (That.isOne())
  242. return;
  243. if (That.isMinusOne()) {
  244. negate();
  245. return;
  246. }
  247. if (isInt() && That.isInt()) {
  248. int Res = IntVal * (int)That.IntVal;
  249. assert(!insaneIntVal(Res) && "Insane int value");
  250. IntVal = Res;
  251. return;
  252. }
  253. const fltSemantics &Semantic =
  254. isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
  255. if (isInt())
  256. convertToFpType(Semantic);
  257. APFloat &F0 = getFpVal();
  258. if (That.isInt())
  259. F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
  260. APFloat::rmNearestTiesToEven);
  261. else
  262. F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
  263. return;
  264. }
  265. void FAddendCoef::negate() {
  266. if (isInt())
  267. IntVal = 0 - IntVal;
  268. else
  269. getFpVal().changeSign();
  270. }
  271. Value *FAddendCoef::getValue(Type *Ty) const {
  272. return isInt() ?
  273. ConstantFP::get(Ty, float(IntVal)) :
  274. ConstantFP::get(Ty->getContext(), getFpVal());
  275. }
  276. // The definition of <Val> Addends
  277. // =========================================
  278. // A + B <1, A>, <1,B>
  279. // A - B <1, A>, <1,B>
  280. // 0 - B <-1, B>
  281. // C * A, <C, A>
  282. // A + C <1, A> <C, NULL>
  283. // 0 +/- 0 <0, NULL> (corner case)
  284. //
  285. // Legend: A and B are not constant, C is constant
  286. //
  287. unsigned FAddend::drillValueDownOneStep
  288. (Value *Val, FAddend &Addend0, FAddend &Addend1) {
  289. Instruction *I = nullptr;
  290. if (!Val || !(I = dyn_cast<Instruction>(Val)))
  291. return 0;
  292. unsigned Opcode = I->getOpcode();
  293. if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
  294. ConstantFP *C0, *C1;
  295. Value *Opnd0 = I->getOperand(0);
  296. Value *Opnd1 = I->getOperand(1);
  297. if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
  298. Opnd0 = nullptr;
  299. if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
  300. Opnd1 = nullptr;
  301. if (Opnd0) {
  302. if (!C0)
  303. Addend0.set(1, Opnd0);
  304. else
  305. Addend0.set(C0, nullptr);
  306. }
  307. if (Opnd1) {
  308. FAddend &Addend = Opnd0 ? Addend1 : Addend0;
  309. if (!C1)
  310. Addend.set(1, Opnd1);
  311. else
  312. Addend.set(C1, nullptr);
  313. if (Opcode == Instruction::FSub)
  314. Addend.negate();
  315. }
  316. if (Opnd0 || Opnd1)
  317. return Opnd0 && Opnd1 ? 2 : 1;
  318. // Both operands are zero. Weird!
  319. Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
  320. return 1;
  321. }
  322. if (I->getOpcode() == Instruction::FMul) {
  323. Value *V0 = I->getOperand(0);
  324. Value *V1 = I->getOperand(1);
  325. if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
  326. Addend0.set(C, V1);
  327. return 1;
  328. }
  329. if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
  330. Addend0.set(C, V0);
  331. return 1;
  332. }
  333. }
  334. return 0;
  335. }
  336. // Try to break *this* addend into two addends. e.g. Suppose this addend is
  337. // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
  338. // i.e. <2.3, X> and <2.3, Y>.
  339. //
  340. unsigned FAddend::drillAddendDownOneStep
  341. (FAddend &Addend0, FAddend &Addend1) const {
  342. if (isConstant())
  343. return 0;
  344. unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
  345. if (!BreakNum || Coeff.isOne())
  346. return BreakNum;
  347. Addend0.Scale(Coeff);
  348. if (BreakNum == 2)
  349. Addend1.Scale(Coeff);
  350. return BreakNum;
  351. }
  352. // Try to perform following optimization on the input instruction I. Return the
  353. // simplified expression if was successful; otherwise, return 0.
  354. //
  355. // Instruction "I" is Simplified into
  356. // -------------------------------------------------------
  357. // (x * y) +/- (x * z) x * (y +/- z)
  358. // (y / x) +/- (z / x) (y +/- z) / x
  359. //
  360. Value *FAddCombine::performFactorization(Instruction *I) {
  361. assert((I->getOpcode() == Instruction::FAdd ||
  362. I->getOpcode() == Instruction::FSub) && "Expect add/sub");
  363. Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
  364. Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
  365. if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
  366. return nullptr;
  367. bool isMpy = false;
  368. if (I0->getOpcode() == Instruction::FMul)
  369. isMpy = true;
  370. else if (I0->getOpcode() != Instruction::FDiv)
  371. return nullptr;
  372. Value *Opnd0_0 = I0->getOperand(0);
  373. Value *Opnd0_1 = I0->getOperand(1);
  374. Value *Opnd1_0 = I1->getOperand(0);
  375. Value *Opnd1_1 = I1->getOperand(1);
  376. // Input Instr I Factor AddSub0 AddSub1
  377. // ----------------------------------------------
  378. // (x*y) +/- (x*z) x y z
  379. // (y/x) +/- (z/x) x y z
  380. //
  381. Value *Factor = nullptr;
  382. Value *AddSub0 = nullptr, *AddSub1 = nullptr;
  383. if (isMpy) {
  384. if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
  385. Factor = Opnd0_0;
  386. else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
  387. Factor = Opnd0_1;
  388. if (Factor) {
  389. AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
  390. AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
  391. }
  392. } else if (Opnd0_1 == Opnd1_1) {
  393. Factor = Opnd0_1;
  394. AddSub0 = Opnd0_0;
  395. AddSub1 = Opnd1_0;
  396. }
  397. if (!Factor)
  398. return nullptr;
  399. FastMathFlags Flags;
  400. Flags.setUnsafeAlgebra();
  401. if (I0) Flags &= I->getFastMathFlags();
  402. if (I1) Flags &= I->getFastMathFlags();
  403. // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
  404. Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
  405. createFAdd(AddSub0, AddSub1) :
  406. createFSub(AddSub0, AddSub1);
  407. if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
  408. const APFloat &F = CFP->getValueAPF();
  409. if (!F.isNormal())
  410. return nullptr;
  411. } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
  412. II->setFastMathFlags(Flags);
  413. if (isMpy) {
  414. Value *RI = createFMul(Factor, NewAddSub);
  415. if (Instruction *II = dyn_cast<Instruction>(RI))
  416. II->setFastMathFlags(Flags);
  417. return RI;
  418. }
  419. Value *RI = createFDiv(NewAddSub, Factor);
  420. if (Instruction *II = dyn_cast<Instruction>(RI))
  421. II->setFastMathFlags(Flags);
  422. return RI;
  423. }
  424. Value *FAddCombine::simplify(Instruction *I) {
  425. assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
  426. // Currently we are not able to handle vector type.
  427. if (I->getType()->isVectorTy())
  428. return nullptr;
  429. assert((I->getOpcode() == Instruction::FAdd ||
  430. I->getOpcode() == Instruction::FSub) && "Expect add/sub");
  431. // Save the instruction before calling other member-functions.
  432. Instr = I;
  433. FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
  434. unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
  435. // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
  436. unsigned Opnd0_ExpNum = 0;
  437. unsigned Opnd1_ExpNum = 0;
  438. if (!Opnd0.isConstant())
  439. Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
  440. // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
  441. if (OpndNum == 2 && !Opnd1.isConstant())
  442. Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
  443. // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
  444. if (Opnd0_ExpNum && Opnd1_ExpNum) {
  445. AddendVect AllOpnds;
  446. AllOpnds.push_back(&Opnd0_0);
  447. AllOpnds.push_back(&Opnd1_0);
  448. if (Opnd0_ExpNum == 2)
  449. AllOpnds.push_back(&Opnd0_1);
  450. if (Opnd1_ExpNum == 2)
  451. AllOpnds.push_back(&Opnd1_1);
  452. // Compute instruction quota. We should save at least one instruction.
  453. unsigned InstQuota = 0;
  454. Value *V0 = I->getOperand(0);
  455. Value *V1 = I->getOperand(1);
  456. InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
  457. (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
  458. if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
  459. return R;
  460. }
  461. if (OpndNum != 2) {
  462. // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
  463. // splitted into two addends, say "V = X - Y", the instruction would have
  464. // been optimized into "I = Y - X" in the previous steps.
  465. //
  466. const FAddendCoef &CE = Opnd0.getCoef();
  467. return CE.isOne() ? Opnd0.getSymVal() : nullptr;
  468. }
  469. // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
  470. if (Opnd1_ExpNum) {
  471. AddendVect AllOpnds;
  472. AllOpnds.push_back(&Opnd0);
  473. AllOpnds.push_back(&Opnd1_0);
  474. if (Opnd1_ExpNum == 2)
  475. AllOpnds.push_back(&Opnd1_1);
  476. if (Value *R = simplifyFAdd(AllOpnds, 1))
  477. return R;
  478. }
  479. // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
  480. if (Opnd0_ExpNum) {
  481. AddendVect AllOpnds;
  482. AllOpnds.push_back(&Opnd1);
  483. AllOpnds.push_back(&Opnd0_0);
  484. if (Opnd0_ExpNum == 2)
  485. AllOpnds.push_back(&Opnd0_1);
  486. if (Value *R = simplifyFAdd(AllOpnds, 1))
  487. return R;
  488. }
  489. // step 6: Try factorization as the last resort,
  490. return performFactorization(I);
  491. }
  492. Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
  493. unsigned AddendNum = Addends.size();
  494. assert(AddendNum <= 4 && "Too many addends");
  495. // For saving intermediate results;
  496. unsigned NextTmpIdx = 0;
  497. FAddend TmpResult[3];
  498. // Points to the constant addend of the resulting simplified expression.
  499. // If the resulting expr has constant-addend, this constant-addend is
  500. // desirable to reside at the top of the resulting expression tree. Placing
  501. // constant close to supper-expr(s) will potentially reveal some optimization
  502. // opportunities in super-expr(s).
  503. //
  504. const FAddend *ConstAdd = nullptr;
  505. // Simplified addends are placed <SimpVect>.
  506. AddendVect SimpVect;
  507. // The outer loop works on one symbolic-value at a time. Suppose the input
  508. // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
  509. // The symbolic-values will be processed in this order: x, y, z.
  510. //
  511. for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
  512. const FAddend *ThisAddend = Addends[SymIdx];
  513. if (!ThisAddend) {
  514. // This addend was processed before.
  515. continue;
  516. }
  517. Value *Val = ThisAddend->getSymVal();
  518. unsigned StartIdx = SimpVect.size();
  519. SimpVect.push_back(ThisAddend);
  520. // The inner loop collects addends sharing same symbolic-value, and these
  521. // addends will be later on folded into a single addend. Following above
  522. // example, if the symbolic value "y" is being processed, the inner loop
  523. // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
  524. // be later on folded into "<b1+b2, y>".
  525. //
  526. for (unsigned SameSymIdx = SymIdx + 1;
  527. SameSymIdx < AddendNum; SameSymIdx++) {
  528. const FAddend *T = Addends[SameSymIdx];
  529. if (T && T->getSymVal() == Val) {
  530. // Set null such that next iteration of the outer loop will not process
  531. // this addend again.
  532. Addends[SameSymIdx] = nullptr;
  533. SimpVect.push_back(T);
  534. }
  535. }
  536. // If multiple addends share same symbolic value, fold them together.
  537. if (StartIdx + 1 != SimpVect.size()) {
  538. FAddend &R = TmpResult[NextTmpIdx ++];
  539. R = *SimpVect[StartIdx];
  540. for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
  541. R += *SimpVect[Idx];
  542. // Pop all addends being folded and push the resulting folded addend.
  543. SimpVect.resize(StartIdx);
  544. if (Val) {
  545. if (!R.isZero()) {
  546. SimpVect.push_back(&R);
  547. }
  548. } else {
  549. // Don't push constant addend at this time. It will be the last element
  550. // of <SimpVect>.
  551. ConstAdd = &R;
  552. }
  553. }
  554. }
  555. assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
  556. "out-of-bound access");
  557. if (ConstAdd)
  558. SimpVect.push_back(ConstAdd);
  559. Value *Result;
  560. if (!SimpVect.empty())
  561. Result = createNaryFAdd(SimpVect, InstrQuota);
  562. else {
  563. // The addition is folded to 0.0.
  564. Result = ConstantFP::get(Instr->getType(), 0.0);
  565. }
  566. return Result;
  567. }
  568. Value *FAddCombine::createNaryFAdd
  569. (const AddendVect &Opnds, unsigned InstrQuota) {
  570. assert(!Opnds.empty() && "Expect at least one addend");
  571. // Step 1: Check if the # of instructions needed exceeds the quota.
  572. //
  573. unsigned InstrNeeded = calcInstrNumber(Opnds);
  574. if (InstrNeeded > InstrQuota)
  575. return nullptr;
  576. initCreateInstNum();
  577. // step 2: Emit the N-ary addition.
  578. // Note that at most three instructions are involved in Fadd-InstCombine: the
  579. // addition in question, and at most two neighboring instructions.
  580. // The resulting optimized addition should have at least one less instruction
  581. // than the original addition expression tree. This implies that the resulting
  582. // N-ary addition has at most two instructions, and we don't need to worry
  583. // about tree-height when constructing the N-ary addition.
  584. Value *LastVal = nullptr;
  585. bool LastValNeedNeg = false;
  586. // Iterate the addends, creating fadd/fsub using adjacent two addends.
  587. for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
  588. I != E; I++) {
  589. bool NeedNeg;
  590. Value *V = createAddendVal(**I, NeedNeg);
  591. if (!LastVal) {
  592. LastVal = V;
  593. LastValNeedNeg = NeedNeg;
  594. continue;
  595. }
  596. if (LastValNeedNeg == NeedNeg) {
  597. LastVal = createFAdd(LastVal, V);
  598. continue;
  599. }
  600. if (LastValNeedNeg)
  601. LastVal = createFSub(V, LastVal);
  602. else
  603. LastVal = createFSub(LastVal, V);
  604. LastValNeedNeg = false;
  605. }
  606. if (LastValNeedNeg) {
  607. LastVal = createFNeg(LastVal);
  608. }
  609. #ifndef NDEBUG
  610. assert(CreateInstrNum == InstrNeeded &&
  611. "Inconsistent in instruction numbers");
  612. #endif
  613. return LastVal;
  614. }
  615. Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
  616. Value *V = Builder->CreateFSub(Opnd0, Opnd1);
  617. if (Instruction *I = dyn_cast<Instruction>(V))
  618. createInstPostProc(I);
  619. return V;
  620. }
  621. Value *FAddCombine::createFNeg(Value *V) {
  622. Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
  623. Value *NewV = createFSub(Zero, V);
  624. if (Instruction *I = dyn_cast<Instruction>(NewV))
  625. createInstPostProc(I, true); // fneg's don't receive instruction numbers.
  626. return NewV;
  627. }
  628. Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
  629. Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
  630. if (Instruction *I = dyn_cast<Instruction>(V))
  631. createInstPostProc(I);
  632. return V;
  633. }
  634. Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
  635. Value *V = Builder->CreateFMul(Opnd0, Opnd1);
  636. if (Instruction *I = dyn_cast<Instruction>(V))
  637. createInstPostProc(I);
  638. return V;
  639. }
  640. Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
  641. Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
  642. if (Instruction *I = dyn_cast<Instruction>(V))
  643. createInstPostProc(I);
  644. return V;
  645. }
  646. void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
  647. NewInstr->setDebugLoc(Instr->getDebugLoc());
  648. // Keep track of the number of instruction created.
  649. if (!NoNumber)
  650. incCreateInstNum();
  651. // Propagate fast-math flags
  652. NewInstr->setFastMathFlags(Instr->getFastMathFlags());
  653. }
  654. // Return the number of instruction needed to emit the N-ary addition.
  655. // NOTE: Keep this function in sync with createAddendVal().
  656. unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
  657. unsigned OpndNum = Opnds.size();
  658. unsigned InstrNeeded = OpndNum - 1;
  659. // The number of addends in the form of "(-1)*x".
  660. unsigned NegOpndNum = 0;
  661. // Adjust the number of instructions needed to emit the N-ary add.
  662. for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
  663. I != E; I++) {
  664. const FAddend *Opnd = *I;
  665. if (Opnd->isConstant())
  666. continue;
  667. const FAddendCoef &CE = Opnd->getCoef();
  668. if (CE.isMinusOne() || CE.isMinusTwo())
  669. NegOpndNum++;
  670. // Let the addend be "c * x". If "c == +/-1", the value of the addend
  671. // is immediately available; otherwise, it needs exactly one instruction
  672. // to evaluate the value.
  673. if (!CE.isMinusOne() && !CE.isOne())
  674. InstrNeeded++;
  675. }
  676. if (NegOpndNum == OpndNum)
  677. InstrNeeded++;
  678. return InstrNeeded;
  679. }
  680. // Input Addend Value NeedNeg(output)
  681. // ================================================================
  682. // Constant C C false
  683. // <+/-1, V> V coefficient is -1
  684. // <2/-2, V> "fadd V, V" coefficient is -2
  685. // <C, V> "fmul V, C" false
  686. //
  687. // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
  688. Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
  689. const FAddendCoef &Coeff = Opnd.getCoef();
  690. if (Opnd.isConstant()) {
  691. NeedNeg = false;
  692. return Coeff.getValue(Instr->getType());
  693. }
  694. Value *OpndVal = Opnd.getSymVal();
  695. if (Coeff.isMinusOne() || Coeff.isOne()) {
  696. NeedNeg = Coeff.isMinusOne();
  697. return OpndVal;
  698. }
  699. if (Coeff.isTwo() || Coeff.isMinusTwo()) {
  700. NeedNeg = Coeff.isMinusTwo();
  701. return createFAdd(OpndVal, OpndVal);
  702. }
  703. NeedNeg = false;
  704. return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
  705. }
  706. // If one of the operands only has one non-zero bit, and if the other
  707. // operand has a known-zero bit in a more significant place than it (not
  708. // including the sign bit) the ripple may go up to and fill the zero, but
  709. // won't change the sign. For example, (X & ~4) + 1.
  710. static bool checkRippleForAdd(const APInt &Op0KnownZero,
  711. const APInt &Op1KnownZero) {
  712. APInt Op1MaybeOne = ~Op1KnownZero;
  713. // Make sure that one of the operand has at most one bit set to 1.
  714. if (Op1MaybeOne.countPopulation() != 1)
  715. return false;
  716. // Find the most significant known 0 other than the sign bit.
  717. int BitWidth = Op0KnownZero.getBitWidth();
  718. APInt Op0KnownZeroTemp(Op0KnownZero);
  719. Op0KnownZeroTemp.clearBit(BitWidth - 1);
  720. int Op0ZeroPosition = BitWidth - Op0KnownZeroTemp.countLeadingZeros() - 1;
  721. int Op1OnePosition = BitWidth - Op1MaybeOne.countLeadingZeros() - 1;
  722. assert(Op1OnePosition >= 0);
  723. // This also covers the case of no known zero, since in that case
  724. // Op0ZeroPosition is -1.
  725. return Op0ZeroPosition >= Op1OnePosition;
  726. }
  727. /// WillNotOverflowSignedAdd - Return true if we can prove that:
  728. /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
  729. /// This basically requires proving that the add in the original type would not
  730. /// overflow to change the sign bit or have a carry out.
  731. bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS,
  732. Instruction &CxtI) {
  733. // There are different heuristics we can use for this. Here are some simple
  734. // ones.
  735. // If LHS and RHS each have at least two sign bits, the addition will look
  736. // like
  737. //
  738. // XX..... +
  739. // YY.....
  740. //
  741. // If the carry into the most significant position is 0, X and Y can't both
  742. // be 1 and therefore the carry out of the addition is also 0.
  743. //
  744. // If the carry into the most significant position is 1, X and Y can't both
  745. // be 0 and therefore the carry out of the addition is also 1.
  746. //
  747. // Since the carry into the most significant position is always equal to
  748. // the carry out of the addition, there is no signed overflow.
  749. if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
  750. ComputeNumSignBits(RHS, 0, &CxtI) > 1)
  751. return true;
  752. unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
  753. APInt LHSKnownZero(BitWidth, 0);
  754. APInt LHSKnownOne(BitWidth, 0);
  755. computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &CxtI);
  756. APInt RHSKnownZero(BitWidth, 0);
  757. APInt RHSKnownOne(BitWidth, 0);
  758. computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &CxtI);
  759. // Addition of two 2's compliment numbers having opposite signs will never
  760. // overflow.
  761. if ((LHSKnownOne[BitWidth - 1] && RHSKnownZero[BitWidth - 1]) ||
  762. (LHSKnownZero[BitWidth - 1] && RHSKnownOne[BitWidth - 1]))
  763. return true;
  764. // Check if carry bit of addition will not cause overflow.
  765. if (checkRippleForAdd(LHSKnownZero, RHSKnownZero))
  766. return true;
  767. if (checkRippleForAdd(RHSKnownZero, LHSKnownZero))
  768. return true;
  769. return false;
  770. }
  771. /// \brief Return true if we can prove that:
  772. /// (sub LHS, RHS) === (sub nsw LHS, RHS)
  773. /// This basically requires proving that the add in the original type would not
  774. /// overflow to change the sign bit or have a carry out.
  775. /// TODO: Handle this for Vectors.
  776. bool InstCombiner::WillNotOverflowSignedSub(Value *LHS, Value *RHS,
  777. Instruction &CxtI) {
  778. // If LHS and RHS each have at least two sign bits, the subtraction
  779. // cannot overflow.
  780. if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
  781. ComputeNumSignBits(RHS, 0, &CxtI) > 1)
  782. return true;
  783. unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
  784. APInt LHSKnownZero(BitWidth, 0);
  785. APInt LHSKnownOne(BitWidth, 0);
  786. computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &CxtI);
  787. APInt RHSKnownZero(BitWidth, 0);
  788. APInt RHSKnownOne(BitWidth, 0);
  789. computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &CxtI);
  790. // Subtraction of two 2's compliment numbers having identical signs will
  791. // never overflow.
  792. if ((LHSKnownOne[BitWidth - 1] && RHSKnownOne[BitWidth - 1]) ||
  793. (LHSKnownZero[BitWidth - 1] && RHSKnownZero[BitWidth - 1]))
  794. return true;
  795. // TODO: implement logic similar to checkRippleForAdd
  796. return false;
  797. }
  798. /// \brief Return true if we can prove that:
  799. /// (sub LHS, RHS) === (sub nuw LHS, RHS)
  800. bool InstCombiner::WillNotOverflowUnsignedSub(Value *LHS, Value *RHS,
  801. Instruction &CxtI) {
  802. // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
  803. bool LHSKnownNonNegative, LHSKnownNegative;
  804. bool RHSKnownNonNegative, RHSKnownNegative;
  805. ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, /*Depth=*/0,
  806. &CxtI);
  807. ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, /*Depth=*/0,
  808. &CxtI);
  809. if (LHSKnownNegative && RHSKnownNonNegative)
  810. return true;
  811. return false;
  812. }
  813. // Checks if any operand is negative and we can convert add to sub.
  814. // This function checks for following negative patterns
  815. // ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
  816. // ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
  817. // XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
  818. static Value *checkForNegativeOperand(BinaryOperator &I,
  819. InstCombiner::BuilderTy *Builder) {
  820. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  821. // This function creates 2 instructions to replace ADD, we need at least one
  822. // of LHS or RHS to have one use to ensure benefit in transform.
  823. if (!LHS->hasOneUse() && !RHS->hasOneUse())
  824. return nullptr;
  825. Value *X = nullptr, *Y = nullptr, *Z = nullptr;
  826. const APInt *C1 = nullptr, *C2 = nullptr;
  827. // if ONE is on other side, swap
  828. if (match(RHS, m_Add(m_Value(X), m_One())))
  829. std::swap(LHS, RHS);
  830. if (match(LHS, m_Add(m_Value(X), m_One()))) {
  831. // if XOR on other side, swap
  832. if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
  833. std::swap(X, RHS);
  834. if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
  835. // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
  836. // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
  837. if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
  838. Value *NewAnd = Builder->CreateAnd(Z, *C1);
  839. return Builder->CreateSub(RHS, NewAnd, "sub");
  840. } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
  841. // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
  842. // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
  843. Value *NewOr = Builder->CreateOr(Z, ~(*C1));
  844. return Builder->CreateSub(RHS, NewOr, "sub");
  845. }
  846. }
  847. }
  848. // Restore LHS and RHS
  849. LHS = I.getOperand(0);
  850. RHS = I.getOperand(1);
  851. // if XOR is on other side, swap
  852. if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
  853. std::swap(LHS, RHS);
  854. // C2 is ODD
  855. // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
  856. // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
  857. if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
  858. if (C1->countTrailingZeros() == 0)
  859. if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
  860. Value *NewOr = Builder->CreateOr(Z, ~(*C2));
  861. return Builder->CreateSub(RHS, NewOr, "sub");
  862. }
  863. return nullptr;
  864. }
  865. Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
  866. bool Changed = SimplifyAssociativeOrCommutative(I);
  867. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  868. if (Value *V = SimplifyVectorOp(I))
  869. return ReplaceInstUsesWith(I, V);
  870. if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
  871. I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
  872. return ReplaceInstUsesWith(I, V);
  873. // (A*B)+(A*C) -> A*(B+C) etc
  874. if (Value *V = SimplifyUsingDistributiveLaws(I))
  875. return ReplaceInstUsesWith(I, V);
  876. if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
  877. // X + (signbit) --> X ^ signbit
  878. const APInt &Val = CI->getValue();
  879. if (Val.isSignBit())
  880. return BinaryOperator::CreateXor(LHS, RHS);
  881. // See if SimplifyDemandedBits can simplify this. This handles stuff like
  882. // (X & 254)+1 -> (X&254)|1
  883. if (SimplifyDemandedInstructionBits(I))
  884. return &I;
  885. // zext(bool) + C -> bool ? C + 1 : C
  886. if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
  887. if (ZI->getSrcTy()->isIntegerTy(1))
  888. return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
  889. Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
  890. if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
  891. uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
  892. const APInt &RHSVal = CI->getValue();
  893. unsigned ExtendAmt = 0;
  894. // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
  895. // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
  896. if (XorRHS->getValue() == -RHSVal) {
  897. if (RHSVal.isPowerOf2())
  898. ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
  899. else if (XorRHS->getValue().isPowerOf2())
  900. ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
  901. }
  902. if (ExtendAmt) {
  903. APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
  904. if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
  905. ExtendAmt = 0;
  906. }
  907. if (ExtendAmt) {
  908. Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
  909. Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
  910. return BinaryOperator::CreateAShr(NewShl, ShAmt);
  911. }
  912. // If this is a xor that was canonicalized from a sub, turn it back into
  913. // a sub and fuse this add with it.
  914. if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
  915. IntegerType *IT = cast<IntegerType>(I.getType());
  916. APInt LHSKnownOne(IT->getBitWidth(), 0);
  917. APInt LHSKnownZero(IT->getBitWidth(), 0);
  918. computeKnownBits(XorLHS, LHSKnownZero, LHSKnownOne, 0, &I);
  919. if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
  920. return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
  921. XorLHS);
  922. }
  923. // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
  924. // transform them into (X + (signbit ^ C))
  925. if (XorRHS->getValue().isSignBit())
  926. return BinaryOperator::CreateAdd(XorLHS,
  927. ConstantExpr::getXor(XorRHS, CI));
  928. }
  929. }
  930. if (isa<Constant>(RHS) && isa<PHINode>(LHS))
  931. if (Instruction *NV = FoldOpIntoPhi(I))
  932. return NV;
  933. if (I.getType()->getScalarType()->isIntegerTy(1))
  934. return BinaryOperator::CreateXor(LHS, RHS);
  935. // X + X --> X << 1
  936. if (LHS == RHS) {
  937. BinaryOperator *New =
  938. BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
  939. New->setHasNoSignedWrap(I.hasNoSignedWrap());
  940. New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
  941. return New;
  942. }
  943. // -A + B --> B - A
  944. // -A + -B --> -(A + B)
  945. if (Value *LHSV = dyn_castNegVal(LHS)) {
  946. if (!isa<Constant>(RHS))
  947. if (Value *RHSV = dyn_castNegVal(RHS)) {
  948. Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
  949. return BinaryOperator::CreateNeg(NewAdd);
  950. }
  951. return BinaryOperator::CreateSub(RHS, LHSV);
  952. }
  953. // A + -B --> A - B
  954. if (!isa<Constant>(RHS))
  955. if (Value *V = dyn_castNegVal(RHS))
  956. return BinaryOperator::CreateSub(LHS, V);
  957. if (Value *V = checkForNegativeOperand(I, Builder))
  958. return ReplaceInstUsesWith(I, V);
  959. // A+B --> A|B iff A and B have no bits set in common.
  960. if (haveNoCommonBitsSet(LHS, RHS, DL, AC, &I, DT))
  961. return BinaryOperator::CreateOr(LHS, RHS);
  962. if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
  963. Value *X;
  964. if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
  965. return BinaryOperator::CreateSub(SubOne(CRHS), X);
  966. }
  967. if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
  968. // (X & FF00) + xx00 -> (X+xx00) & FF00
  969. Value *X;
  970. ConstantInt *C2;
  971. if (LHS->hasOneUse() &&
  972. match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
  973. CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
  974. // See if all bits from the first bit set in the Add RHS up are included
  975. // in the mask. First, get the rightmost bit.
  976. const APInt &AddRHSV = CRHS->getValue();
  977. // Form a mask of all bits from the lowest bit added through the top.
  978. APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
  979. // See if the and mask includes all of these bits.
  980. APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
  981. if (AddRHSHighBits == AddRHSHighBitsAnd) {
  982. // Okay, the xform is safe. Insert the new add pronto.
  983. Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
  984. return BinaryOperator::CreateAnd(NewAdd, C2);
  985. }
  986. }
  987. // Try to fold constant add into select arguments.
  988. if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
  989. if (Instruction *R = FoldOpIntoSelect(I, SI))
  990. return R;
  991. }
  992. // add (select X 0 (sub n A)) A --> select X A n
  993. {
  994. SelectInst *SI = dyn_cast<SelectInst>(LHS);
  995. Value *A = RHS;
  996. if (!SI) {
  997. SI = dyn_cast<SelectInst>(RHS);
  998. A = LHS;
  999. }
  1000. if (SI && SI->hasOneUse()) {
  1001. Value *TV = SI->getTrueValue();
  1002. Value *FV = SI->getFalseValue();
  1003. Value *N;
  1004. // Can we fold the add into the argument of the select?
  1005. // We check both true and false select arguments for a matching subtract.
  1006. if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
  1007. // Fold the add into the true select value.
  1008. return SelectInst::Create(SI->getCondition(), N, A);
  1009. if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
  1010. // Fold the add into the false select value.
  1011. return SelectInst::Create(SI->getCondition(), A, N);
  1012. }
  1013. }
  1014. // Check for (add (sext x), y), see if we can merge this into an
  1015. // integer add followed by a sext.
  1016. if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
  1017. // (add (sext x), cst) --> (sext (add x, cst'))
  1018. if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
  1019. Constant *CI =
  1020. ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
  1021. if (LHSConv->hasOneUse() &&
  1022. ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
  1023. WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
  1024. // Insert the new, smaller add.
  1025. Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
  1026. CI, "addconv");
  1027. return new SExtInst(NewAdd, I.getType());
  1028. }
  1029. }
  1030. // (add (sext x), (sext y)) --> (sext (add int x, y))
  1031. if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
  1032. // Only do this if x/y have the same type, if at last one of them has a
  1033. // single use (so we don't increase the number of sexts), and if the
  1034. // integer add will not overflow.
  1035. if (LHSConv->getOperand(0)->getType() ==
  1036. RHSConv->getOperand(0)->getType() &&
  1037. (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
  1038. WillNotOverflowSignedAdd(LHSConv->getOperand(0),
  1039. RHSConv->getOperand(0), I)) {
  1040. // Insert the new integer add.
  1041. Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
  1042. RHSConv->getOperand(0), "addconv");
  1043. return new SExtInst(NewAdd, I.getType());
  1044. }
  1045. }
  1046. }
  1047. // (add (xor A, B) (and A, B)) --> (or A, B)
  1048. {
  1049. Value *A = nullptr, *B = nullptr;
  1050. if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
  1051. (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
  1052. match(LHS, m_And(m_Specific(B), m_Specific(A)))))
  1053. return BinaryOperator::CreateOr(A, B);
  1054. if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
  1055. (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
  1056. match(RHS, m_And(m_Specific(B), m_Specific(A)))))
  1057. return BinaryOperator::CreateOr(A, B);
  1058. }
  1059. // (add (or A, B) (and A, B)) --> (add A, B)
  1060. {
  1061. Value *A = nullptr, *B = nullptr;
  1062. if (match(RHS, m_Or(m_Value(A), m_Value(B))) &&
  1063. (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
  1064. match(LHS, m_And(m_Specific(B), m_Specific(A))))) {
  1065. auto *New = BinaryOperator::CreateAdd(A, B);
  1066. New->setHasNoSignedWrap(I.hasNoSignedWrap());
  1067. New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
  1068. return New;
  1069. }
  1070. if (match(LHS, m_Or(m_Value(A), m_Value(B))) &&
  1071. (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
  1072. match(RHS, m_And(m_Specific(B), m_Specific(A))))) {
  1073. auto *New = BinaryOperator::CreateAdd(A, B);
  1074. New->setHasNoSignedWrap(I.hasNoSignedWrap());
  1075. New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
  1076. return New;
  1077. }
  1078. }
  1079. // TODO(jingyue): Consider WillNotOverflowSignedAdd and
  1080. // WillNotOverflowUnsignedAdd to reduce the number of invocations of
  1081. // computeKnownBits.
  1082. if (!I.hasNoSignedWrap() && WillNotOverflowSignedAdd(LHS, RHS, I)) {
  1083. Changed = true;
  1084. I.setHasNoSignedWrap(true);
  1085. }
  1086. if (!I.hasNoUnsignedWrap() &&
  1087. computeOverflowForUnsignedAdd(LHS, RHS, &I) ==
  1088. OverflowResult::NeverOverflows) {
  1089. Changed = true;
  1090. I.setHasNoUnsignedWrap(true);
  1091. }
  1092. return Changed ? &I : nullptr;
  1093. }
  1094. Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
  1095. bool Changed = SimplifyAssociativeOrCommutative(I);
  1096. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  1097. if (Value *V = SimplifyVectorOp(I))
  1098. return ReplaceInstUsesWith(I, V);
  1099. if (Value *V =
  1100. SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL, TLI, DT, AC))
  1101. return ReplaceInstUsesWith(I, V);
  1102. if (isa<Constant>(RHS)) {
  1103. if (isa<PHINode>(LHS))
  1104. if (Instruction *NV = FoldOpIntoPhi(I))
  1105. return NV;
  1106. if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
  1107. if (Instruction *NV = FoldOpIntoSelect(I, SI))
  1108. return NV;
  1109. }
  1110. // -A + B --> B - A
  1111. // -A + -B --> -(A + B)
  1112. if (Value *LHSV = dyn_castFNegVal(LHS)) {
  1113. Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
  1114. RI->copyFastMathFlags(&I);
  1115. return RI;
  1116. }
  1117. // A + -B --> A - B
  1118. if (!isa<Constant>(RHS))
  1119. if (Value *V = dyn_castFNegVal(RHS)) {
  1120. Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
  1121. RI->copyFastMathFlags(&I);
  1122. return RI;
  1123. }
  1124. // Check for (fadd double (sitofp x), y), see if we can merge this into an
  1125. // integer add followed by a promotion.
  1126. if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
  1127. // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
  1128. // ... if the constant fits in the integer value. This is useful for things
  1129. // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
  1130. // requires a constant pool load, and generally allows the add to be better
  1131. // instcombined.
  1132. if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
  1133. Constant *CI =
  1134. ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
  1135. if (LHSConv->hasOneUse() &&
  1136. ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
  1137. WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
  1138. // Insert the new integer add.
  1139. Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
  1140. CI, "addconv");
  1141. return new SIToFPInst(NewAdd, I.getType());
  1142. }
  1143. }
  1144. // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
  1145. if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
  1146. // Only do this if x/y have the same type, if at last one of them has a
  1147. // single use (so we don't increase the number of int->fp conversions),
  1148. // and if the integer add will not overflow.
  1149. if (LHSConv->getOperand(0)->getType() ==
  1150. RHSConv->getOperand(0)->getType() &&
  1151. (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
  1152. WillNotOverflowSignedAdd(LHSConv->getOperand(0),
  1153. RHSConv->getOperand(0), I)) {
  1154. // Insert the new integer add.
  1155. Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
  1156. RHSConv->getOperand(0),"addconv");
  1157. return new SIToFPInst(NewAdd, I.getType());
  1158. }
  1159. }
  1160. }
  1161. // select C, 0, B + select C, A, 0 -> select C, A, B
  1162. {
  1163. Value *A1, *B1, *C1, *A2, *B2, *C2;
  1164. if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
  1165. match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
  1166. if (C1 == C2) {
  1167. Constant *Z1=nullptr, *Z2=nullptr;
  1168. Value *A, *B, *C=C1;
  1169. if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
  1170. Z1 = dyn_cast<Constant>(A1); A = A2;
  1171. Z2 = dyn_cast<Constant>(B2); B = B1;
  1172. } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
  1173. Z1 = dyn_cast<Constant>(B1); B = B2;
  1174. Z2 = dyn_cast<Constant>(A2); A = A1;
  1175. }
  1176. if (Z1 && Z2 &&
  1177. (I.hasNoSignedZeros() ||
  1178. (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
  1179. return SelectInst::Create(C, A, B);
  1180. }
  1181. }
  1182. }
  1183. }
  1184. if (I.hasUnsafeAlgebra()) {
  1185. if (Value *V = FAddCombine(Builder).simplify(&I))
  1186. return ReplaceInstUsesWith(I, V);
  1187. }
  1188. return Changed ? &I : nullptr;
  1189. }
  1190. /// Optimize pointer differences into the same array into a size. Consider:
  1191. /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
  1192. /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
  1193. ///
  1194. Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
  1195. Type *Ty) {
  1196. // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
  1197. // this.
  1198. bool Swapped = false;
  1199. GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
  1200. // For now we require one side to be the base pointer "A" or a constant
  1201. // GEP derived from it.
  1202. if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
  1203. // (gep X, ...) - X
  1204. if (LHSGEP->getOperand(0) == RHS) {
  1205. GEP1 = LHSGEP;
  1206. Swapped = false;
  1207. } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
  1208. // (gep X, ...) - (gep X, ...)
  1209. if (LHSGEP->getOperand(0)->stripPointerCasts() ==
  1210. RHSGEP->getOperand(0)->stripPointerCasts()) {
  1211. GEP2 = RHSGEP;
  1212. GEP1 = LHSGEP;
  1213. Swapped = false;
  1214. }
  1215. }
  1216. }
  1217. if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
  1218. // X - (gep X, ...)
  1219. if (RHSGEP->getOperand(0) == LHS) {
  1220. GEP1 = RHSGEP;
  1221. Swapped = true;
  1222. } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
  1223. // (gep X, ...) - (gep X, ...)
  1224. if (RHSGEP->getOperand(0)->stripPointerCasts() ==
  1225. LHSGEP->getOperand(0)->stripPointerCasts()) {
  1226. GEP2 = LHSGEP;
  1227. GEP1 = RHSGEP;
  1228. Swapped = true;
  1229. }
  1230. }
  1231. }
  1232. // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
  1233. // multiple users.
  1234. if (!GEP1 ||
  1235. (GEP2 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
  1236. return nullptr;
  1237. // Emit the offset of the GEP and an intptr_t.
  1238. Value *Result = EmitGEPOffset(GEP1);
  1239. // If we had a constant expression GEP on the other side offsetting the
  1240. // pointer, subtract it from the offset we have.
  1241. if (GEP2) {
  1242. Value *Offset = EmitGEPOffset(GEP2);
  1243. Result = Builder->CreateSub(Result, Offset);
  1244. }
  1245. // If we have p - gep(p, ...) then we have to negate the result.
  1246. if (Swapped)
  1247. Result = Builder->CreateNeg(Result, "diff.neg");
  1248. return Builder->CreateIntCast(Result, Ty, true);
  1249. }
  1250. Instruction *InstCombiner::visitSub(BinaryOperator &I) {
  1251. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1252. if (Value *V = SimplifyVectorOp(I))
  1253. return ReplaceInstUsesWith(I, V);
  1254. if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
  1255. I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
  1256. return ReplaceInstUsesWith(I, V);
  1257. // (A*B)-(A*C) -> A*(B-C) etc
  1258. if (Value *V = SimplifyUsingDistributiveLaws(I))
  1259. return ReplaceInstUsesWith(I, V);
  1260. // If this is a 'B = x-(-A)', change to B = x+A.
  1261. if (Value *V = dyn_castNegVal(Op1)) {
  1262. BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
  1263. if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
  1264. assert(BO->getOpcode() == Instruction::Sub &&
  1265. "Expected a subtraction operator!");
  1266. if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
  1267. Res->setHasNoSignedWrap(true);
  1268. } else {
  1269. if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
  1270. Res->setHasNoSignedWrap(true);
  1271. }
  1272. return Res;
  1273. }
  1274. if (I.getType()->isIntegerTy(1))
  1275. return BinaryOperator::CreateXor(Op0, Op1);
  1276. // Replace (-1 - A) with (~A).
  1277. if (match(Op0, m_AllOnes()))
  1278. return BinaryOperator::CreateNot(Op1);
  1279. if (Constant *C = dyn_cast<Constant>(Op0)) {
  1280. // C - ~X == X + (1+C)
  1281. Value *X = nullptr;
  1282. if (match(Op1, m_Not(m_Value(X))))
  1283. return BinaryOperator::CreateAdd(X, AddOne(C));
  1284. // Try to fold constant sub into select arguments.
  1285. if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
  1286. if (Instruction *R = FoldOpIntoSelect(I, SI))
  1287. return R;
  1288. // C-(X+C2) --> (C-C2)-X
  1289. Constant *C2;
  1290. if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
  1291. return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
  1292. if (SimplifyDemandedInstructionBits(I))
  1293. return &I;
  1294. // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
  1295. if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
  1296. if (X->getType()->getScalarType()->isIntegerTy(1))
  1297. return CastInst::CreateSExtOrBitCast(X, Op1->getType());
  1298. // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
  1299. if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
  1300. if (X->getType()->getScalarType()->isIntegerTy(1))
  1301. return CastInst::CreateZExtOrBitCast(X, Op1->getType());
  1302. }
  1303. if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
  1304. // -(X >>u 31) -> (X >>s 31)
  1305. // -(X >>s 31) -> (X >>u 31)
  1306. if (C->isZero()) {
  1307. Value *X;
  1308. ConstantInt *CI;
  1309. if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
  1310. // Verify we are shifting out everything but the sign bit.
  1311. CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
  1312. return BinaryOperator::CreateAShr(X, CI);
  1313. if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
  1314. // Verify we are shifting out everything but the sign bit.
  1315. CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
  1316. return BinaryOperator::CreateLShr(X, CI);
  1317. }
  1318. // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
  1319. // zero.
  1320. APInt IntVal = C->getValue();
  1321. if ((IntVal + 1).isPowerOf2()) {
  1322. unsigned BitWidth = I.getType()->getScalarSizeInBits();
  1323. APInt KnownZero(BitWidth, 0);
  1324. APInt KnownOne(BitWidth, 0);
  1325. computeKnownBits(&I, KnownZero, KnownOne, 0, &I);
  1326. if ((IntVal | KnownZero).isAllOnesValue()) {
  1327. return BinaryOperator::CreateXor(Op1, C);
  1328. }
  1329. }
  1330. }
  1331. {
  1332. Value *Y;
  1333. // X-(X+Y) == -Y X-(Y+X) == -Y
  1334. if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
  1335. match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
  1336. return BinaryOperator::CreateNeg(Y);
  1337. // (X-Y)-X == -Y
  1338. if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
  1339. return BinaryOperator::CreateNeg(Y);
  1340. }
  1341. // (sub (or A, B) (xor A, B)) --> (and A, B)
  1342. {
  1343. Value *A = nullptr, *B = nullptr;
  1344. if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
  1345. (match(Op0, m_Or(m_Specific(A), m_Specific(B))) ||
  1346. match(Op0, m_Or(m_Specific(B), m_Specific(A)))))
  1347. return BinaryOperator::CreateAnd(A, B);
  1348. }
  1349. // (sub (select (a, c, b)), (select (a, d, b))) -> (select (a, (sub c, d), 0))
  1350. // (sub (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (sub c, d)))
  1351. if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
  1352. if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
  1353. if (SI0->getCondition() == SI1->getCondition()) {
  1354. if (Value *V = SimplifySubInst(
  1355. SI0->getFalseValue(), SI1->getFalseValue(), I.hasNoSignedWrap(),
  1356. I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
  1357. return SelectInst::Create(
  1358. SI0->getCondition(),
  1359. Builder->CreateSub(SI0->getTrueValue(), SI1->getTrueValue(), "",
  1360. /*HasNUW=*/I.hasNoUnsignedWrap(),
  1361. /*HasNSW=*/I.hasNoSignedWrap()),
  1362. V);
  1363. if (Value *V = SimplifySubInst(SI0->getTrueValue(), SI1->getTrueValue(),
  1364. I.hasNoSignedWrap(),
  1365. I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
  1366. return SelectInst::Create(
  1367. SI0->getCondition(), V,
  1368. Builder->CreateSub(SI0->getFalseValue(), SI1->getFalseValue(), "",
  1369. /*HasNUW=*/I.hasNoUnsignedWrap(),
  1370. /*HasNSW=*/I.hasNoSignedWrap()));
  1371. }
  1372. }
  1373. }
  1374. if (Op0->hasOneUse()) {
  1375. Value *Y = nullptr;
  1376. // ((X | Y) - X) --> (~X & Y)
  1377. if (match(Op0, m_Or(m_Value(Y), m_Specific(Op1))) ||
  1378. match(Op0, m_Or(m_Specific(Op1), m_Value(Y))))
  1379. return BinaryOperator::CreateAnd(
  1380. Y, Builder->CreateNot(Op1, Op1->getName() + ".not"));
  1381. }
  1382. if (Op1->hasOneUse()) {
  1383. Value *X = nullptr, *Y = nullptr, *Z = nullptr;
  1384. Constant *C = nullptr;
  1385. Constant *CI = nullptr;
  1386. // (X - (Y - Z)) --> (X + (Z - Y)).
  1387. if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
  1388. return BinaryOperator::CreateAdd(Op0,
  1389. Builder->CreateSub(Z, Y, Op1->getName()));
  1390. // (X - (X & Y)) --> (X & ~Y)
  1391. //
  1392. if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
  1393. match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
  1394. return BinaryOperator::CreateAnd(Op0,
  1395. Builder->CreateNot(Y, Y->getName() + ".not"));
  1396. // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
  1397. if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) &&
  1398. C->isNotMinSignedValue() && !C->isOneValue())
  1399. return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
  1400. // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
  1401. if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
  1402. if (Value *XNeg = dyn_castNegVal(X))
  1403. return BinaryOperator::CreateShl(XNeg, Y);
  1404. // X - A*-B -> X + A*B
  1405. // X - -A*B -> X + A*B
  1406. Value *A, *B;
  1407. if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
  1408. match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
  1409. return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
  1410. // X - A*CI -> X + A*-CI
  1411. // X - CI*A -> X + A*-CI
  1412. if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
  1413. match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
  1414. Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
  1415. return BinaryOperator::CreateAdd(Op0, NewMul);
  1416. }
  1417. }
  1418. // Optimize pointer differences into the same array into a size. Consider:
  1419. // &A[10] - &A[0]: we should compile this to "10".
  1420. Value *LHSOp, *RHSOp;
  1421. if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
  1422. match(Op1, m_PtrToInt(m_Value(RHSOp))))
  1423. if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
  1424. return ReplaceInstUsesWith(I, Res);
  1425. // trunc(p)-trunc(q) -> trunc(p-q)
  1426. if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
  1427. match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
  1428. if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
  1429. return ReplaceInstUsesWith(I, Res);
  1430. bool Changed = false;
  1431. if (!I.hasNoSignedWrap() && WillNotOverflowSignedSub(Op0, Op1, I)) {
  1432. Changed = true;
  1433. I.setHasNoSignedWrap(true);
  1434. }
  1435. if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedSub(Op0, Op1, I)) {
  1436. Changed = true;
  1437. I.setHasNoUnsignedWrap(true);
  1438. }
  1439. return Changed ? &I : nullptr;
  1440. }
  1441. Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
  1442. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1443. if (Value *V = SimplifyVectorOp(I))
  1444. return ReplaceInstUsesWith(I, V);
  1445. if (Value *V =
  1446. SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL, TLI, DT, AC))
  1447. return ReplaceInstUsesWith(I, V);
  1448. // fsub nsz 0, X ==> fsub nsz -0.0, X
  1449. if (I.getFastMathFlags().noSignedZeros() && match(Op0, m_Zero())) {
  1450. // Subtraction from -0.0 is the canonical form of fneg.
  1451. Instruction *NewI = BinaryOperator::CreateFNeg(Op1);
  1452. NewI->copyFastMathFlags(&I);
  1453. return NewI;
  1454. }
  1455. if (isa<Constant>(Op0))
  1456. if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
  1457. if (Instruction *NV = FoldOpIntoSelect(I, SI))
  1458. return NV;
  1459. // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
  1460. // through FP extensions/truncations along the way.
  1461. if (Value *V = dyn_castFNegVal(Op1)) {
  1462. Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
  1463. NewI->copyFastMathFlags(&I);
  1464. return NewI;
  1465. }
  1466. if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
  1467. if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
  1468. Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
  1469. Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
  1470. NewI->copyFastMathFlags(&I);
  1471. return NewI;
  1472. }
  1473. } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
  1474. if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
  1475. Value *NewExt = Builder->CreateFPExt(V, I.getType());
  1476. Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
  1477. NewI->copyFastMathFlags(&I);
  1478. return NewI;
  1479. }
  1480. }
  1481. if (I.hasUnsafeAlgebra()) {
  1482. if (Value *V = FAddCombine(Builder).simplify(&I))
  1483. return ReplaceInstUsesWith(I, V);
  1484. }
  1485. return nullptr;
  1486. }