InstCombineAddSub.cpp 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478
  1. //===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the visit functions for add, fadd, sub, and fsub.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "InstCombineInternal.h"
  13. #include "llvm/ADT/APFloat.h"
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Analysis/InstructionSimplify.h"
  18. #include "llvm/Analysis/ValueTracking.h"
  19. #include "llvm/IR/Constant.h"
  20. #include "llvm/IR/Constants.h"
  21. #include "llvm/IR/InstrTypes.h"
  22. #include "llvm/IR/Instruction.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/Operator.h"
  25. #include "llvm/IR/PatternMatch.h"
  26. #include "llvm/IR/Type.h"
  27. #include "llvm/IR/Value.h"
  28. #include "llvm/Support/AlignOf.h"
  29. #include "llvm/Support/Casting.h"
  30. #include "llvm/Support/KnownBits.h"
  31. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  32. #include <cassert>
  33. #include <utility>
  34. using namespace llvm;
  35. using namespace PatternMatch;
  36. #define DEBUG_TYPE "instcombine"
  37. namespace {
  38. /// Class representing coefficient of floating-point addend.
  39. /// This class needs to be highly efficient, which is especially true for
  40. /// the constructor. As of I write this comment, the cost of the default
  41. /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
  42. /// perform write-merging).
  43. ///
  44. class FAddendCoef {
  45. public:
  46. // The constructor has to initialize a APFloat, which is unnecessary for
  47. // most addends which have coefficient either 1 or -1. So, the constructor
  48. // is expensive. In order to avoid the cost of the constructor, we should
  49. // reuse some instances whenever possible. The pre-created instances
  50. // FAddCombine::Add[0-5] embodies this idea.
  51. FAddendCoef() = default;
  52. ~FAddendCoef();
  53. // If possible, don't define operator+/operator- etc because these
  54. // operators inevitably call FAddendCoef's constructor which is not cheap.
  55. void operator=(const FAddendCoef &A);
  56. void operator+=(const FAddendCoef &A);
  57. void operator*=(const FAddendCoef &S);
  58. void set(short C) {
  59. assert(!insaneIntVal(C) && "Insane coefficient");
  60. IsFp = false; IntVal = C;
  61. }
  62. void set(const APFloat& C);
  63. void negate();
  64. bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
  65. Value *getValue(Type *) const;
  66. bool isOne() const { return isInt() && IntVal == 1; }
  67. bool isTwo() const { return isInt() && IntVal == 2; }
  68. bool isMinusOne() const { return isInt() && IntVal == -1; }
  69. bool isMinusTwo() const { return isInt() && IntVal == -2; }
  70. private:
  71. bool insaneIntVal(int V) { return V > 4 || V < -4; }
  72. APFloat *getFpValPtr() { return reinterpret_cast<APFloat *>(&FpValBuf); }
  73. const APFloat *getFpValPtr() const {
  74. return reinterpret_cast<const APFloat *>(&FpValBuf);
  75. }
  76. const APFloat &getFpVal() const {
  77. assert(IsFp && BufHasFpVal && "Incorret state");
  78. return *getFpValPtr();
  79. }
  80. APFloat &getFpVal() {
  81. assert(IsFp && BufHasFpVal && "Incorret state");
  82. return *getFpValPtr();
  83. }
  84. bool isInt() const { return !IsFp; }
  85. // If the coefficient is represented by an integer, promote it to a
  86. // floating point.
  87. void convertToFpType(const fltSemantics &Sem);
  88. // Construct an APFloat from a signed integer.
  89. // TODO: We should get rid of this function when APFloat can be constructed
  90. // from an *SIGNED* integer.
  91. APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
  92. bool IsFp = false;
  93. // True iff FpValBuf contains an instance of APFloat.
  94. bool BufHasFpVal = false;
  95. // The integer coefficient of an individual addend is either 1 or -1,
  96. // and we try to simplify at most 4 addends from neighboring at most
  97. // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
  98. // is overkill of this end.
  99. short IntVal = 0;
  100. AlignedCharArrayUnion<APFloat> FpValBuf;
  101. };
  102. /// FAddend is used to represent floating-point addend. An addend is
  103. /// represented as <C, V>, where the V is a symbolic value, and C is a
  104. /// constant coefficient. A constant addend is represented as <C, 0>.
  105. class FAddend {
  106. public:
  107. FAddend() = default;
  108. void operator+=(const FAddend &T) {
  109. assert((Val == T.Val) && "Symbolic-values disagree");
  110. Coeff += T.Coeff;
  111. }
  112. Value *getSymVal() const { return Val; }
  113. const FAddendCoef &getCoef() const { return Coeff; }
  114. bool isConstant() const { return Val == nullptr; }
  115. bool isZero() const { return Coeff.isZero(); }
  116. void set(short Coefficient, Value *V) {
  117. Coeff.set(Coefficient);
  118. Val = V;
  119. }
  120. void set(const APFloat &Coefficient, Value *V) {
  121. Coeff.set(Coefficient);
  122. Val = V;
  123. }
  124. void set(const ConstantFP *Coefficient, Value *V) {
  125. Coeff.set(Coefficient->getValueAPF());
  126. Val = V;
  127. }
  128. void negate() { Coeff.negate(); }
  129. /// Drill down the U-D chain one step to find the definition of V, and
  130. /// try to break the definition into one or two addends.
  131. static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
  132. /// Similar to FAddend::drillDownOneStep() except that the value being
  133. /// splitted is the addend itself.
  134. unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
  135. private:
  136. void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
  137. // This addend has the value of "Coeff * Val".
  138. Value *Val = nullptr;
  139. FAddendCoef Coeff;
  140. };
  141. /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
  142. /// with its neighboring at most two instructions.
  143. ///
  144. class FAddCombine {
  145. public:
  146. FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
  147. Value *simplify(Instruction *FAdd);
  148. private:
  149. using AddendVect = SmallVector<const FAddend *, 4>;
  150. Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
  151. /// Convert given addend to a Value
  152. Value *createAddendVal(const FAddend &A, bool& NeedNeg);
  153. /// Return the number of instructions needed to emit the N-ary addition.
  154. unsigned calcInstrNumber(const AddendVect& Vect);
  155. Value *createFSub(Value *Opnd0, Value *Opnd1);
  156. Value *createFAdd(Value *Opnd0, Value *Opnd1);
  157. Value *createFMul(Value *Opnd0, Value *Opnd1);
  158. Value *createFNeg(Value *V);
  159. Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
  160. void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
  161. // Debugging stuff are clustered here.
  162. #ifndef NDEBUG
  163. unsigned CreateInstrNum;
  164. void initCreateInstNum() { CreateInstrNum = 0; }
  165. void incCreateInstNum() { CreateInstrNum++; }
  166. #else
  167. void initCreateInstNum() {}
  168. void incCreateInstNum() {}
  169. #endif
  170. InstCombiner::BuilderTy &Builder;
  171. Instruction *Instr = nullptr;
  172. };
  173. } // end anonymous namespace
  174. //===----------------------------------------------------------------------===//
  175. //
  176. // Implementation of
  177. // {FAddendCoef, FAddend, FAddition, FAddCombine}.
  178. //
  179. //===----------------------------------------------------------------------===//
  180. FAddendCoef::~FAddendCoef() {
  181. if (BufHasFpVal)
  182. getFpValPtr()->~APFloat();
  183. }
  184. void FAddendCoef::set(const APFloat& C) {
  185. APFloat *P = getFpValPtr();
  186. if (isInt()) {
  187. // As the buffer is meanless byte stream, we cannot call
  188. // APFloat::operator=().
  189. new(P) APFloat(C);
  190. } else
  191. *P = C;
  192. IsFp = BufHasFpVal = true;
  193. }
  194. void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
  195. if (!isInt())
  196. return;
  197. APFloat *P = getFpValPtr();
  198. if (IntVal > 0)
  199. new(P) APFloat(Sem, IntVal);
  200. else {
  201. new(P) APFloat(Sem, 0 - IntVal);
  202. P->changeSign();
  203. }
  204. IsFp = BufHasFpVal = true;
  205. }
  206. APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
  207. if (Val >= 0)
  208. return APFloat(Sem, Val);
  209. APFloat T(Sem, 0 - Val);
  210. T.changeSign();
  211. return T;
  212. }
  213. void FAddendCoef::operator=(const FAddendCoef &That) {
  214. if (That.isInt())
  215. set(That.IntVal);
  216. else
  217. set(That.getFpVal());
  218. }
  219. void FAddendCoef::operator+=(const FAddendCoef &That) {
  220. RoundingMode RndMode = RoundingMode::NearestTiesToEven;
  221. if (isInt() == That.isInt()) {
  222. if (isInt())
  223. IntVal += That.IntVal;
  224. else
  225. getFpVal().add(That.getFpVal(), RndMode);
  226. return;
  227. }
  228. if (isInt()) {
  229. const APFloat &T = That.getFpVal();
  230. convertToFpType(T.getSemantics());
  231. getFpVal().add(T, RndMode);
  232. return;
  233. }
  234. APFloat &T = getFpVal();
  235. T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
  236. }
  237. void FAddendCoef::operator*=(const FAddendCoef &That) {
  238. if (That.isOne())
  239. return;
  240. if (That.isMinusOne()) {
  241. negate();
  242. return;
  243. }
  244. if (isInt() && That.isInt()) {
  245. int Res = IntVal * (int)That.IntVal;
  246. assert(!insaneIntVal(Res) && "Insane int value");
  247. IntVal = Res;
  248. return;
  249. }
  250. const fltSemantics &Semantic =
  251. isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
  252. if (isInt())
  253. convertToFpType(Semantic);
  254. APFloat &F0 = getFpVal();
  255. if (That.isInt())
  256. F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
  257. APFloat::rmNearestTiesToEven);
  258. else
  259. F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
  260. }
  261. void FAddendCoef::negate() {
  262. if (isInt())
  263. IntVal = 0 - IntVal;
  264. else
  265. getFpVal().changeSign();
  266. }
  267. Value *FAddendCoef::getValue(Type *Ty) const {
  268. return isInt() ?
  269. ConstantFP::get(Ty, float(IntVal)) :
  270. ConstantFP::get(Ty->getContext(), getFpVal());
  271. }
  272. // The definition of <Val> Addends
  273. // =========================================
  274. // A + B <1, A>, <1,B>
  275. // A - B <1, A>, <1,B>
  276. // 0 - B <-1, B>
  277. // C * A, <C, A>
  278. // A + C <1, A> <C, NULL>
  279. // 0 +/- 0 <0, NULL> (corner case)
  280. //
  281. // Legend: A and B are not constant, C is constant
  282. unsigned FAddend::drillValueDownOneStep
  283. (Value *Val, FAddend &Addend0, FAddend &Addend1) {
  284. Instruction *I = nullptr;
  285. if (!Val || !(I = dyn_cast<Instruction>(Val)))
  286. return 0;
  287. unsigned Opcode = I->getOpcode();
  288. if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
  289. ConstantFP *C0, *C1;
  290. Value *Opnd0 = I->getOperand(0);
  291. Value *Opnd1 = I->getOperand(1);
  292. if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
  293. Opnd0 = nullptr;
  294. if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
  295. Opnd1 = nullptr;
  296. if (Opnd0) {
  297. if (!C0)
  298. Addend0.set(1, Opnd0);
  299. else
  300. Addend0.set(C0, nullptr);
  301. }
  302. if (Opnd1) {
  303. FAddend &Addend = Opnd0 ? Addend1 : Addend0;
  304. if (!C1)
  305. Addend.set(1, Opnd1);
  306. else
  307. Addend.set(C1, nullptr);
  308. if (Opcode == Instruction::FSub)
  309. Addend.negate();
  310. }
  311. if (Opnd0 || Opnd1)
  312. return Opnd0 && Opnd1 ? 2 : 1;
  313. // Both operands are zero. Weird!
  314. Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
  315. return 1;
  316. }
  317. if (I->getOpcode() == Instruction::FMul) {
  318. Value *V0 = I->getOperand(0);
  319. Value *V1 = I->getOperand(1);
  320. if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
  321. Addend0.set(C, V1);
  322. return 1;
  323. }
  324. if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
  325. Addend0.set(C, V0);
  326. return 1;
  327. }
  328. }
  329. return 0;
  330. }
  331. // Try to break *this* addend into two addends. e.g. Suppose this addend is
  332. // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
  333. // i.e. <2.3, X> and <2.3, Y>.
  334. unsigned FAddend::drillAddendDownOneStep
  335. (FAddend &Addend0, FAddend &Addend1) const {
  336. if (isConstant())
  337. return 0;
  338. unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
  339. if (!BreakNum || Coeff.isOne())
  340. return BreakNum;
  341. Addend0.Scale(Coeff);
  342. if (BreakNum == 2)
  343. Addend1.Scale(Coeff);
  344. return BreakNum;
  345. }
  346. Value *FAddCombine::simplify(Instruction *I) {
  347. assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
  348. "Expected 'reassoc'+'nsz' instruction");
  349. // Currently we are not able to handle vector type.
  350. if (I->getType()->isVectorTy())
  351. return nullptr;
  352. assert((I->getOpcode() == Instruction::FAdd ||
  353. I->getOpcode() == Instruction::FSub) && "Expect add/sub");
  354. // Save the instruction before calling other member-functions.
  355. Instr = I;
  356. FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
  357. unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
  358. // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
  359. unsigned Opnd0_ExpNum = 0;
  360. unsigned Opnd1_ExpNum = 0;
  361. if (!Opnd0.isConstant())
  362. Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
  363. // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
  364. if (OpndNum == 2 && !Opnd1.isConstant())
  365. Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
  366. // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
  367. if (Opnd0_ExpNum && Opnd1_ExpNum) {
  368. AddendVect AllOpnds;
  369. AllOpnds.push_back(&Opnd0_0);
  370. AllOpnds.push_back(&Opnd1_0);
  371. if (Opnd0_ExpNum == 2)
  372. AllOpnds.push_back(&Opnd0_1);
  373. if (Opnd1_ExpNum == 2)
  374. AllOpnds.push_back(&Opnd1_1);
  375. // Compute instruction quota. We should save at least one instruction.
  376. unsigned InstQuota = 0;
  377. Value *V0 = I->getOperand(0);
  378. Value *V1 = I->getOperand(1);
  379. InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
  380. (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
  381. if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
  382. return R;
  383. }
  384. if (OpndNum != 2) {
  385. // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
  386. // splitted into two addends, say "V = X - Y", the instruction would have
  387. // been optimized into "I = Y - X" in the previous steps.
  388. //
  389. const FAddendCoef &CE = Opnd0.getCoef();
  390. return CE.isOne() ? Opnd0.getSymVal() : nullptr;
  391. }
  392. // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
  393. if (Opnd1_ExpNum) {
  394. AddendVect AllOpnds;
  395. AllOpnds.push_back(&Opnd0);
  396. AllOpnds.push_back(&Opnd1_0);
  397. if (Opnd1_ExpNum == 2)
  398. AllOpnds.push_back(&Opnd1_1);
  399. if (Value *R = simplifyFAdd(AllOpnds, 1))
  400. return R;
  401. }
  402. // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
  403. if (Opnd0_ExpNum) {
  404. AddendVect AllOpnds;
  405. AllOpnds.push_back(&Opnd1);
  406. AllOpnds.push_back(&Opnd0_0);
  407. if (Opnd0_ExpNum == 2)
  408. AllOpnds.push_back(&Opnd0_1);
  409. if (Value *R = simplifyFAdd(AllOpnds, 1))
  410. return R;
  411. }
  412. return nullptr;
  413. }
  414. Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
  415. unsigned AddendNum = Addends.size();
  416. assert(AddendNum <= 4 && "Too many addends");
  417. // For saving intermediate results;
  418. unsigned NextTmpIdx = 0;
  419. FAddend TmpResult[3];
  420. // Simplified addends are placed <SimpVect>.
  421. AddendVect SimpVect;
  422. // The outer loop works on one symbolic-value at a time. Suppose the input
  423. // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
  424. // The symbolic-values will be processed in this order: x, y, z.
  425. for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
  426. const FAddend *ThisAddend = Addends[SymIdx];
  427. if (!ThisAddend) {
  428. // This addend was processed before.
  429. continue;
  430. }
  431. Value *Val = ThisAddend->getSymVal();
  432. // If the resulting expr has constant-addend, this constant-addend is
  433. // desirable to reside at the top of the resulting expression tree. Placing
  434. // constant close to super-expr(s) will potentially reveal some
  435. // optimization opportunities in super-expr(s). Here we do not implement
  436. // this logic intentionally and rely on SimplifyAssociativeOrCommutative
  437. // call later.
  438. unsigned StartIdx = SimpVect.size();
  439. SimpVect.push_back(ThisAddend);
  440. // The inner loop collects addends sharing same symbolic-value, and these
  441. // addends will be later on folded into a single addend. Following above
  442. // example, if the symbolic value "y" is being processed, the inner loop
  443. // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
  444. // be later on folded into "<b1+b2, y>".
  445. for (unsigned SameSymIdx = SymIdx + 1;
  446. SameSymIdx < AddendNum; SameSymIdx++) {
  447. const FAddend *T = Addends[SameSymIdx];
  448. if (T && T->getSymVal() == Val) {
  449. // Set null such that next iteration of the outer loop will not process
  450. // this addend again.
  451. Addends[SameSymIdx] = nullptr;
  452. SimpVect.push_back(T);
  453. }
  454. }
  455. // If multiple addends share same symbolic value, fold them together.
  456. if (StartIdx + 1 != SimpVect.size()) {
  457. FAddend &R = TmpResult[NextTmpIdx ++];
  458. R = *SimpVect[StartIdx];
  459. for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
  460. R += *SimpVect[Idx];
  461. // Pop all addends being folded and push the resulting folded addend.
  462. SimpVect.resize(StartIdx);
  463. if (!R.isZero()) {
  464. SimpVect.push_back(&R);
  465. }
  466. }
  467. }
  468. assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
  469. "out-of-bound access");
  470. Value *Result;
  471. if (!SimpVect.empty())
  472. Result = createNaryFAdd(SimpVect, InstrQuota);
  473. else {
  474. // The addition is folded to 0.0.
  475. Result = ConstantFP::get(Instr->getType(), 0.0);
  476. }
  477. return Result;
  478. }
  479. Value *FAddCombine::createNaryFAdd
  480. (const AddendVect &Opnds, unsigned InstrQuota) {
  481. assert(!Opnds.empty() && "Expect at least one addend");
  482. // Step 1: Check if the # of instructions needed exceeds the quota.
  483. unsigned InstrNeeded = calcInstrNumber(Opnds);
  484. if (InstrNeeded > InstrQuota)
  485. return nullptr;
  486. initCreateInstNum();
  487. // step 2: Emit the N-ary addition.
  488. // Note that at most three instructions are involved in Fadd-InstCombine: the
  489. // addition in question, and at most two neighboring instructions.
  490. // The resulting optimized addition should have at least one less instruction
  491. // than the original addition expression tree. This implies that the resulting
  492. // N-ary addition has at most two instructions, and we don't need to worry
  493. // about tree-height when constructing the N-ary addition.
  494. Value *LastVal = nullptr;
  495. bool LastValNeedNeg = false;
  496. // Iterate the addends, creating fadd/fsub using adjacent two addends.
  497. for (const FAddend *Opnd : Opnds) {
  498. bool NeedNeg;
  499. Value *V = createAddendVal(*Opnd, NeedNeg);
  500. if (!LastVal) {
  501. LastVal = V;
  502. LastValNeedNeg = NeedNeg;
  503. continue;
  504. }
  505. if (LastValNeedNeg == NeedNeg) {
  506. LastVal = createFAdd(LastVal, V);
  507. continue;
  508. }
  509. if (LastValNeedNeg)
  510. LastVal = createFSub(V, LastVal);
  511. else
  512. LastVal = createFSub(LastVal, V);
  513. LastValNeedNeg = false;
  514. }
  515. if (LastValNeedNeg) {
  516. LastVal = createFNeg(LastVal);
  517. }
  518. #ifndef NDEBUG
  519. assert(CreateInstrNum == InstrNeeded &&
  520. "Inconsistent in instruction numbers");
  521. #endif
  522. return LastVal;
  523. }
  524. Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
  525. Value *V = Builder.CreateFSub(Opnd0, Opnd1);
  526. if (Instruction *I = dyn_cast<Instruction>(V))
  527. createInstPostProc(I);
  528. return V;
  529. }
  530. Value *FAddCombine::createFNeg(Value *V) {
  531. Value *NewV = Builder.CreateFNeg(V);
  532. if (Instruction *I = dyn_cast<Instruction>(NewV))
  533. createInstPostProc(I, true); // fneg's don't receive instruction numbers.
  534. return NewV;
  535. }
  536. Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
  537. Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
  538. if (Instruction *I = dyn_cast<Instruction>(V))
  539. createInstPostProc(I);
  540. return V;
  541. }
  542. Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
  543. Value *V = Builder.CreateFMul(Opnd0, Opnd1);
  544. if (Instruction *I = dyn_cast<Instruction>(V))
  545. createInstPostProc(I);
  546. return V;
  547. }
  548. void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
  549. NewInstr->setDebugLoc(Instr->getDebugLoc());
  550. // Keep track of the number of instruction created.
  551. if (!NoNumber)
  552. incCreateInstNum();
  553. // Propagate fast-math flags
  554. NewInstr->setFastMathFlags(Instr->getFastMathFlags());
  555. }
  556. // Return the number of instruction needed to emit the N-ary addition.
  557. // NOTE: Keep this function in sync with createAddendVal().
  558. unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
  559. unsigned OpndNum = Opnds.size();
  560. unsigned InstrNeeded = OpndNum - 1;
  561. // The number of addends in the form of "(-1)*x".
  562. unsigned NegOpndNum = 0;
  563. // Adjust the number of instructions needed to emit the N-ary add.
  564. for (const FAddend *Opnd : Opnds) {
  565. if (Opnd->isConstant())
  566. continue;
  567. // The constant check above is really for a few special constant
  568. // coefficients.
  569. if (isa<UndefValue>(Opnd->getSymVal()))
  570. continue;
  571. const FAddendCoef &CE = Opnd->getCoef();
  572. if (CE.isMinusOne() || CE.isMinusTwo())
  573. NegOpndNum++;
  574. // Let the addend be "c * x". If "c == +/-1", the value of the addend
  575. // is immediately available; otherwise, it needs exactly one instruction
  576. // to evaluate the value.
  577. if (!CE.isMinusOne() && !CE.isOne())
  578. InstrNeeded++;
  579. }
  580. return InstrNeeded;
  581. }
  582. // Input Addend Value NeedNeg(output)
  583. // ================================================================
  584. // Constant C C false
  585. // <+/-1, V> V coefficient is -1
  586. // <2/-2, V> "fadd V, V" coefficient is -2
  587. // <C, V> "fmul V, C" false
  588. //
  589. // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
  590. Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
  591. const FAddendCoef &Coeff = Opnd.getCoef();
  592. if (Opnd.isConstant()) {
  593. NeedNeg = false;
  594. return Coeff.getValue(Instr->getType());
  595. }
  596. Value *OpndVal = Opnd.getSymVal();
  597. if (Coeff.isMinusOne() || Coeff.isOne()) {
  598. NeedNeg = Coeff.isMinusOne();
  599. return OpndVal;
  600. }
  601. if (Coeff.isTwo() || Coeff.isMinusTwo()) {
  602. NeedNeg = Coeff.isMinusTwo();
  603. return createFAdd(OpndVal, OpndVal);
  604. }
  605. NeedNeg = false;
  606. return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
  607. }
  608. // Checks if any operand is negative and we can convert add to sub.
  609. // This function checks for following negative patterns
  610. // ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
  611. // ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
  612. // XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
  613. static Value *checkForNegativeOperand(BinaryOperator &I,
  614. InstCombiner::BuilderTy &Builder) {
  615. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  616. // This function creates 2 instructions to replace ADD, we need at least one
  617. // of LHS or RHS to have one use to ensure benefit in transform.
  618. if (!LHS->hasOneUse() && !RHS->hasOneUse())
  619. return nullptr;
  620. Value *X = nullptr, *Y = nullptr, *Z = nullptr;
  621. const APInt *C1 = nullptr, *C2 = nullptr;
  622. // if ONE is on other side, swap
  623. if (match(RHS, m_Add(m_Value(X), m_One())))
  624. std::swap(LHS, RHS);
  625. if (match(LHS, m_Add(m_Value(X), m_One()))) {
  626. // if XOR on other side, swap
  627. if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
  628. std::swap(X, RHS);
  629. if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
  630. // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
  631. // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
  632. if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
  633. Value *NewAnd = Builder.CreateAnd(Z, *C1);
  634. return Builder.CreateSub(RHS, NewAnd, "sub");
  635. } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
  636. // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
  637. // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
  638. Value *NewOr = Builder.CreateOr(Z, ~(*C1));
  639. return Builder.CreateSub(RHS, NewOr, "sub");
  640. }
  641. }
  642. }
  643. // Restore LHS and RHS
  644. LHS = I.getOperand(0);
  645. RHS = I.getOperand(1);
  646. // if XOR is on other side, swap
  647. if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
  648. std::swap(LHS, RHS);
  649. // C2 is ODD
  650. // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
  651. // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
  652. if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
  653. if (C1->countTrailingZeros() == 0)
  654. if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
  655. Value *NewOr = Builder.CreateOr(Z, ~(*C2));
  656. return Builder.CreateSub(RHS, NewOr, "sub");
  657. }
  658. return nullptr;
  659. }
  660. /// Wrapping flags may allow combining constants separated by an extend.
  661. static Instruction *foldNoWrapAdd(BinaryOperator &Add,
  662. InstCombiner::BuilderTy &Builder) {
  663. Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
  664. Type *Ty = Add.getType();
  665. Constant *Op1C;
  666. if (!match(Op1, m_Constant(Op1C)))
  667. return nullptr;
  668. // Try this match first because it results in an add in the narrow type.
  669. // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
  670. Value *X;
  671. const APInt *C1, *C2;
  672. if (match(Op1, m_APInt(C1)) &&
  673. match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
  674. C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
  675. Constant *NewC =
  676. ConstantInt::get(X->getType(), *C2 + C1->trunc(C2->getBitWidth()));
  677. return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
  678. }
  679. // More general combining of constants in the wide type.
  680. // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
  681. Constant *NarrowC;
  682. if (match(Op0, m_OneUse(m_SExt(m_NSWAdd(m_Value(X), m_Constant(NarrowC)))))) {
  683. Constant *WideC = ConstantExpr::getSExt(NarrowC, Ty);
  684. Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
  685. Value *WideX = Builder.CreateSExt(X, Ty);
  686. return BinaryOperator::CreateAdd(WideX, NewC);
  687. }
  688. // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
  689. if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_Constant(NarrowC)))))) {
  690. Constant *WideC = ConstantExpr::getZExt(NarrowC, Ty);
  691. Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
  692. Value *WideX = Builder.CreateZExt(X, Ty);
  693. return BinaryOperator::CreateAdd(WideX, NewC);
  694. }
  695. return nullptr;
  696. }
  697. Instruction *InstCombinerImpl::foldAddWithConstant(BinaryOperator &Add) {
  698. Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
  699. Constant *Op1C;
  700. if (!match(Op1, m_ImmConstant(Op1C)))
  701. return nullptr;
  702. if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
  703. return NV;
  704. Value *X;
  705. Constant *Op00C;
  706. // add (sub C1, X), C2 --> sub (add C1, C2), X
  707. if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
  708. return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
  709. Value *Y;
  710. // add (sub X, Y), -1 --> add (not Y), X
  711. if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
  712. match(Op1, m_AllOnes()))
  713. return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
  714. // zext(bool) + C -> bool ? C + 1 : C
  715. if (match(Op0, m_ZExt(m_Value(X))) &&
  716. X->getType()->getScalarSizeInBits() == 1)
  717. return SelectInst::Create(X, InstCombiner::AddOne(Op1C), Op1);
  718. // sext(bool) + C -> bool ? C - 1 : C
  719. if (match(Op0, m_SExt(m_Value(X))) &&
  720. X->getType()->getScalarSizeInBits() == 1)
  721. return SelectInst::Create(X, InstCombiner::SubOne(Op1C), Op1);
  722. // ~X + C --> (C-1) - X
  723. if (match(Op0, m_Not(m_Value(X))))
  724. return BinaryOperator::CreateSub(InstCombiner::SubOne(Op1C), X);
  725. const APInt *C;
  726. if (!match(Op1, m_APInt(C)))
  727. return nullptr;
  728. // (X | Op01C) + Op1C --> X + (Op01C + Op1C) iff the `or` is actually an `add`
  729. Constant *Op01C;
  730. if (match(Op0, m_Or(m_Value(X), m_ImmConstant(Op01C))) &&
  731. haveNoCommonBitsSet(X, Op01C, DL, &AC, &Add, &DT))
  732. return BinaryOperator::CreateAdd(X, ConstantExpr::getAdd(Op01C, Op1C));
  733. // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
  734. const APInt *C2;
  735. if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
  736. return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
  737. if (C->isSignMask()) {
  738. // If wrapping is not allowed, then the addition must set the sign bit:
  739. // X + (signmask) --> X | signmask
  740. if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
  741. return BinaryOperator::CreateOr(Op0, Op1);
  742. // If wrapping is allowed, then the addition flips the sign bit of LHS:
  743. // X + (signmask) --> X ^ signmask
  744. return BinaryOperator::CreateXor(Op0, Op1);
  745. }
  746. // Is this add the last step in a convoluted sext?
  747. // add(zext(xor i16 X, -32768), -32768) --> sext X
  748. Type *Ty = Add.getType();
  749. if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
  750. C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
  751. return CastInst::Create(Instruction::SExt, X, Ty);
  752. if (match(Op0, m_Xor(m_Value(X), m_APInt(C2)))) {
  753. // (X ^ signmask) + C --> (X + (signmask ^ C))
  754. if (C2->isSignMask())
  755. return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C2 ^ *C));
  756. // If X has no high-bits set above an xor mask:
  757. // add (xor X, LowMaskC), C --> sub (LowMaskC + C), X
  758. if (C2->isMask()) {
  759. KnownBits LHSKnown = computeKnownBits(X, 0, &Add);
  760. if ((*C2 | LHSKnown.Zero).isAllOnes())
  761. return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C2 + *C), X);
  762. }
  763. // Look for a math+logic pattern that corresponds to sext-in-register of a
  764. // value with cleared high bits. Convert that into a pair of shifts:
  765. // add (xor X, 0x80), 0xF..F80 --> (X << ShAmtC) >>s ShAmtC
  766. // add (xor X, 0xF..F80), 0x80 --> (X << ShAmtC) >>s ShAmtC
  767. if (Op0->hasOneUse() && *C2 == -(*C)) {
  768. unsigned BitWidth = Ty->getScalarSizeInBits();
  769. unsigned ShAmt = 0;
  770. if (C->isPowerOf2())
  771. ShAmt = BitWidth - C->logBase2() - 1;
  772. else if (C2->isPowerOf2())
  773. ShAmt = BitWidth - C2->logBase2() - 1;
  774. if (ShAmt && MaskedValueIsZero(X, APInt::getHighBitsSet(BitWidth, ShAmt),
  775. 0, &Add)) {
  776. Constant *ShAmtC = ConstantInt::get(Ty, ShAmt);
  777. Value *NewShl = Builder.CreateShl(X, ShAmtC, "sext");
  778. return BinaryOperator::CreateAShr(NewShl, ShAmtC);
  779. }
  780. }
  781. }
  782. if (C->isOne() && Op0->hasOneUse()) {
  783. // add (sext i1 X), 1 --> zext (not X)
  784. // TODO: The smallest IR representation is (select X, 0, 1), and that would
  785. // not require the one-use check. But we need to remove a transform in
  786. // visitSelect and make sure that IR value tracking for select is equal or
  787. // better than for these ops.
  788. if (match(Op0, m_SExt(m_Value(X))) &&
  789. X->getType()->getScalarSizeInBits() == 1)
  790. return new ZExtInst(Builder.CreateNot(X), Ty);
  791. // Shifts and add used to flip and mask off the low bit:
  792. // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
  793. const APInt *C3;
  794. if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
  795. C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
  796. Value *NotX = Builder.CreateNot(X);
  797. return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
  798. }
  799. }
  800. // If all bits affected by the add are included in a high-bit-mask, do the
  801. // add before the mask op:
  802. // (X & 0xFF00) + xx00 --> (X + xx00) & 0xFF00
  803. if (match(Op0, m_OneUse(m_And(m_Value(X), m_APInt(C2)))) &&
  804. C2->isNegative() && C2->isShiftedMask() && *C == (*C & *C2)) {
  805. Value *NewAdd = Builder.CreateAdd(X, ConstantInt::get(Ty, *C));
  806. return BinaryOperator::CreateAnd(NewAdd, ConstantInt::get(Ty, *C2));
  807. }
  808. return nullptr;
  809. }
  810. // Matches multiplication expression Op * C where C is a constant. Returns the
  811. // constant value in C and the other operand in Op. Returns true if such a
  812. // match is found.
  813. static bool MatchMul(Value *E, Value *&Op, APInt &C) {
  814. const APInt *AI;
  815. if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
  816. C = *AI;
  817. return true;
  818. }
  819. if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
  820. C = APInt(AI->getBitWidth(), 1);
  821. C <<= *AI;
  822. return true;
  823. }
  824. return false;
  825. }
  826. // Matches remainder expression Op % C where C is a constant. Returns the
  827. // constant value in C and the other operand in Op. Returns the signedness of
  828. // the remainder operation in IsSigned. Returns true if such a match is
  829. // found.
  830. static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
  831. const APInt *AI;
  832. IsSigned = false;
  833. if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
  834. IsSigned = true;
  835. C = *AI;
  836. return true;
  837. }
  838. if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
  839. C = *AI;
  840. return true;
  841. }
  842. if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
  843. C = *AI + 1;
  844. return true;
  845. }
  846. return false;
  847. }
  848. // Matches division expression Op / C with the given signedness as indicated
  849. // by IsSigned, where C is a constant. Returns the constant value in C and the
  850. // other operand in Op. Returns true if such a match is found.
  851. static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
  852. const APInt *AI;
  853. if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
  854. C = *AI;
  855. return true;
  856. }
  857. if (!IsSigned) {
  858. if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
  859. C = *AI;
  860. return true;
  861. }
  862. if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
  863. C = APInt(AI->getBitWidth(), 1);
  864. C <<= *AI;
  865. return true;
  866. }
  867. }
  868. return false;
  869. }
  870. // Returns whether C0 * C1 with the given signedness overflows.
  871. static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
  872. bool overflow;
  873. if (IsSigned)
  874. (void)C0.smul_ov(C1, overflow);
  875. else
  876. (void)C0.umul_ov(C1, overflow);
  877. return overflow;
  878. }
  879. // Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
  880. // does not overflow.
  881. Value *InstCombinerImpl::SimplifyAddWithRemainder(BinaryOperator &I) {
  882. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  883. Value *X, *MulOpV;
  884. APInt C0, MulOpC;
  885. bool IsSigned;
  886. // Match I = X % C0 + MulOpV * C0
  887. if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
  888. (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
  889. C0 == MulOpC) {
  890. Value *RemOpV;
  891. APInt C1;
  892. bool Rem2IsSigned;
  893. // Match MulOpC = RemOpV % C1
  894. if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
  895. IsSigned == Rem2IsSigned) {
  896. Value *DivOpV;
  897. APInt DivOpC;
  898. // Match RemOpV = X / C0
  899. if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
  900. C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
  901. Value *NewDivisor = ConstantInt::get(X->getType(), C0 * C1);
  902. return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
  903. : Builder.CreateURem(X, NewDivisor, "urem");
  904. }
  905. }
  906. }
  907. return nullptr;
  908. }
  909. /// Fold
  910. /// (1 << NBits) - 1
  911. /// Into:
  912. /// ~(-(1 << NBits))
  913. /// Because a 'not' is better for bit-tracking analysis and other transforms
  914. /// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
  915. static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
  916. InstCombiner::BuilderTy &Builder) {
  917. Value *NBits;
  918. if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
  919. return nullptr;
  920. Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
  921. Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
  922. // Be wary of constant folding.
  923. if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
  924. // Always NSW. But NUW propagates from `add`.
  925. BOp->setHasNoSignedWrap();
  926. BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
  927. }
  928. return BinaryOperator::CreateNot(NotMask, I.getName());
  929. }
  930. static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
  931. assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
  932. Type *Ty = I.getType();
  933. auto getUAddSat = [&]() {
  934. return Intrinsic::getDeclaration(I.getModule(), Intrinsic::uadd_sat, Ty);
  935. };
  936. // add (umin X, ~Y), Y --> uaddsat X, Y
  937. Value *X, *Y;
  938. if (match(&I, m_c_Add(m_c_UMin(m_Value(X), m_Not(m_Value(Y))),
  939. m_Deferred(Y))))
  940. return CallInst::Create(getUAddSat(), { X, Y });
  941. // add (umin X, ~C), C --> uaddsat X, C
  942. const APInt *C, *NotC;
  943. if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
  944. *C == ~*NotC)
  945. return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
  946. return nullptr;
  947. }
  948. Instruction *InstCombinerImpl::
  949. canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
  950. BinaryOperator &I) {
  951. assert((I.getOpcode() == Instruction::Add ||
  952. I.getOpcode() == Instruction::Or ||
  953. I.getOpcode() == Instruction::Sub) &&
  954. "Expecting add/or/sub instruction");
  955. // We have a subtraction/addition between a (potentially truncated) *logical*
  956. // right-shift of X and a "select".
  957. Value *X, *Select;
  958. Instruction *LowBitsToSkip, *Extract;
  959. if (!match(&I, m_c_BinOp(m_TruncOrSelf(m_CombineAnd(
  960. m_LShr(m_Value(X), m_Instruction(LowBitsToSkip)),
  961. m_Instruction(Extract))),
  962. m_Value(Select))))
  963. return nullptr;
  964. // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
  965. if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
  966. return nullptr;
  967. Type *XTy = X->getType();
  968. bool HadTrunc = I.getType() != XTy;
  969. // If there was a truncation of extracted value, then we'll need to produce
  970. // one extra instruction, so we need to ensure one instruction will go away.
  971. if (HadTrunc && !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
  972. return nullptr;
  973. // Extraction should extract high NBits bits, with shift amount calculated as:
  974. // low bits to skip = shift bitwidth - high bits to extract
  975. // The shift amount itself may be extended, and we need to look past zero-ext
  976. // when matching NBits, that will matter for matching later.
  977. Constant *C;
  978. Value *NBits;
  979. if (!match(
  980. LowBitsToSkip,
  981. m_ZExtOrSelf(m_Sub(m_Constant(C), m_ZExtOrSelf(m_Value(NBits))))) ||
  982. !match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
  983. APInt(C->getType()->getScalarSizeInBits(),
  984. X->getType()->getScalarSizeInBits()))))
  985. return nullptr;
  986. // Sign-extending value can be zero-extended if we `sub`tract it,
  987. // or sign-extended otherwise.
  988. auto SkipExtInMagic = [&I](Value *&V) {
  989. if (I.getOpcode() == Instruction::Sub)
  990. match(V, m_ZExtOrSelf(m_Value(V)));
  991. else
  992. match(V, m_SExtOrSelf(m_Value(V)));
  993. };
  994. // Now, finally validate the sign-extending magic.
  995. // `select` itself may be appropriately extended, look past that.
  996. SkipExtInMagic(Select);
  997. ICmpInst::Predicate Pred;
  998. const APInt *Thr;
  999. Value *SignExtendingValue, *Zero;
  1000. bool ShouldSignext;
  1001. // It must be a select between two values we will later establish to be a
  1002. // sign-extending value and a zero constant. The condition guarding the
  1003. // sign-extension must be based on a sign bit of the same X we had in `lshr`.
  1004. if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
  1005. m_Value(SignExtendingValue), m_Value(Zero))) ||
  1006. !isSignBitCheck(Pred, *Thr, ShouldSignext))
  1007. return nullptr;
  1008. // icmp-select pair is commutative.
  1009. if (!ShouldSignext)
  1010. std::swap(SignExtendingValue, Zero);
  1011. // If we should not perform sign-extension then we must add/or/subtract zero.
  1012. if (!match(Zero, m_Zero()))
  1013. return nullptr;
  1014. // Otherwise, it should be some constant, left-shifted by the same NBits we
  1015. // had in `lshr`. Said left-shift can also be appropriately extended.
  1016. // Again, we must look past zero-ext when looking for NBits.
  1017. SkipExtInMagic(SignExtendingValue);
  1018. Constant *SignExtendingValueBaseConstant;
  1019. if (!match(SignExtendingValue,
  1020. m_Shl(m_Constant(SignExtendingValueBaseConstant),
  1021. m_ZExtOrSelf(m_Specific(NBits)))))
  1022. return nullptr;
  1023. // If we `sub`, then the constant should be one, else it should be all-ones.
  1024. if (I.getOpcode() == Instruction::Sub
  1025. ? !match(SignExtendingValueBaseConstant, m_One())
  1026. : !match(SignExtendingValueBaseConstant, m_AllOnes()))
  1027. return nullptr;
  1028. auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
  1029. Extract->getName() + ".sext");
  1030. NewAShr->copyIRFlags(Extract); // Preserve `exact`-ness.
  1031. if (!HadTrunc)
  1032. return NewAShr;
  1033. Builder.Insert(NewAShr);
  1034. return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
  1035. }
  1036. /// This is a specialization of a more general transform from
  1037. /// SimplifyUsingDistributiveLaws. If that code can be made to work optimally
  1038. /// for multi-use cases or propagating nsw/nuw, then we would not need this.
  1039. static Instruction *factorizeMathWithShlOps(BinaryOperator &I,
  1040. InstCombiner::BuilderTy &Builder) {
  1041. // TODO: Also handle mul by doubling the shift amount?
  1042. assert((I.getOpcode() == Instruction::Add ||
  1043. I.getOpcode() == Instruction::Sub) &&
  1044. "Expected add/sub");
  1045. auto *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
  1046. auto *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
  1047. if (!Op0 || !Op1 || !(Op0->hasOneUse() || Op1->hasOneUse()))
  1048. return nullptr;
  1049. Value *X, *Y, *ShAmt;
  1050. if (!match(Op0, m_Shl(m_Value(X), m_Value(ShAmt))) ||
  1051. !match(Op1, m_Shl(m_Value(Y), m_Specific(ShAmt))))
  1052. return nullptr;
  1053. // No-wrap propagates only when all ops have no-wrap.
  1054. bool HasNSW = I.hasNoSignedWrap() && Op0->hasNoSignedWrap() &&
  1055. Op1->hasNoSignedWrap();
  1056. bool HasNUW = I.hasNoUnsignedWrap() && Op0->hasNoUnsignedWrap() &&
  1057. Op1->hasNoUnsignedWrap();
  1058. // add/sub (X << ShAmt), (Y << ShAmt) --> (add/sub X, Y) << ShAmt
  1059. Value *NewMath = Builder.CreateBinOp(I.getOpcode(), X, Y);
  1060. if (auto *NewI = dyn_cast<BinaryOperator>(NewMath)) {
  1061. NewI->setHasNoSignedWrap(HasNSW);
  1062. NewI->setHasNoUnsignedWrap(HasNUW);
  1063. }
  1064. auto *NewShl = BinaryOperator::CreateShl(NewMath, ShAmt);
  1065. NewShl->setHasNoSignedWrap(HasNSW);
  1066. NewShl->setHasNoUnsignedWrap(HasNUW);
  1067. return NewShl;
  1068. }
  1069. Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
  1070. if (Value *V = SimplifyAddInst(I.getOperand(0), I.getOperand(1),
  1071. I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
  1072. SQ.getWithInstruction(&I)))
  1073. return replaceInstUsesWith(I, V);
  1074. if (SimplifyAssociativeOrCommutative(I))
  1075. return &I;
  1076. if (Instruction *X = foldVectorBinop(I))
  1077. return X;
  1078. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  1079. return Phi;
  1080. // (A*B)+(A*C) -> A*(B+C) etc
  1081. if (Value *V = SimplifyUsingDistributiveLaws(I))
  1082. return replaceInstUsesWith(I, V);
  1083. if (Instruction *R = factorizeMathWithShlOps(I, Builder))
  1084. return R;
  1085. if (Instruction *X = foldAddWithConstant(I))
  1086. return X;
  1087. if (Instruction *X = foldNoWrapAdd(I, Builder))
  1088. return X;
  1089. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  1090. Type *Ty = I.getType();
  1091. if (Ty->isIntOrIntVectorTy(1))
  1092. return BinaryOperator::CreateXor(LHS, RHS);
  1093. // X + X --> X << 1
  1094. if (LHS == RHS) {
  1095. auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
  1096. Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
  1097. Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
  1098. return Shl;
  1099. }
  1100. Value *A, *B;
  1101. if (match(LHS, m_Neg(m_Value(A)))) {
  1102. // -A + -B --> -(A + B)
  1103. if (match(RHS, m_Neg(m_Value(B))))
  1104. return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
  1105. // -A + B --> B - A
  1106. return BinaryOperator::CreateSub(RHS, A);
  1107. }
  1108. // A + -B --> A - B
  1109. if (match(RHS, m_Neg(m_Value(B))))
  1110. return BinaryOperator::CreateSub(LHS, B);
  1111. if (Value *V = checkForNegativeOperand(I, Builder))
  1112. return replaceInstUsesWith(I, V);
  1113. // (A + 1) + ~B --> A - B
  1114. // ~B + (A + 1) --> A - B
  1115. // (~B + A) + 1 --> A - B
  1116. // (A + ~B) + 1 --> A - B
  1117. if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
  1118. match(&I, m_BinOp(m_c_Add(m_Not(m_Value(B)), m_Value(A)), m_One())))
  1119. return BinaryOperator::CreateSub(A, B);
  1120. // (A + RHS) + RHS --> A + (RHS << 1)
  1121. if (match(LHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(RHS)))))
  1122. return BinaryOperator::CreateAdd(A, Builder.CreateShl(RHS, 1, "reass.add"));
  1123. // LHS + (A + LHS) --> A + (LHS << 1)
  1124. if (match(RHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(LHS)))))
  1125. return BinaryOperator::CreateAdd(A, Builder.CreateShl(LHS, 1, "reass.add"));
  1126. {
  1127. // (A + C1) + (C2 - B) --> (A - B) + (C1 + C2)
  1128. Constant *C1, *C2;
  1129. if (match(&I, m_c_Add(m_Add(m_Value(A), m_ImmConstant(C1)),
  1130. m_Sub(m_ImmConstant(C2), m_Value(B)))) &&
  1131. (LHS->hasOneUse() || RHS->hasOneUse())) {
  1132. Value *Sub = Builder.CreateSub(A, B);
  1133. return BinaryOperator::CreateAdd(Sub, ConstantExpr::getAdd(C1, C2));
  1134. }
  1135. }
  1136. // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
  1137. if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
  1138. // ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
  1139. const APInt *C1, *C2;
  1140. if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
  1141. APInt one(C2->getBitWidth(), 1);
  1142. APInt minusC1 = -(*C1);
  1143. if (minusC1 == (one << *C2)) {
  1144. Constant *NewRHS = ConstantInt::get(RHS->getType(), minusC1);
  1145. return BinaryOperator::CreateSRem(RHS, NewRHS);
  1146. }
  1147. }
  1148. // A+B --> A|B iff A and B have no bits set in common.
  1149. if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
  1150. return BinaryOperator::CreateOr(LHS, RHS);
  1151. // add (select X 0 (sub n A)) A --> select X A n
  1152. {
  1153. SelectInst *SI = dyn_cast<SelectInst>(LHS);
  1154. Value *A = RHS;
  1155. if (!SI) {
  1156. SI = dyn_cast<SelectInst>(RHS);
  1157. A = LHS;
  1158. }
  1159. if (SI && SI->hasOneUse()) {
  1160. Value *TV = SI->getTrueValue();
  1161. Value *FV = SI->getFalseValue();
  1162. Value *N;
  1163. // Can we fold the add into the argument of the select?
  1164. // We check both true and false select arguments for a matching subtract.
  1165. if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
  1166. // Fold the add into the true select value.
  1167. return SelectInst::Create(SI->getCondition(), N, A);
  1168. if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
  1169. // Fold the add into the false select value.
  1170. return SelectInst::Create(SI->getCondition(), A, N);
  1171. }
  1172. }
  1173. if (Instruction *Ext = narrowMathIfNoOverflow(I))
  1174. return Ext;
  1175. // (add (xor A, B) (and A, B)) --> (or A, B)
  1176. // (add (and A, B) (xor A, B)) --> (or A, B)
  1177. if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
  1178. m_c_And(m_Deferred(A), m_Deferred(B)))))
  1179. return BinaryOperator::CreateOr(A, B);
  1180. // (add (or A, B) (and A, B)) --> (add A, B)
  1181. // (add (and A, B) (or A, B)) --> (add A, B)
  1182. if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
  1183. m_c_And(m_Deferred(A), m_Deferred(B))))) {
  1184. // Replacing operands in-place to preserve nuw/nsw flags.
  1185. replaceOperand(I, 0, A);
  1186. replaceOperand(I, 1, B);
  1187. return &I;
  1188. }
  1189. // TODO(jingyue): Consider willNotOverflowSignedAdd and
  1190. // willNotOverflowUnsignedAdd to reduce the number of invocations of
  1191. // computeKnownBits.
  1192. bool Changed = false;
  1193. if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
  1194. Changed = true;
  1195. I.setHasNoSignedWrap(true);
  1196. }
  1197. if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
  1198. Changed = true;
  1199. I.setHasNoUnsignedWrap(true);
  1200. }
  1201. if (Instruction *V = canonicalizeLowbitMask(I, Builder))
  1202. return V;
  1203. if (Instruction *V =
  1204. canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
  1205. return V;
  1206. if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
  1207. return SatAdd;
  1208. // usub.sat(A, B) + B => umax(A, B)
  1209. if (match(&I, m_c_BinOp(
  1210. m_OneUse(m_Intrinsic<Intrinsic::usub_sat>(m_Value(A), m_Value(B))),
  1211. m_Deferred(B)))) {
  1212. return replaceInstUsesWith(I,
  1213. Builder.CreateIntrinsic(Intrinsic::umax, {I.getType()}, {A, B}));
  1214. }
  1215. // ctpop(A) + ctpop(B) => ctpop(A | B) if A and B have no bits set in common.
  1216. if (match(LHS, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(A)))) &&
  1217. match(RHS, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(B)))) &&
  1218. haveNoCommonBitsSet(A, B, DL, &AC, &I, &DT))
  1219. return replaceInstUsesWith(
  1220. I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
  1221. {Builder.CreateOr(A, B)}));
  1222. return Changed ? &I : nullptr;
  1223. }
  1224. /// Eliminate an op from a linear interpolation (lerp) pattern.
  1225. static Instruction *factorizeLerp(BinaryOperator &I,
  1226. InstCombiner::BuilderTy &Builder) {
  1227. Value *X, *Y, *Z;
  1228. if (!match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_Value(Y),
  1229. m_OneUse(m_FSub(m_FPOne(),
  1230. m_Value(Z))))),
  1231. m_OneUse(m_c_FMul(m_Value(X), m_Deferred(Z))))))
  1232. return nullptr;
  1233. // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
  1234. Value *XY = Builder.CreateFSubFMF(X, Y, &I);
  1235. Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
  1236. return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
  1237. }
  1238. /// Factor a common operand out of fadd/fsub of fmul/fdiv.
  1239. static Instruction *factorizeFAddFSub(BinaryOperator &I,
  1240. InstCombiner::BuilderTy &Builder) {
  1241. assert((I.getOpcode() == Instruction::FAdd ||
  1242. I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
  1243. assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
  1244. "FP factorization requires FMF");
  1245. if (Instruction *Lerp = factorizeLerp(I, Builder))
  1246. return Lerp;
  1247. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1248. if (!Op0->hasOneUse() || !Op1->hasOneUse())
  1249. return nullptr;
  1250. Value *X, *Y, *Z;
  1251. bool IsFMul;
  1252. if ((match(Op0, m_FMul(m_Value(X), m_Value(Z))) &&
  1253. match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))) ||
  1254. (match(Op0, m_FMul(m_Value(Z), m_Value(X))) &&
  1255. match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))))
  1256. IsFMul = true;
  1257. else if (match(Op0, m_FDiv(m_Value(X), m_Value(Z))) &&
  1258. match(Op1, m_FDiv(m_Value(Y), m_Specific(Z))))
  1259. IsFMul = false;
  1260. else
  1261. return nullptr;
  1262. // (X * Z) + (Y * Z) --> (X + Y) * Z
  1263. // (X * Z) - (Y * Z) --> (X - Y) * Z
  1264. // (X / Z) + (Y / Z) --> (X + Y) / Z
  1265. // (X / Z) - (Y / Z) --> (X - Y) / Z
  1266. bool IsFAdd = I.getOpcode() == Instruction::FAdd;
  1267. Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
  1268. : Builder.CreateFSubFMF(X, Y, &I);
  1269. // Bail out if we just created a denormal constant.
  1270. // TODO: This is copied from a previous implementation. Is it necessary?
  1271. const APFloat *C;
  1272. if (match(XY, m_APFloat(C)) && !C->isNormal())
  1273. return nullptr;
  1274. return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
  1275. : BinaryOperator::CreateFDivFMF(XY, Z, &I);
  1276. }
  1277. Instruction *InstCombinerImpl::visitFAdd(BinaryOperator &I) {
  1278. if (Value *V = SimplifyFAddInst(I.getOperand(0), I.getOperand(1),
  1279. I.getFastMathFlags(),
  1280. SQ.getWithInstruction(&I)))
  1281. return replaceInstUsesWith(I, V);
  1282. if (SimplifyAssociativeOrCommutative(I))
  1283. return &I;
  1284. if (Instruction *X = foldVectorBinop(I))
  1285. return X;
  1286. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  1287. return Phi;
  1288. if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
  1289. return FoldedFAdd;
  1290. // (-X) + Y --> Y - X
  1291. Value *X, *Y;
  1292. if (match(&I, m_c_FAdd(m_FNeg(m_Value(X)), m_Value(Y))))
  1293. return BinaryOperator::CreateFSubFMF(Y, X, &I);
  1294. // Similar to above, but look through fmul/fdiv for the negated term.
  1295. // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
  1296. Value *Z;
  1297. if (match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))),
  1298. m_Value(Z)))) {
  1299. Value *XY = Builder.CreateFMulFMF(X, Y, &I);
  1300. return BinaryOperator::CreateFSubFMF(Z, XY, &I);
  1301. }
  1302. // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
  1303. // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
  1304. if (match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y))),
  1305. m_Value(Z))) ||
  1306. match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))),
  1307. m_Value(Z)))) {
  1308. Value *XY = Builder.CreateFDivFMF(X, Y, &I);
  1309. return BinaryOperator::CreateFSubFMF(Z, XY, &I);
  1310. }
  1311. // Check for (fadd double (sitofp x), y), see if we can merge this into an
  1312. // integer add followed by a promotion.
  1313. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  1314. if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
  1315. Value *LHSIntVal = LHSConv->getOperand(0);
  1316. Type *FPType = LHSConv->getType();
  1317. // TODO: This check is overly conservative. In many cases known bits
  1318. // analysis can tell us that the result of the addition has less significant
  1319. // bits than the integer type can hold.
  1320. auto IsValidPromotion = [](Type *FTy, Type *ITy) {
  1321. Type *FScalarTy = FTy->getScalarType();
  1322. Type *IScalarTy = ITy->getScalarType();
  1323. // Do we have enough bits in the significand to represent the result of
  1324. // the integer addition?
  1325. unsigned MaxRepresentableBits =
  1326. APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
  1327. return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
  1328. };
  1329. // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
  1330. // ... if the constant fits in the integer value. This is useful for things
  1331. // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
  1332. // requires a constant pool load, and generally allows the add to be better
  1333. // instcombined.
  1334. if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
  1335. if (IsValidPromotion(FPType, LHSIntVal->getType())) {
  1336. Constant *CI =
  1337. ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
  1338. if (LHSConv->hasOneUse() &&
  1339. ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
  1340. willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
  1341. // Insert the new integer add.
  1342. Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
  1343. return new SIToFPInst(NewAdd, I.getType());
  1344. }
  1345. }
  1346. // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
  1347. if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
  1348. Value *RHSIntVal = RHSConv->getOperand(0);
  1349. // It's enough to check LHS types only because we require int types to
  1350. // be the same for this transform.
  1351. if (IsValidPromotion(FPType, LHSIntVal->getType())) {
  1352. // Only do this if x/y have the same type, if at least one of them has a
  1353. // single use (so we don't increase the number of int->fp conversions),
  1354. // and if the integer add will not overflow.
  1355. if (LHSIntVal->getType() == RHSIntVal->getType() &&
  1356. (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
  1357. willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
  1358. // Insert the new integer add.
  1359. Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
  1360. return new SIToFPInst(NewAdd, I.getType());
  1361. }
  1362. }
  1363. }
  1364. }
  1365. // Handle specials cases for FAdd with selects feeding the operation
  1366. if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
  1367. return replaceInstUsesWith(I, V);
  1368. if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
  1369. if (Instruction *F = factorizeFAddFSub(I, Builder))
  1370. return F;
  1371. // Try to fold fadd into start value of reduction intrinsic.
  1372. if (match(&I, m_c_FAdd(m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(
  1373. m_AnyZeroFP(), m_Value(X))),
  1374. m_Value(Y)))) {
  1375. // fadd (rdx 0.0, X), Y --> rdx Y, X
  1376. return replaceInstUsesWith(
  1377. I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
  1378. {X->getType()}, {Y, X}, &I));
  1379. }
  1380. const APFloat *StartC, *C;
  1381. if (match(LHS, m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(
  1382. m_APFloat(StartC), m_Value(X)))) &&
  1383. match(RHS, m_APFloat(C))) {
  1384. // fadd (rdx StartC, X), C --> rdx (C + StartC), X
  1385. Constant *NewStartC = ConstantFP::get(I.getType(), *C + *StartC);
  1386. return replaceInstUsesWith(
  1387. I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
  1388. {X->getType()}, {NewStartC, X}, &I));
  1389. }
  1390. // (X * MulC) + X --> X * (MulC + 1.0)
  1391. Constant *MulC;
  1392. if (match(&I, m_c_FAdd(m_FMul(m_Value(X), m_ImmConstant(MulC)),
  1393. m_Deferred(X)))) {
  1394. MulC = ConstantExpr::getFAdd(MulC, ConstantFP::get(I.getType(), 1.0));
  1395. return BinaryOperator::CreateFMulFMF(X, MulC, &I);
  1396. }
  1397. if (Value *V = FAddCombine(Builder).simplify(&I))
  1398. return replaceInstUsesWith(I, V);
  1399. }
  1400. return nullptr;
  1401. }
  1402. /// Optimize pointer differences into the same array into a size. Consider:
  1403. /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
  1404. /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
  1405. Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
  1406. Type *Ty, bool IsNUW) {
  1407. // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
  1408. // this.
  1409. bool Swapped = false;
  1410. GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
  1411. if (!isa<GEPOperator>(LHS) && isa<GEPOperator>(RHS)) {
  1412. std::swap(LHS, RHS);
  1413. Swapped = true;
  1414. }
  1415. // Require at least one GEP with a common base pointer on both sides.
  1416. if (auto *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
  1417. // (gep X, ...) - X
  1418. if (LHSGEP->getOperand(0) == RHS) {
  1419. GEP1 = LHSGEP;
  1420. } else if (auto *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
  1421. // (gep X, ...) - (gep X, ...)
  1422. if (LHSGEP->getOperand(0)->stripPointerCasts() ==
  1423. RHSGEP->getOperand(0)->stripPointerCasts()) {
  1424. GEP1 = LHSGEP;
  1425. GEP2 = RHSGEP;
  1426. }
  1427. }
  1428. }
  1429. if (!GEP1)
  1430. return nullptr;
  1431. if (GEP2) {
  1432. // (gep X, ...) - (gep X, ...)
  1433. //
  1434. // Avoid duplicating the arithmetic if there are more than one non-constant
  1435. // indices between the two GEPs and either GEP has a non-constant index and
  1436. // multiple users. If zero non-constant index, the result is a constant and
  1437. // there is no duplication. If one non-constant index, the result is an add
  1438. // or sub with a constant, which is no larger than the original code, and
  1439. // there's no duplicated arithmetic, even if either GEP has multiple
  1440. // users. If more than one non-constant indices combined, as long as the GEP
  1441. // with at least one non-constant index doesn't have multiple users, there
  1442. // is no duplication.
  1443. unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
  1444. unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
  1445. if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
  1446. ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
  1447. (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
  1448. return nullptr;
  1449. }
  1450. }
  1451. // Emit the offset of the GEP and an intptr_t.
  1452. Value *Result = EmitGEPOffset(GEP1);
  1453. // If this is a single inbounds GEP and the original sub was nuw,
  1454. // then the final multiplication is also nuw.
  1455. if (auto *I = dyn_cast<Instruction>(Result))
  1456. if (IsNUW && !GEP2 && !Swapped && GEP1->isInBounds() &&
  1457. I->getOpcode() == Instruction::Mul)
  1458. I->setHasNoUnsignedWrap();
  1459. // If we have a 2nd GEP of the same base pointer, subtract the offsets.
  1460. // If both GEPs are inbounds, then the subtract does not have signed overflow.
  1461. if (GEP2) {
  1462. Value *Offset = EmitGEPOffset(GEP2);
  1463. Result = Builder.CreateSub(Result, Offset, "gepdiff", /* NUW */ false,
  1464. GEP1->isInBounds() && GEP2->isInBounds());
  1465. }
  1466. // If we have p - gep(p, ...) then we have to negate the result.
  1467. if (Swapped)
  1468. Result = Builder.CreateNeg(Result, "diff.neg");
  1469. return Builder.CreateIntCast(Result, Ty, true);
  1470. }
  1471. Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
  1472. if (Value *V = SimplifySubInst(I.getOperand(0), I.getOperand(1),
  1473. I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
  1474. SQ.getWithInstruction(&I)))
  1475. return replaceInstUsesWith(I, V);
  1476. if (Instruction *X = foldVectorBinop(I))
  1477. return X;
  1478. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  1479. return Phi;
  1480. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1481. // If this is a 'B = x-(-A)', change to B = x+A.
  1482. // We deal with this without involving Negator to preserve NSW flag.
  1483. if (Value *V = dyn_castNegVal(Op1)) {
  1484. BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
  1485. if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
  1486. assert(BO->getOpcode() == Instruction::Sub &&
  1487. "Expected a subtraction operator!");
  1488. if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
  1489. Res->setHasNoSignedWrap(true);
  1490. } else {
  1491. if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
  1492. Res->setHasNoSignedWrap(true);
  1493. }
  1494. return Res;
  1495. }
  1496. // Try this before Negator to preserve NSW flag.
  1497. if (Instruction *R = factorizeMathWithShlOps(I, Builder))
  1498. return R;
  1499. Constant *C;
  1500. if (match(Op0, m_ImmConstant(C))) {
  1501. Value *X;
  1502. Constant *C2;
  1503. // C-(X+C2) --> (C-C2)-X
  1504. if (match(Op1, m_Add(m_Value(X), m_ImmConstant(C2))))
  1505. return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
  1506. }
  1507. auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
  1508. if (Instruction *Ext = narrowMathIfNoOverflow(I))
  1509. return Ext;
  1510. bool Changed = false;
  1511. if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
  1512. Changed = true;
  1513. I.setHasNoSignedWrap(true);
  1514. }
  1515. if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
  1516. Changed = true;
  1517. I.setHasNoUnsignedWrap(true);
  1518. }
  1519. return Changed ? &I : nullptr;
  1520. };
  1521. // First, let's try to interpret `sub a, b` as `add a, (sub 0, b)`,
  1522. // and let's try to sink `(sub 0, b)` into `b` itself. But only if this isn't
  1523. // a pure negation used by a select that looks like abs/nabs.
  1524. bool IsNegation = match(Op0, m_ZeroInt());
  1525. if (!IsNegation || none_of(I.users(), [&I, Op1](const User *U) {
  1526. const Instruction *UI = dyn_cast<Instruction>(U);
  1527. if (!UI)
  1528. return false;
  1529. return match(UI,
  1530. m_Select(m_Value(), m_Specific(Op1), m_Specific(&I))) ||
  1531. match(UI, m_Select(m_Value(), m_Specific(&I), m_Specific(Op1)));
  1532. })) {
  1533. if (Value *NegOp1 = Negator::Negate(IsNegation, Op1, *this))
  1534. return BinaryOperator::CreateAdd(NegOp1, Op0);
  1535. }
  1536. if (IsNegation)
  1537. return TryToNarrowDeduceFlags(); // Should have been handled in Negator!
  1538. // (A*B)-(A*C) -> A*(B-C) etc
  1539. if (Value *V = SimplifyUsingDistributiveLaws(I))
  1540. return replaceInstUsesWith(I, V);
  1541. if (I.getType()->isIntOrIntVectorTy(1))
  1542. return BinaryOperator::CreateXor(Op0, Op1);
  1543. // Replace (-1 - A) with (~A).
  1544. if (match(Op0, m_AllOnes()))
  1545. return BinaryOperator::CreateNot(Op1);
  1546. // (X + -1) - Y --> ~Y + X
  1547. Value *X, *Y;
  1548. if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
  1549. return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
  1550. // Reassociate sub/add sequences to create more add instructions and
  1551. // reduce dependency chains:
  1552. // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
  1553. Value *Z;
  1554. if (match(Op0, m_OneUse(m_c_Add(m_OneUse(m_Sub(m_Value(X), m_Value(Y))),
  1555. m_Value(Z))))) {
  1556. Value *XZ = Builder.CreateAdd(X, Z);
  1557. Value *YW = Builder.CreateAdd(Y, Op1);
  1558. return BinaryOperator::CreateSub(XZ, YW);
  1559. }
  1560. // ((X - Y) - Op1) --> X - (Y + Op1)
  1561. if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y))))) {
  1562. Value *Add = Builder.CreateAdd(Y, Op1);
  1563. return BinaryOperator::CreateSub(X, Add);
  1564. }
  1565. // (~X) - (~Y) --> Y - X
  1566. // This is placed after the other reassociations and explicitly excludes a
  1567. // sub-of-sub pattern to avoid infinite looping.
  1568. if (isFreeToInvert(Op0, Op0->hasOneUse()) &&
  1569. isFreeToInvert(Op1, Op1->hasOneUse()) &&
  1570. !match(Op0, m_Sub(m_ImmConstant(), m_Value()))) {
  1571. Value *NotOp0 = Builder.CreateNot(Op0);
  1572. Value *NotOp1 = Builder.CreateNot(Op1);
  1573. return BinaryOperator::CreateSub(NotOp1, NotOp0);
  1574. }
  1575. auto m_AddRdx = [](Value *&Vec) {
  1576. return m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_add>(m_Value(Vec)));
  1577. };
  1578. Value *V0, *V1;
  1579. if (match(Op0, m_AddRdx(V0)) && match(Op1, m_AddRdx(V1)) &&
  1580. V0->getType() == V1->getType()) {
  1581. // Difference of sums is sum of differences:
  1582. // add_rdx(V0) - add_rdx(V1) --> add_rdx(V0 - V1)
  1583. Value *Sub = Builder.CreateSub(V0, V1);
  1584. Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_add,
  1585. {Sub->getType()}, {Sub});
  1586. return replaceInstUsesWith(I, Rdx);
  1587. }
  1588. if (Constant *C = dyn_cast<Constant>(Op0)) {
  1589. Value *X;
  1590. if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
  1591. // C - (zext bool) --> bool ? C - 1 : C
  1592. return SelectInst::Create(X, InstCombiner::SubOne(C), C);
  1593. if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
  1594. // C - (sext bool) --> bool ? C + 1 : C
  1595. return SelectInst::Create(X, InstCombiner::AddOne(C), C);
  1596. // C - ~X == X + (1+C)
  1597. if (match(Op1, m_Not(m_Value(X))))
  1598. return BinaryOperator::CreateAdd(X, InstCombiner::AddOne(C));
  1599. // Try to fold constant sub into select arguments.
  1600. if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
  1601. if (Instruction *R = FoldOpIntoSelect(I, SI))
  1602. return R;
  1603. // Try to fold constant sub into PHI values.
  1604. if (PHINode *PN = dyn_cast<PHINode>(Op1))
  1605. if (Instruction *R = foldOpIntoPhi(I, PN))
  1606. return R;
  1607. Constant *C2;
  1608. // C-(C2-X) --> X+(C-C2)
  1609. if (match(Op1, m_Sub(m_ImmConstant(C2), m_Value(X))))
  1610. return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
  1611. }
  1612. const APInt *Op0C;
  1613. if (match(Op0, m_APInt(Op0C)) && Op0C->isMask()) {
  1614. // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
  1615. // zero.
  1616. KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
  1617. if ((*Op0C | RHSKnown.Zero).isAllOnes())
  1618. return BinaryOperator::CreateXor(Op1, Op0);
  1619. }
  1620. {
  1621. Value *Y;
  1622. // X-(X+Y) == -Y X-(Y+X) == -Y
  1623. if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
  1624. return BinaryOperator::CreateNeg(Y);
  1625. // (X-Y)-X == -Y
  1626. if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
  1627. return BinaryOperator::CreateNeg(Y);
  1628. }
  1629. // (sub (or A, B) (and A, B)) --> (xor A, B)
  1630. {
  1631. Value *A, *B;
  1632. if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
  1633. match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
  1634. return BinaryOperator::CreateXor(A, B);
  1635. }
  1636. // (sub (add A, B) (or A, B)) --> (and A, B)
  1637. {
  1638. Value *A, *B;
  1639. if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
  1640. match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
  1641. return BinaryOperator::CreateAnd(A, B);
  1642. }
  1643. // (sub (add A, B) (and A, B)) --> (or A, B)
  1644. {
  1645. Value *A, *B;
  1646. if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
  1647. match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
  1648. return BinaryOperator::CreateOr(A, B);
  1649. }
  1650. // (sub (and A, B) (or A, B)) --> neg (xor A, B)
  1651. {
  1652. Value *A, *B;
  1653. if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
  1654. match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
  1655. (Op0->hasOneUse() || Op1->hasOneUse()))
  1656. return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
  1657. }
  1658. // (sub (or A, B), (xor A, B)) --> (and A, B)
  1659. {
  1660. Value *A, *B;
  1661. if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
  1662. match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
  1663. return BinaryOperator::CreateAnd(A, B);
  1664. }
  1665. // (sub (xor A, B) (or A, B)) --> neg (and A, B)
  1666. {
  1667. Value *A, *B;
  1668. if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
  1669. match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
  1670. (Op0->hasOneUse() || Op1->hasOneUse()))
  1671. return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
  1672. }
  1673. {
  1674. Value *Y;
  1675. // ((X | Y) - X) --> (~X & Y)
  1676. if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
  1677. return BinaryOperator::CreateAnd(
  1678. Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
  1679. }
  1680. {
  1681. // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
  1682. Value *X;
  1683. if (match(Op0, m_OneUse(m_c_And(m_Specific(Op1),
  1684. m_OneUse(m_Neg(m_Value(X))))))) {
  1685. return BinaryOperator::CreateNeg(Builder.CreateAnd(
  1686. Op1, Builder.CreateAdd(X, Constant::getAllOnesValue(I.getType()))));
  1687. }
  1688. }
  1689. {
  1690. // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
  1691. Constant *C;
  1692. if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_Constant(C))))) {
  1693. return BinaryOperator::CreateNeg(
  1694. Builder.CreateAnd(Op1, Builder.CreateNot(C)));
  1695. }
  1696. }
  1697. {
  1698. // If we have a subtraction between some value and a select between
  1699. // said value and something else, sink subtraction into select hands, i.e.:
  1700. // sub (select %Cond, %TrueVal, %FalseVal), %Op1
  1701. // ->
  1702. // select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
  1703. // or
  1704. // sub %Op0, (select %Cond, %TrueVal, %FalseVal)
  1705. // ->
  1706. // select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
  1707. // This will result in select between new subtraction and 0.
  1708. auto SinkSubIntoSelect =
  1709. [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
  1710. auto SubBuilder) -> Instruction * {
  1711. Value *Cond, *TrueVal, *FalseVal;
  1712. if (!match(Select, m_OneUse(m_Select(m_Value(Cond), m_Value(TrueVal),
  1713. m_Value(FalseVal)))))
  1714. return nullptr;
  1715. if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
  1716. return nullptr;
  1717. // While it is really tempting to just create two subtractions and let
  1718. // InstCombine fold one of those to 0, it isn't possible to do so
  1719. // because of worklist visitation order. So ugly it is.
  1720. bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
  1721. Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
  1722. Constant *Zero = Constant::getNullValue(Ty);
  1723. SelectInst *NewSel =
  1724. SelectInst::Create(Cond, OtherHandOfSubIsTrueVal ? Zero : NewSub,
  1725. OtherHandOfSubIsTrueVal ? NewSub : Zero);
  1726. // Preserve prof metadata if any.
  1727. NewSel->copyMetadata(cast<Instruction>(*Select));
  1728. return NewSel;
  1729. };
  1730. if (Instruction *NewSel = SinkSubIntoSelect(
  1731. /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
  1732. [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
  1733. return Builder->CreateSub(OtherHandOfSelect,
  1734. /*OtherHandOfSub=*/Op1);
  1735. }))
  1736. return NewSel;
  1737. if (Instruction *NewSel = SinkSubIntoSelect(
  1738. /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
  1739. [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
  1740. return Builder->CreateSub(/*OtherHandOfSub=*/Op0,
  1741. OtherHandOfSelect);
  1742. }))
  1743. return NewSel;
  1744. }
  1745. // (X - (X & Y)) --> (X & ~Y)
  1746. if (match(Op1, m_c_And(m_Specific(Op0), m_Value(Y))) &&
  1747. (Op1->hasOneUse() || isa<Constant>(Y)))
  1748. return BinaryOperator::CreateAnd(
  1749. Op0, Builder.CreateNot(Y, Y->getName() + ".not"));
  1750. // ~X - Min/Max(~X, Y) -> ~Min/Max(X, ~Y) - X
  1751. // ~X - Min/Max(Y, ~X) -> ~Min/Max(X, ~Y) - X
  1752. // Min/Max(~X, Y) - ~X -> X - ~Min/Max(X, ~Y)
  1753. // Min/Max(Y, ~X) - ~X -> X - ~Min/Max(X, ~Y)
  1754. // As long as Y is freely invertible, this will be neutral or a win.
  1755. // Note: We don't generate the inverse max/min, just create the 'not' of
  1756. // it and let other folds do the rest.
  1757. if (match(Op0, m_Not(m_Value(X))) &&
  1758. match(Op1, m_c_MaxOrMin(m_Specific(Op0), m_Value(Y))) &&
  1759. !Op0->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
  1760. Value *Not = Builder.CreateNot(Op1);
  1761. return BinaryOperator::CreateSub(Not, X);
  1762. }
  1763. if (match(Op1, m_Not(m_Value(X))) &&
  1764. match(Op0, m_c_MaxOrMin(m_Specific(Op1), m_Value(Y))) &&
  1765. !Op1->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
  1766. Value *Not = Builder.CreateNot(Op0);
  1767. return BinaryOperator::CreateSub(X, Not);
  1768. }
  1769. // TODO: This is the same logic as above but handles the cmp-select idioms
  1770. // for min/max, so the use checks are increased to account for the
  1771. // extra instructions. If we canonicalize to intrinsics, this block
  1772. // can likely be removed.
  1773. {
  1774. Value *LHS, *RHS, *A;
  1775. Value *NotA = Op0, *MinMax = Op1;
  1776. SelectPatternFlavor SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
  1777. if (!SelectPatternResult::isMinOrMax(SPF)) {
  1778. NotA = Op1;
  1779. MinMax = Op0;
  1780. SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
  1781. }
  1782. if (SelectPatternResult::isMinOrMax(SPF) &&
  1783. match(NotA, m_Not(m_Value(A))) && (NotA == LHS || NotA == RHS)) {
  1784. if (NotA == LHS)
  1785. std::swap(LHS, RHS);
  1786. // LHS is now Y above and expected to have at least 2 uses (the min/max)
  1787. // NotA is expected to have 2 uses from the min/max and 1 from the sub.
  1788. if (isFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
  1789. !NotA->hasNUsesOrMore(4)) {
  1790. Value *Not = Builder.CreateNot(MinMax);
  1791. if (NotA == Op0)
  1792. return BinaryOperator::CreateSub(Not, A);
  1793. else
  1794. return BinaryOperator::CreateSub(A, Not);
  1795. }
  1796. }
  1797. }
  1798. // Optimize pointer differences into the same array into a size. Consider:
  1799. // &A[10] - &A[0]: we should compile this to "10".
  1800. Value *LHSOp, *RHSOp;
  1801. if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
  1802. match(Op1, m_PtrToInt(m_Value(RHSOp))))
  1803. if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
  1804. I.hasNoUnsignedWrap()))
  1805. return replaceInstUsesWith(I, Res);
  1806. // trunc(p)-trunc(q) -> trunc(p-q)
  1807. if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
  1808. match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
  1809. if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
  1810. /* IsNUW */ false))
  1811. return replaceInstUsesWith(I, Res);
  1812. // Canonicalize a shifty way to code absolute value to the common pattern.
  1813. // There are 2 potential commuted variants.
  1814. // We're relying on the fact that we only do this transform when the shift has
  1815. // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
  1816. // instructions).
  1817. Value *A;
  1818. const APInt *ShAmt;
  1819. Type *Ty = I.getType();
  1820. if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
  1821. Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
  1822. match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
  1823. // B = ashr i32 A, 31 ; smear the sign bit
  1824. // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
  1825. // --> (A < 0) ? -A : A
  1826. Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
  1827. // Copy the nuw/nsw flags from the sub to the negate.
  1828. Value *Neg = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
  1829. I.hasNoSignedWrap());
  1830. return SelectInst::Create(Cmp, Neg, A);
  1831. }
  1832. // If we are subtracting a low-bit masked subset of some value from an add
  1833. // of that same value with no low bits changed, that is clearing some low bits
  1834. // of the sum:
  1835. // sub (X + AddC), (X & AndC) --> and (X + AddC), ~AndC
  1836. const APInt *AddC, *AndC;
  1837. if (match(Op0, m_Add(m_Value(X), m_APInt(AddC))) &&
  1838. match(Op1, m_And(m_Specific(X), m_APInt(AndC)))) {
  1839. unsigned BitWidth = Ty->getScalarSizeInBits();
  1840. unsigned Cttz = AddC->countTrailingZeros();
  1841. APInt HighMask(APInt::getHighBitsSet(BitWidth, BitWidth - Cttz));
  1842. if ((HighMask & *AndC).isZero())
  1843. return BinaryOperator::CreateAnd(Op0, ConstantInt::get(Ty, ~(*AndC)));
  1844. }
  1845. if (Instruction *V =
  1846. canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
  1847. return V;
  1848. // X - usub.sat(X, Y) => umin(X, Y)
  1849. if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::usub_sat>(m_Specific(Op0),
  1850. m_Value(Y)))))
  1851. return replaceInstUsesWith(
  1852. I, Builder.CreateIntrinsic(Intrinsic::umin, {I.getType()}, {Op0, Y}));
  1853. // umax(X, Op1) - Op1 --> usub.sat(X, Op1)
  1854. // TODO: The one-use restriction is not strictly necessary, but it may
  1855. // require improving other pattern matching and/or codegen.
  1856. if (match(Op0, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op1)))))
  1857. return replaceInstUsesWith(
  1858. I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op1}));
  1859. // Op0 - umax(X, Op0) --> 0 - usub.sat(X, Op0)
  1860. if (match(Op1, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op0))))) {
  1861. Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op0});
  1862. return BinaryOperator::CreateNeg(USub);
  1863. }
  1864. // C - ctpop(X) => ctpop(~X) if C is bitwidth
  1865. if (match(Op0, m_SpecificInt(Ty->getScalarSizeInBits())) &&
  1866. match(Op1, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(X)))))
  1867. return replaceInstUsesWith(
  1868. I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
  1869. {Builder.CreateNot(X)}));
  1870. return TryToNarrowDeduceFlags();
  1871. }
  1872. /// This eliminates floating-point negation in either 'fneg(X)' or
  1873. /// 'fsub(-0.0, X)' form by combining into a constant operand.
  1874. static Instruction *foldFNegIntoConstant(Instruction &I) {
  1875. // This is limited with one-use because fneg is assumed better for
  1876. // reassociation and cheaper in codegen than fmul/fdiv.
  1877. // TODO: Should the m_OneUse restriction be removed?
  1878. Instruction *FNegOp;
  1879. if (!match(&I, m_FNeg(m_OneUse(m_Instruction(FNegOp)))))
  1880. return nullptr;
  1881. Value *X;
  1882. Constant *C;
  1883. // Fold negation into constant operand.
  1884. // -(X * C) --> X * (-C)
  1885. if (match(FNegOp, m_FMul(m_Value(X), m_Constant(C))))
  1886. return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
  1887. // -(X / C) --> X / (-C)
  1888. if (match(FNegOp, m_FDiv(m_Value(X), m_Constant(C))))
  1889. return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
  1890. // -(C / X) --> (-C) / X
  1891. if (match(FNegOp, m_FDiv(m_Constant(C), m_Value(X)))) {
  1892. Instruction *FDiv =
  1893. BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
  1894. // Intersect 'nsz' and 'ninf' because those special value exceptions may not
  1895. // apply to the fdiv. Everything else propagates from the fneg.
  1896. // TODO: We could propagate nsz/ninf from fdiv alone?
  1897. FastMathFlags FMF = I.getFastMathFlags();
  1898. FastMathFlags OpFMF = FNegOp->getFastMathFlags();
  1899. FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
  1900. FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
  1901. return FDiv;
  1902. }
  1903. // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
  1904. // -(X + C) --> -X + -C --> -C - X
  1905. if (I.hasNoSignedZeros() && match(FNegOp, m_FAdd(m_Value(X), m_Constant(C))))
  1906. return BinaryOperator::CreateFSubFMF(ConstantExpr::getFNeg(C), X, &I);
  1907. return nullptr;
  1908. }
  1909. static Instruction *hoistFNegAboveFMulFDiv(Instruction &I,
  1910. InstCombiner::BuilderTy &Builder) {
  1911. Value *FNeg;
  1912. if (!match(&I, m_FNeg(m_Value(FNeg))))
  1913. return nullptr;
  1914. Value *X, *Y;
  1915. if (match(FNeg, m_OneUse(m_FMul(m_Value(X), m_Value(Y)))))
  1916. return BinaryOperator::CreateFMulFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
  1917. if (match(FNeg, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))))
  1918. return BinaryOperator::CreateFDivFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
  1919. return nullptr;
  1920. }
  1921. Instruction *InstCombinerImpl::visitFNeg(UnaryOperator &I) {
  1922. Value *Op = I.getOperand(0);
  1923. if (Value *V = SimplifyFNegInst(Op, I.getFastMathFlags(),
  1924. getSimplifyQuery().getWithInstruction(&I)))
  1925. return replaceInstUsesWith(I, V);
  1926. if (Instruction *X = foldFNegIntoConstant(I))
  1927. return X;
  1928. Value *X, *Y;
  1929. // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
  1930. if (I.hasNoSignedZeros() &&
  1931. match(Op, m_OneUse(m_FSub(m_Value(X), m_Value(Y)))))
  1932. return BinaryOperator::CreateFSubFMF(Y, X, &I);
  1933. if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
  1934. return R;
  1935. // Try to eliminate fneg if at least 1 arm of the select is negated.
  1936. Value *Cond;
  1937. if (match(Op, m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y))))) {
  1938. // Unlike most transforms, this one is not safe to propagate nsz unless
  1939. // it is present on the original select. (We are conservatively intersecting
  1940. // the nsz flags from the select and root fneg instruction.)
  1941. auto propagateSelectFMF = [&](SelectInst *S) {
  1942. S->copyFastMathFlags(&I);
  1943. if (auto *OldSel = dyn_cast<SelectInst>(Op))
  1944. if (!OldSel->hasNoSignedZeros())
  1945. S->setHasNoSignedZeros(false);
  1946. };
  1947. // -(Cond ? -P : Y) --> Cond ? P : -Y
  1948. Value *P;
  1949. if (match(X, m_FNeg(m_Value(P)))) {
  1950. Value *NegY = Builder.CreateFNegFMF(Y, &I, Y->getName() + ".neg");
  1951. SelectInst *NewSel = SelectInst::Create(Cond, P, NegY);
  1952. propagateSelectFMF(NewSel);
  1953. return NewSel;
  1954. }
  1955. // -(Cond ? X : -P) --> Cond ? -X : P
  1956. if (match(Y, m_FNeg(m_Value(P)))) {
  1957. Value *NegX = Builder.CreateFNegFMF(X, &I, X->getName() + ".neg");
  1958. SelectInst *NewSel = SelectInst::Create(Cond, NegX, P);
  1959. propagateSelectFMF(NewSel);
  1960. return NewSel;
  1961. }
  1962. }
  1963. return nullptr;
  1964. }
  1965. Instruction *InstCombinerImpl::visitFSub(BinaryOperator &I) {
  1966. if (Value *V = SimplifyFSubInst(I.getOperand(0), I.getOperand(1),
  1967. I.getFastMathFlags(),
  1968. getSimplifyQuery().getWithInstruction(&I)))
  1969. return replaceInstUsesWith(I, V);
  1970. if (Instruction *X = foldVectorBinop(I))
  1971. return X;
  1972. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  1973. return Phi;
  1974. // Subtraction from -0.0 is the canonical form of fneg.
  1975. // fsub -0.0, X ==> fneg X
  1976. // fsub nsz 0.0, X ==> fneg nsz X
  1977. //
  1978. // FIXME This matcher does not respect FTZ or DAZ yet:
  1979. // fsub -0.0, Denorm ==> +-0
  1980. // fneg Denorm ==> -Denorm
  1981. Value *Op;
  1982. if (match(&I, m_FNeg(m_Value(Op))))
  1983. return UnaryOperator::CreateFNegFMF(Op, &I);
  1984. if (Instruction *X = foldFNegIntoConstant(I))
  1985. return X;
  1986. if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
  1987. return R;
  1988. Value *X, *Y;
  1989. Constant *C;
  1990. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1991. // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
  1992. // Canonicalize to fadd to make analysis easier.
  1993. // This can also help codegen because fadd is commutative.
  1994. // Note that if this fsub was really an fneg, the fadd with -0.0 will get
  1995. // killed later. We still limit that particular transform with 'hasOneUse'
  1996. // because an fneg is assumed better/cheaper than a generic fsub.
  1997. if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) {
  1998. if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
  1999. Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
  2000. return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
  2001. }
  2002. }
  2003. // (-X) - Op1 --> -(X + Op1)
  2004. if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Op0) &&
  2005. match(Op0, m_OneUse(m_FNeg(m_Value(X))))) {
  2006. Value *FAdd = Builder.CreateFAddFMF(X, Op1, &I);
  2007. return UnaryOperator::CreateFNegFMF(FAdd, &I);
  2008. }
  2009. if (isa<Constant>(Op0))
  2010. if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
  2011. if (Instruction *NV = FoldOpIntoSelect(I, SI))
  2012. return NV;
  2013. // X - C --> X + (-C)
  2014. // But don't transform constant expressions because there's an inverse fold
  2015. // for X + (-Y) --> X - Y.
  2016. if (match(Op1, m_ImmConstant(C)))
  2017. return BinaryOperator::CreateFAddFMF(Op0, ConstantExpr::getFNeg(C), &I);
  2018. // X - (-Y) --> X + Y
  2019. if (match(Op1, m_FNeg(m_Value(Y))))
  2020. return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
  2021. // Similar to above, but look through a cast of the negated value:
  2022. // X - (fptrunc(-Y)) --> X + fptrunc(Y)
  2023. Type *Ty = I.getType();
  2024. if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
  2025. return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
  2026. // X - (fpext(-Y)) --> X + fpext(Y)
  2027. if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
  2028. return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
  2029. // Similar to above, but look through fmul/fdiv of the negated value:
  2030. // Op0 - (-X * Y) --> Op0 + (X * Y)
  2031. // Op0 - (Y * -X) --> Op0 + (X * Y)
  2032. if (match(Op1, m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))))) {
  2033. Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
  2034. return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
  2035. }
  2036. // Op0 - (-X / Y) --> Op0 + (X / Y)
  2037. // Op0 - (X / -Y) --> Op0 + (X / Y)
  2038. if (match(Op1, m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y)))) ||
  2039. match(Op1, m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))))) {
  2040. Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
  2041. return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
  2042. }
  2043. // Handle special cases for FSub with selects feeding the operation
  2044. if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
  2045. return replaceInstUsesWith(I, V);
  2046. if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
  2047. // (Y - X) - Y --> -X
  2048. if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
  2049. return UnaryOperator::CreateFNegFMF(X, &I);
  2050. // Y - (X + Y) --> -X
  2051. // Y - (Y + X) --> -X
  2052. if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
  2053. return UnaryOperator::CreateFNegFMF(X, &I);
  2054. // (X * C) - X --> X * (C - 1.0)
  2055. if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
  2056. Constant *CSubOne = ConstantExpr::getFSub(C, ConstantFP::get(Ty, 1.0));
  2057. return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
  2058. }
  2059. // X - (X * C) --> X * (1.0 - C)
  2060. if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
  2061. Constant *OneSubC = ConstantExpr::getFSub(ConstantFP::get(Ty, 1.0), C);
  2062. return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
  2063. }
  2064. // Reassociate fsub/fadd sequences to create more fadd instructions and
  2065. // reduce dependency chains:
  2066. // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
  2067. Value *Z;
  2068. if (match(Op0, m_OneUse(m_c_FAdd(m_OneUse(m_FSub(m_Value(X), m_Value(Y))),
  2069. m_Value(Z))))) {
  2070. Value *XZ = Builder.CreateFAddFMF(X, Z, &I);
  2071. Value *YW = Builder.CreateFAddFMF(Y, Op1, &I);
  2072. return BinaryOperator::CreateFSubFMF(XZ, YW, &I);
  2073. }
  2074. auto m_FaddRdx = [](Value *&Sum, Value *&Vec) {
  2075. return m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(m_Value(Sum),
  2076. m_Value(Vec)));
  2077. };
  2078. Value *A0, *A1, *V0, *V1;
  2079. if (match(Op0, m_FaddRdx(A0, V0)) && match(Op1, m_FaddRdx(A1, V1)) &&
  2080. V0->getType() == V1->getType()) {
  2081. // Difference of sums is sum of differences:
  2082. // add_rdx(A0, V0) - add_rdx(A1, V1) --> add_rdx(A0, V0 - V1) - A1
  2083. Value *Sub = Builder.CreateFSubFMF(V0, V1, &I);
  2084. Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
  2085. {Sub->getType()}, {A0, Sub}, &I);
  2086. return BinaryOperator::CreateFSubFMF(Rdx, A1, &I);
  2087. }
  2088. if (Instruction *F = factorizeFAddFSub(I, Builder))
  2089. return F;
  2090. // TODO: This performs reassociative folds for FP ops. Some fraction of the
  2091. // functionality has been subsumed by simple pattern matching here and in
  2092. // InstSimplify. We should let a dedicated reassociation pass handle more
  2093. // complex pattern matching and remove this from InstCombine.
  2094. if (Value *V = FAddCombine(Builder).simplify(&I))
  2095. return replaceInstUsesWith(I, V);
  2096. // (X - Y) - Op1 --> X - (Y + Op1)
  2097. if (match(Op0, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
  2098. Value *FAdd = Builder.CreateFAddFMF(Y, Op1, &I);
  2099. return BinaryOperator::CreateFSubFMF(X, FAdd, &I);
  2100. }
  2101. }
  2102. return nullptr;
  2103. }