InstCombineAddSub.cpp 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696
  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 <= std::size(TmpResult) + 1) && "out-of-bound access");
  469. Value *Result;
  470. if (!SimpVect.empty())
  471. Result = createNaryFAdd(SimpVect, InstrQuota);
  472. else {
  473. // The addition is folded to 0.0.
  474. Result = ConstantFP::get(Instr->getType(), 0.0);
  475. }
  476. return Result;
  477. }
  478. Value *FAddCombine::createNaryFAdd
  479. (const AddendVect &Opnds, unsigned InstrQuota) {
  480. assert(!Opnds.empty() && "Expect at least one addend");
  481. // Step 1: Check if the # of instructions needed exceeds the quota.
  482. unsigned InstrNeeded = calcInstrNumber(Opnds);
  483. if (InstrNeeded > InstrQuota)
  484. return nullptr;
  485. initCreateInstNum();
  486. // step 2: Emit the N-ary addition.
  487. // Note that at most three instructions are involved in Fadd-InstCombine: the
  488. // addition in question, and at most two neighboring instructions.
  489. // The resulting optimized addition should have at least one less instruction
  490. // than the original addition expression tree. This implies that the resulting
  491. // N-ary addition has at most two instructions, and we don't need to worry
  492. // about tree-height when constructing the N-ary addition.
  493. Value *LastVal = nullptr;
  494. bool LastValNeedNeg = false;
  495. // Iterate the addends, creating fadd/fsub using adjacent two addends.
  496. for (const FAddend *Opnd : Opnds) {
  497. bool NeedNeg;
  498. Value *V = createAddendVal(*Opnd, NeedNeg);
  499. if (!LastVal) {
  500. LastVal = V;
  501. LastValNeedNeg = NeedNeg;
  502. continue;
  503. }
  504. if (LastValNeedNeg == NeedNeg) {
  505. LastVal = createFAdd(LastVal, V);
  506. continue;
  507. }
  508. if (LastValNeedNeg)
  509. LastVal = createFSub(V, LastVal);
  510. else
  511. LastVal = createFSub(LastVal, V);
  512. LastValNeedNeg = false;
  513. }
  514. if (LastValNeedNeg) {
  515. LastVal = createFNeg(LastVal);
  516. }
  517. #ifndef NDEBUG
  518. assert(CreateInstrNum == InstrNeeded &&
  519. "Inconsistent in instruction numbers");
  520. #endif
  521. return LastVal;
  522. }
  523. Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
  524. Value *V = Builder.CreateFSub(Opnd0, Opnd1);
  525. if (Instruction *I = dyn_cast<Instruction>(V))
  526. createInstPostProc(I);
  527. return V;
  528. }
  529. Value *FAddCombine::createFNeg(Value *V) {
  530. Value *NewV = Builder.CreateFNeg(V);
  531. if (Instruction *I = dyn_cast<Instruction>(NewV))
  532. createInstPostProc(I, true); // fneg's don't receive instruction numbers.
  533. return NewV;
  534. }
  535. Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
  536. Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
  537. if (Instruction *I = dyn_cast<Instruction>(V))
  538. createInstPostProc(I);
  539. return V;
  540. }
  541. Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
  542. Value *V = Builder.CreateFMul(Opnd0, Opnd1);
  543. if (Instruction *I = dyn_cast<Instruction>(V))
  544. createInstPostProc(I);
  545. return V;
  546. }
  547. void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
  548. NewInstr->setDebugLoc(Instr->getDebugLoc());
  549. // Keep track of the number of instruction created.
  550. if (!NoNumber)
  551. incCreateInstNum();
  552. // Propagate fast-math flags
  553. NewInstr->setFastMathFlags(Instr->getFastMathFlags());
  554. }
  555. // Return the number of instruction needed to emit the N-ary addition.
  556. // NOTE: Keep this function in sync with createAddendVal().
  557. unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
  558. unsigned OpndNum = Opnds.size();
  559. unsigned InstrNeeded = OpndNum - 1;
  560. // Adjust the number of instructions needed to emit the N-ary add.
  561. for (const FAddend *Opnd : Opnds) {
  562. if (Opnd->isConstant())
  563. continue;
  564. // The constant check above is really for a few special constant
  565. // coefficients.
  566. if (isa<UndefValue>(Opnd->getSymVal()))
  567. continue;
  568. const FAddendCoef &CE = Opnd->getCoef();
  569. // Let the addend be "c * x". If "c == +/-1", the value of the addend
  570. // is immediately available; otherwise, it needs exactly one instruction
  571. // to evaluate the value.
  572. if (!CE.isMinusOne() && !CE.isOne())
  573. InstrNeeded++;
  574. }
  575. return InstrNeeded;
  576. }
  577. // Input Addend Value NeedNeg(output)
  578. // ================================================================
  579. // Constant C C false
  580. // <+/-1, V> V coefficient is -1
  581. // <2/-2, V> "fadd V, V" coefficient is -2
  582. // <C, V> "fmul V, C" false
  583. //
  584. // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
  585. Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
  586. const FAddendCoef &Coeff = Opnd.getCoef();
  587. if (Opnd.isConstant()) {
  588. NeedNeg = false;
  589. return Coeff.getValue(Instr->getType());
  590. }
  591. Value *OpndVal = Opnd.getSymVal();
  592. if (Coeff.isMinusOne() || Coeff.isOne()) {
  593. NeedNeg = Coeff.isMinusOne();
  594. return OpndVal;
  595. }
  596. if (Coeff.isTwo() || Coeff.isMinusTwo()) {
  597. NeedNeg = Coeff.isMinusTwo();
  598. return createFAdd(OpndVal, OpndVal);
  599. }
  600. NeedNeg = false;
  601. return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
  602. }
  603. // Checks if any operand is negative and we can convert add to sub.
  604. // This function checks for following negative patterns
  605. // ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
  606. // ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
  607. // XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
  608. static Value *checkForNegativeOperand(BinaryOperator &I,
  609. InstCombiner::BuilderTy &Builder) {
  610. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  611. // This function creates 2 instructions to replace ADD, we need at least one
  612. // of LHS or RHS to have one use to ensure benefit in transform.
  613. if (!LHS->hasOneUse() && !RHS->hasOneUse())
  614. return nullptr;
  615. Value *X = nullptr, *Y = nullptr, *Z = nullptr;
  616. const APInt *C1 = nullptr, *C2 = nullptr;
  617. // if ONE is on other side, swap
  618. if (match(RHS, m_Add(m_Value(X), m_One())))
  619. std::swap(LHS, RHS);
  620. if (match(LHS, m_Add(m_Value(X), m_One()))) {
  621. // if XOR on other side, swap
  622. if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
  623. std::swap(X, RHS);
  624. if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
  625. // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
  626. // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
  627. if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
  628. Value *NewAnd = Builder.CreateAnd(Z, *C1);
  629. return Builder.CreateSub(RHS, NewAnd, "sub");
  630. } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
  631. // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
  632. // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
  633. Value *NewOr = Builder.CreateOr(Z, ~(*C1));
  634. return Builder.CreateSub(RHS, NewOr, "sub");
  635. }
  636. }
  637. }
  638. // Restore LHS and RHS
  639. LHS = I.getOperand(0);
  640. RHS = I.getOperand(1);
  641. // if XOR is on other side, swap
  642. if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
  643. std::swap(LHS, RHS);
  644. // C2 is ODD
  645. // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
  646. // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
  647. if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
  648. if (C1->countTrailingZeros() == 0)
  649. if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
  650. Value *NewOr = Builder.CreateOr(Z, ~(*C2));
  651. return Builder.CreateSub(RHS, NewOr, "sub");
  652. }
  653. return nullptr;
  654. }
  655. /// Wrapping flags may allow combining constants separated by an extend.
  656. static Instruction *foldNoWrapAdd(BinaryOperator &Add,
  657. InstCombiner::BuilderTy &Builder) {
  658. Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
  659. Type *Ty = Add.getType();
  660. Constant *Op1C;
  661. if (!match(Op1, m_Constant(Op1C)))
  662. return nullptr;
  663. // Try this match first because it results in an add in the narrow type.
  664. // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
  665. Value *X;
  666. const APInt *C1, *C2;
  667. if (match(Op1, m_APInt(C1)) &&
  668. match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
  669. C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
  670. Constant *NewC =
  671. ConstantInt::get(X->getType(), *C2 + C1->trunc(C2->getBitWidth()));
  672. return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
  673. }
  674. // More general combining of constants in the wide type.
  675. // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
  676. Constant *NarrowC;
  677. if (match(Op0, m_OneUse(m_SExt(m_NSWAdd(m_Value(X), m_Constant(NarrowC)))))) {
  678. Constant *WideC = ConstantExpr::getSExt(NarrowC, Ty);
  679. Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
  680. Value *WideX = Builder.CreateSExt(X, Ty);
  681. return BinaryOperator::CreateAdd(WideX, NewC);
  682. }
  683. // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
  684. if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_Constant(NarrowC)))))) {
  685. Constant *WideC = ConstantExpr::getZExt(NarrowC, Ty);
  686. Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
  687. Value *WideX = Builder.CreateZExt(X, Ty);
  688. return BinaryOperator::CreateAdd(WideX, NewC);
  689. }
  690. return nullptr;
  691. }
  692. Instruction *InstCombinerImpl::foldAddWithConstant(BinaryOperator &Add) {
  693. Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
  694. Type *Ty = Add.getType();
  695. Constant *Op1C;
  696. if (!match(Op1, m_ImmConstant(Op1C)))
  697. return nullptr;
  698. if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
  699. return NV;
  700. Value *X;
  701. Constant *Op00C;
  702. // add (sub C1, X), C2 --> sub (add C1, C2), X
  703. if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
  704. return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
  705. Value *Y;
  706. // add (sub X, Y), -1 --> add (not Y), X
  707. if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
  708. match(Op1, m_AllOnes()))
  709. return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
  710. // zext(bool) + C -> bool ? C + 1 : C
  711. if (match(Op0, m_ZExt(m_Value(X))) &&
  712. X->getType()->getScalarSizeInBits() == 1)
  713. return SelectInst::Create(X, InstCombiner::AddOne(Op1C), Op1);
  714. // sext(bool) + C -> bool ? C - 1 : C
  715. if (match(Op0, m_SExt(m_Value(X))) &&
  716. X->getType()->getScalarSizeInBits() == 1)
  717. return SelectInst::Create(X, InstCombiner::SubOne(Op1C), Op1);
  718. // ~X + C --> (C-1) - X
  719. if (match(Op0, m_Not(m_Value(X))))
  720. return BinaryOperator::CreateSub(InstCombiner::SubOne(Op1C), X);
  721. // (iN X s>> (N - 1)) + 1 --> zext (X > -1)
  722. const APInt *C;
  723. unsigned BitWidth = Ty->getScalarSizeInBits();
  724. if (match(Op0, m_OneUse(m_AShr(m_Value(X),
  725. m_SpecificIntAllowUndef(BitWidth - 1)))) &&
  726. match(Op1, m_One()))
  727. return new ZExtInst(Builder.CreateIsNotNeg(X, "isnotneg"), Ty);
  728. if (!match(Op1, m_APInt(C)))
  729. return nullptr;
  730. // (X | Op01C) + Op1C --> X + (Op01C + Op1C) iff the `or` is actually an `add`
  731. Constant *Op01C;
  732. if (match(Op0, m_Or(m_Value(X), m_ImmConstant(Op01C))) &&
  733. haveNoCommonBitsSet(X, Op01C, DL, &AC, &Add, &DT))
  734. return BinaryOperator::CreateAdd(X, ConstantExpr::getAdd(Op01C, Op1C));
  735. // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
  736. const APInt *C2;
  737. if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
  738. return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
  739. if (C->isSignMask()) {
  740. // If wrapping is not allowed, then the addition must set the sign bit:
  741. // X + (signmask) --> X | signmask
  742. if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
  743. return BinaryOperator::CreateOr(Op0, Op1);
  744. // If wrapping is allowed, then the addition flips the sign bit of LHS:
  745. // X + (signmask) --> X ^ signmask
  746. return BinaryOperator::CreateXor(Op0, Op1);
  747. }
  748. // Is this add the last step in a convoluted sext?
  749. // add(zext(xor i16 X, -32768), -32768) --> sext X
  750. if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
  751. C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
  752. return CastInst::Create(Instruction::SExt, X, Ty);
  753. if (match(Op0, m_Xor(m_Value(X), m_APInt(C2)))) {
  754. // (X ^ signmask) + C --> (X + (signmask ^ C))
  755. if (C2->isSignMask())
  756. return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C2 ^ *C));
  757. // If X has no high-bits set above an xor mask:
  758. // add (xor X, LowMaskC), C --> sub (LowMaskC + C), X
  759. if (C2->isMask()) {
  760. KnownBits LHSKnown = computeKnownBits(X, 0, &Add);
  761. if ((*C2 | LHSKnown.Zero).isAllOnes())
  762. return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C2 + *C), X);
  763. }
  764. // Look for a math+logic pattern that corresponds to sext-in-register of a
  765. // value with cleared high bits. Convert that into a pair of shifts:
  766. // add (xor X, 0x80), 0xF..F80 --> (X << ShAmtC) >>s ShAmtC
  767. // add (xor X, 0xF..F80), 0x80 --> (X << ShAmtC) >>s ShAmtC
  768. if (Op0->hasOneUse() && *C2 == -(*C)) {
  769. unsigned BitWidth = Ty->getScalarSizeInBits();
  770. unsigned ShAmt = 0;
  771. if (C->isPowerOf2())
  772. ShAmt = BitWidth - C->logBase2() - 1;
  773. else if (C2->isPowerOf2())
  774. ShAmt = BitWidth - C2->logBase2() - 1;
  775. if (ShAmt && MaskedValueIsZero(X, APInt::getHighBitsSet(BitWidth, ShAmt),
  776. 0, &Add)) {
  777. Constant *ShAmtC = ConstantInt::get(Ty, ShAmt);
  778. Value *NewShl = Builder.CreateShl(X, ShAmtC, "sext");
  779. return BinaryOperator::CreateAShr(NewShl, ShAmtC);
  780. }
  781. }
  782. }
  783. if (C->isOne() && Op0->hasOneUse()) {
  784. // add (sext i1 X), 1 --> zext (not X)
  785. // TODO: The smallest IR representation is (select X, 0, 1), and that would
  786. // not require the one-use check. But we need to remove a transform in
  787. // visitSelect and make sure that IR value tracking for select is equal or
  788. // better than for these ops.
  789. if (match(Op0, m_SExt(m_Value(X))) &&
  790. X->getType()->getScalarSizeInBits() == 1)
  791. return new ZExtInst(Builder.CreateNot(X), Ty);
  792. // Shifts and add used to flip and mask off the low bit:
  793. // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
  794. const APInt *C3;
  795. if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
  796. C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
  797. Value *NotX = Builder.CreateNot(X);
  798. return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
  799. }
  800. }
  801. return nullptr;
  802. }
  803. // Matches multiplication expression Op * C where C is a constant. Returns the
  804. // constant value in C and the other operand in Op. Returns true if such a
  805. // match is found.
  806. static bool MatchMul(Value *E, Value *&Op, APInt &C) {
  807. const APInt *AI;
  808. if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
  809. C = *AI;
  810. return true;
  811. }
  812. if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
  813. C = APInt(AI->getBitWidth(), 1);
  814. C <<= *AI;
  815. return true;
  816. }
  817. return false;
  818. }
  819. // Matches remainder expression Op % C where C is a constant. Returns the
  820. // constant value in C and the other operand in Op. Returns the signedness of
  821. // the remainder operation in IsSigned. Returns true if such a match is
  822. // found.
  823. static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
  824. const APInt *AI;
  825. IsSigned = false;
  826. if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
  827. IsSigned = true;
  828. C = *AI;
  829. return true;
  830. }
  831. if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
  832. C = *AI;
  833. return true;
  834. }
  835. if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
  836. C = *AI + 1;
  837. return true;
  838. }
  839. return false;
  840. }
  841. // Matches division expression Op / C with the given signedness as indicated
  842. // by IsSigned, where C is a constant. Returns the constant value in C and the
  843. // other operand in Op. Returns true if such a match is found.
  844. static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
  845. const APInt *AI;
  846. if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
  847. C = *AI;
  848. return true;
  849. }
  850. if (!IsSigned) {
  851. if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
  852. C = *AI;
  853. return true;
  854. }
  855. if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
  856. C = APInt(AI->getBitWidth(), 1);
  857. C <<= *AI;
  858. return true;
  859. }
  860. }
  861. return false;
  862. }
  863. // Returns whether C0 * C1 with the given signedness overflows.
  864. static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
  865. bool overflow;
  866. if (IsSigned)
  867. (void)C0.smul_ov(C1, overflow);
  868. else
  869. (void)C0.umul_ov(C1, overflow);
  870. return overflow;
  871. }
  872. // Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
  873. // does not overflow.
  874. Value *InstCombinerImpl::SimplifyAddWithRemainder(BinaryOperator &I) {
  875. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  876. Value *X, *MulOpV;
  877. APInt C0, MulOpC;
  878. bool IsSigned;
  879. // Match I = X % C0 + MulOpV * C0
  880. if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
  881. (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
  882. C0 == MulOpC) {
  883. Value *RemOpV;
  884. APInt C1;
  885. bool Rem2IsSigned;
  886. // Match MulOpC = RemOpV % C1
  887. if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
  888. IsSigned == Rem2IsSigned) {
  889. Value *DivOpV;
  890. APInt DivOpC;
  891. // Match RemOpV = X / C0
  892. if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
  893. C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
  894. Value *NewDivisor = ConstantInt::get(X->getType(), C0 * C1);
  895. return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
  896. : Builder.CreateURem(X, NewDivisor, "urem");
  897. }
  898. }
  899. }
  900. return nullptr;
  901. }
  902. /// Fold
  903. /// (1 << NBits) - 1
  904. /// Into:
  905. /// ~(-(1 << NBits))
  906. /// Because a 'not' is better for bit-tracking analysis and other transforms
  907. /// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
  908. static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
  909. InstCombiner::BuilderTy &Builder) {
  910. Value *NBits;
  911. if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
  912. return nullptr;
  913. Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
  914. Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
  915. // Be wary of constant folding.
  916. if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
  917. // Always NSW. But NUW propagates from `add`.
  918. BOp->setHasNoSignedWrap();
  919. BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
  920. }
  921. return BinaryOperator::CreateNot(NotMask, I.getName());
  922. }
  923. static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
  924. assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
  925. Type *Ty = I.getType();
  926. auto getUAddSat = [&]() {
  927. return Intrinsic::getDeclaration(I.getModule(), Intrinsic::uadd_sat, Ty);
  928. };
  929. // add (umin X, ~Y), Y --> uaddsat X, Y
  930. Value *X, *Y;
  931. if (match(&I, m_c_Add(m_c_UMin(m_Value(X), m_Not(m_Value(Y))),
  932. m_Deferred(Y))))
  933. return CallInst::Create(getUAddSat(), { X, Y });
  934. // add (umin X, ~C), C --> uaddsat X, C
  935. const APInt *C, *NotC;
  936. if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
  937. *C == ~*NotC)
  938. return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
  939. return nullptr;
  940. }
  941. /// Try to reduce signed division by power-of-2 to an arithmetic shift right.
  942. static Instruction *foldAddToAshr(BinaryOperator &Add) {
  943. // Division must be by power-of-2, but not the minimum signed value.
  944. Value *X;
  945. const APInt *DivC;
  946. if (!match(Add.getOperand(0), m_SDiv(m_Value(X), m_Power2(DivC))) ||
  947. DivC->isNegative())
  948. return nullptr;
  949. // Rounding is done by adding -1 if the dividend (X) is negative and has any
  950. // low bits set. The canonical pattern for that is an "ugt" compare with SMIN:
  951. // sext (icmp ugt (X & (DivC - 1)), SMIN)
  952. const APInt *MaskC;
  953. ICmpInst::Predicate Pred;
  954. if (!match(Add.getOperand(1),
  955. m_SExt(m_ICmp(Pred, m_And(m_Specific(X), m_APInt(MaskC)),
  956. m_SignMask()))) ||
  957. Pred != ICmpInst::ICMP_UGT)
  958. return nullptr;
  959. APInt SMin = APInt::getSignedMinValue(Add.getType()->getScalarSizeInBits());
  960. if (*MaskC != (SMin | (*DivC - 1)))
  961. return nullptr;
  962. // (X / DivC) + sext ((X & (SMin | (DivC - 1)) >u SMin) --> X >>s log2(DivC)
  963. return BinaryOperator::CreateAShr(
  964. X, ConstantInt::get(Add.getType(), DivC->exactLogBase2()));
  965. }
  966. Instruction *InstCombinerImpl::
  967. canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
  968. BinaryOperator &I) {
  969. assert((I.getOpcode() == Instruction::Add ||
  970. I.getOpcode() == Instruction::Or ||
  971. I.getOpcode() == Instruction::Sub) &&
  972. "Expecting add/or/sub instruction");
  973. // We have a subtraction/addition between a (potentially truncated) *logical*
  974. // right-shift of X and a "select".
  975. Value *X, *Select;
  976. Instruction *LowBitsToSkip, *Extract;
  977. if (!match(&I, m_c_BinOp(m_TruncOrSelf(m_CombineAnd(
  978. m_LShr(m_Value(X), m_Instruction(LowBitsToSkip)),
  979. m_Instruction(Extract))),
  980. m_Value(Select))))
  981. return nullptr;
  982. // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
  983. if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
  984. return nullptr;
  985. Type *XTy = X->getType();
  986. bool HadTrunc = I.getType() != XTy;
  987. // If there was a truncation of extracted value, then we'll need to produce
  988. // one extra instruction, so we need to ensure one instruction will go away.
  989. if (HadTrunc && !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
  990. return nullptr;
  991. // Extraction should extract high NBits bits, with shift amount calculated as:
  992. // low bits to skip = shift bitwidth - high bits to extract
  993. // The shift amount itself may be extended, and we need to look past zero-ext
  994. // when matching NBits, that will matter for matching later.
  995. Constant *C;
  996. Value *NBits;
  997. if (!match(
  998. LowBitsToSkip,
  999. m_ZExtOrSelf(m_Sub(m_Constant(C), m_ZExtOrSelf(m_Value(NBits))))) ||
  1000. !match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
  1001. APInt(C->getType()->getScalarSizeInBits(),
  1002. X->getType()->getScalarSizeInBits()))))
  1003. return nullptr;
  1004. // Sign-extending value can be zero-extended if we `sub`tract it,
  1005. // or sign-extended otherwise.
  1006. auto SkipExtInMagic = [&I](Value *&V) {
  1007. if (I.getOpcode() == Instruction::Sub)
  1008. match(V, m_ZExtOrSelf(m_Value(V)));
  1009. else
  1010. match(V, m_SExtOrSelf(m_Value(V)));
  1011. };
  1012. // Now, finally validate the sign-extending magic.
  1013. // `select` itself may be appropriately extended, look past that.
  1014. SkipExtInMagic(Select);
  1015. ICmpInst::Predicate Pred;
  1016. const APInt *Thr;
  1017. Value *SignExtendingValue, *Zero;
  1018. bool ShouldSignext;
  1019. // It must be a select between two values we will later establish to be a
  1020. // sign-extending value and a zero constant. The condition guarding the
  1021. // sign-extension must be based on a sign bit of the same X we had in `lshr`.
  1022. if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
  1023. m_Value(SignExtendingValue), m_Value(Zero))) ||
  1024. !isSignBitCheck(Pred, *Thr, ShouldSignext))
  1025. return nullptr;
  1026. // icmp-select pair is commutative.
  1027. if (!ShouldSignext)
  1028. std::swap(SignExtendingValue, Zero);
  1029. // If we should not perform sign-extension then we must add/or/subtract zero.
  1030. if (!match(Zero, m_Zero()))
  1031. return nullptr;
  1032. // Otherwise, it should be some constant, left-shifted by the same NBits we
  1033. // had in `lshr`. Said left-shift can also be appropriately extended.
  1034. // Again, we must look past zero-ext when looking for NBits.
  1035. SkipExtInMagic(SignExtendingValue);
  1036. Constant *SignExtendingValueBaseConstant;
  1037. if (!match(SignExtendingValue,
  1038. m_Shl(m_Constant(SignExtendingValueBaseConstant),
  1039. m_ZExtOrSelf(m_Specific(NBits)))))
  1040. return nullptr;
  1041. // If we `sub`, then the constant should be one, else it should be all-ones.
  1042. if (I.getOpcode() == Instruction::Sub
  1043. ? !match(SignExtendingValueBaseConstant, m_One())
  1044. : !match(SignExtendingValueBaseConstant, m_AllOnes()))
  1045. return nullptr;
  1046. auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
  1047. Extract->getName() + ".sext");
  1048. NewAShr->copyIRFlags(Extract); // Preserve `exact`-ness.
  1049. if (!HadTrunc)
  1050. return NewAShr;
  1051. Builder.Insert(NewAShr);
  1052. return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
  1053. }
  1054. /// This is a specialization of a more general transform from
  1055. /// foldUsingDistributiveLaws. If that code can be made to work optimally
  1056. /// for multi-use cases or propagating nsw/nuw, then we would not need this.
  1057. static Instruction *factorizeMathWithShlOps(BinaryOperator &I,
  1058. InstCombiner::BuilderTy &Builder) {
  1059. // TODO: Also handle mul by doubling the shift amount?
  1060. assert((I.getOpcode() == Instruction::Add ||
  1061. I.getOpcode() == Instruction::Sub) &&
  1062. "Expected add/sub");
  1063. auto *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
  1064. auto *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
  1065. if (!Op0 || !Op1 || !(Op0->hasOneUse() || Op1->hasOneUse()))
  1066. return nullptr;
  1067. Value *X, *Y, *ShAmt;
  1068. if (!match(Op0, m_Shl(m_Value(X), m_Value(ShAmt))) ||
  1069. !match(Op1, m_Shl(m_Value(Y), m_Specific(ShAmt))))
  1070. return nullptr;
  1071. // No-wrap propagates only when all ops have no-wrap.
  1072. bool HasNSW = I.hasNoSignedWrap() && Op0->hasNoSignedWrap() &&
  1073. Op1->hasNoSignedWrap();
  1074. bool HasNUW = I.hasNoUnsignedWrap() && Op0->hasNoUnsignedWrap() &&
  1075. Op1->hasNoUnsignedWrap();
  1076. // add/sub (X << ShAmt), (Y << ShAmt) --> (add/sub X, Y) << ShAmt
  1077. Value *NewMath = Builder.CreateBinOp(I.getOpcode(), X, Y);
  1078. if (auto *NewI = dyn_cast<BinaryOperator>(NewMath)) {
  1079. NewI->setHasNoSignedWrap(HasNSW);
  1080. NewI->setHasNoUnsignedWrap(HasNUW);
  1081. }
  1082. auto *NewShl = BinaryOperator::CreateShl(NewMath, ShAmt);
  1083. NewShl->setHasNoSignedWrap(HasNSW);
  1084. NewShl->setHasNoUnsignedWrap(HasNUW);
  1085. return NewShl;
  1086. }
  1087. /// Reduce a sequence of masked half-width multiplies to a single multiply.
  1088. /// ((XLow * YHigh) + (YLow * XHigh)) << HalfBits) + (XLow * YLow) --> X * Y
  1089. static Instruction *foldBoxMultiply(BinaryOperator &I) {
  1090. unsigned BitWidth = I.getType()->getScalarSizeInBits();
  1091. // Skip the odd bitwidth types.
  1092. if ((BitWidth & 0x1))
  1093. return nullptr;
  1094. unsigned HalfBits = BitWidth >> 1;
  1095. APInt HalfMask = APInt::getMaxValue(HalfBits);
  1096. // ResLo = (CrossSum << HalfBits) + (YLo * XLo)
  1097. Value *XLo, *YLo;
  1098. Value *CrossSum;
  1099. if (!match(&I, m_c_Add(m_Shl(m_Value(CrossSum), m_SpecificInt(HalfBits)),
  1100. m_Mul(m_Value(YLo), m_Value(XLo)))))
  1101. return nullptr;
  1102. // XLo = X & HalfMask
  1103. // YLo = Y & HalfMask
  1104. // TODO: Refactor with SimplifyDemandedBits or KnownBits known leading zeros
  1105. // to enhance robustness
  1106. Value *X, *Y;
  1107. if (!match(XLo, m_And(m_Value(X), m_SpecificInt(HalfMask))) ||
  1108. !match(YLo, m_And(m_Value(Y), m_SpecificInt(HalfMask))))
  1109. return nullptr;
  1110. // CrossSum = (X' * (Y >> Halfbits)) + (Y' * (X >> HalfBits))
  1111. // X' can be either X or XLo in the pattern (and the same for Y')
  1112. if (match(CrossSum,
  1113. m_c_Add(m_c_Mul(m_LShr(m_Specific(Y), m_SpecificInt(HalfBits)),
  1114. m_CombineOr(m_Specific(X), m_Specific(XLo))),
  1115. m_c_Mul(m_LShr(m_Specific(X), m_SpecificInt(HalfBits)),
  1116. m_CombineOr(m_Specific(Y), m_Specific(YLo))))))
  1117. return BinaryOperator::CreateMul(X, Y);
  1118. return nullptr;
  1119. }
  1120. Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
  1121. if (Value *V = simplifyAddInst(I.getOperand(0), I.getOperand(1),
  1122. I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
  1123. SQ.getWithInstruction(&I)))
  1124. return replaceInstUsesWith(I, V);
  1125. if (SimplifyAssociativeOrCommutative(I))
  1126. return &I;
  1127. if (Instruction *X = foldVectorBinop(I))
  1128. return X;
  1129. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  1130. return Phi;
  1131. // (A*B)+(A*C) -> A*(B+C) etc
  1132. if (Value *V = foldUsingDistributiveLaws(I))
  1133. return replaceInstUsesWith(I, V);
  1134. if (Instruction *R = foldBoxMultiply(I))
  1135. return R;
  1136. if (Instruction *R = factorizeMathWithShlOps(I, Builder))
  1137. return R;
  1138. if (Instruction *X = foldAddWithConstant(I))
  1139. return X;
  1140. if (Instruction *X = foldNoWrapAdd(I, Builder))
  1141. return X;
  1142. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  1143. Type *Ty = I.getType();
  1144. if (Ty->isIntOrIntVectorTy(1))
  1145. return BinaryOperator::CreateXor(LHS, RHS);
  1146. // X + X --> X << 1
  1147. if (LHS == RHS) {
  1148. auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
  1149. Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
  1150. Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
  1151. return Shl;
  1152. }
  1153. Value *A, *B;
  1154. if (match(LHS, m_Neg(m_Value(A)))) {
  1155. // -A + -B --> -(A + B)
  1156. if (match(RHS, m_Neg(m_Value(B))))
  1157. return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
  1158. // -A + B --> B - A
  1159. return BinaryOperator::CreateSub(RHS, A);
  1160. }
  1161. // A + -B --> A - B
  1162. if (match(RHS, m_Neg(m_Value(B))))
  1163. return BinaryOperator::CreateSub(LHS, B);
  1164. if (Value *V = checkForNegativeOperand(I, Builder))
  1165. return replaceInstUsesWith(I, V);
  1166. // (A + 1) + ~B --> A - B
  1167. // ~B + (A + 1) --> A - B
  1168. // (~B + A) + 1 --> A - B
  1169. // (A + ~B) + 1 --> A - B
  1170. if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
  1171. match(&I, m_BinOp(m_c_Add(m_Not(m_Value(B)), m_Value(A)), m_One())))
  1172. return BinaryOperator::CreateSub(A, B);
  1173. // (A + RHS) + RHS --> A + (RHS << 1)
  1174. if (match(LHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(RHS)))))
  1175. return BinaryOperator::CreateAdd(A, Builder.CreateShl(RHS, 1, "reass.add"));
  1176. // LHS + (A + LHS) --> A + (LHS << 1)
  1177. if (match(RHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(LHS)))))
  1178. return BinaryOperator::CreateAdd(A, Builder.CreateShl(LHS, 1, "reass.add"));
  1179. {
  1180. // (A + C1) + (C2 - B) --> (A - B) + (C1 + C2)
  1181. Constant *C1, *C2;
  1182. if (match(&I, m_c_Add(m_Add(m_Value(A), m_ImmConstant(C1)),
  1183. m_Sub(m_ImmConstant(C2), m_Value(B)))) &&
  1184. (LHS->hasOneUse() || RHS->hasOneUse())) {
  1185. Value *Sub = Builder.CreateSub(A, B);
  1186. return BinaryOperator::CreateAdd(Sub, ConstantExpr::getAdd(C1, C2));
  1187. }
  1188. }
  1189. // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
  1190. if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
  1191. // ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
  1192. const APInt *C1, *C2;
  1193. if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
  1194. APInt one(C2->getBitWidth(), 1);
  1195. APInt minusC1 = -(*C1);
  1196. if (minusC1 == (one << *C2)) {
  1197. Constant *NewRHS = ConstantInt::get(RHS->getType(), minusC1);
  1198. return BinaryOperator::CreateSRem(RHS, NewRHS);
  1199. }
  1200. }
  1201. // (A & 2^C1) + A => A & (2^C1 - 1) iff bit C1 in A is a sign bit
  1202. if (match(&I, m_c_Add(m_And(m_Value(A), m_APInt(C1)), m_Deferred(A))) &&
  1203. C1->isPowerOf2() && (ComputeNumSignBits(A) > C1->countLeadingZeros())) {
  1204. Constant *NewMask = ConstantInt::get(RHS->getType(), *C1 - 1);
  1205. return BinaryOperator::CreateAnd(A, NewMask);
  1206. }
  1207. // ZExt (B - A) + ZExt(A) --> ZExt(B)
  1208. if ((match(RHS, m_ZExt(m_Value(A))) &&
  1209. match(LHS, m_ZExt(m_NUWSub(m_Value(B), m_Specific(A))))) ||
  1210. (match(LHS, m_ZExt(m_Value(A))) &&
  1211. match(RHS, m_ZExt(m_NUWSub(m_Value(B), m_Specific(A))))))
  1212. return new ZExtInst(B, LHS->getType());
  1213. // A+B --> A|B iff A and B have no bits set in common.
  1214. if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
  1215. return BinaryOperator::CreateOr(LHS, RHS);
  1216. if (Instruction *Ext = narrowMathIfNoOverflow(I))
  1217. return Ext;
  1218. // (add (xor A, B) (and A, B)) --> (or A, B)
  1219. // (add (and A, B) (xor A, B)) --> (or A, B)
  1220. if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
  1221. m_c_And(m_Deferred(A), m_Deferred(B)))))
  1222. return BinaryOperator::CreateOr(A, B);
  1223. // (add (or A, B) (and A, B)) --> (add A, B)
  1224. // (add (and A, B) (or A, B)) --> (add A, B)
  1225. if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
  1226. m_c_And(m_Deferred(A), m_Deferred(B))))) {
  1227. // Replacing operands in-place to preserve nuw/nsw flags.
  1228. replaceOperand(I, 0, A);
  1229. replaceOperand(I, 1, B);
  1230. return &I;
  1231. }
  1232. // (add A (or A, -A)) --> (and (add A, -1) A)
  1233. // (add A (or -A, A)) --> (and (add A, -1) A)
  1234. // (add (or A, -A) A) --> (and (add A, -1) A)
  1235. // (add (or -A, A) A) --> (and (add A, -1) A)
  1236. if (match(&I, m_c_BinOp(m_Value(A), m_OneUse(m_c_Or(m_Neg(m_Deferred(A)),
  1237. m_Deferred(A)))))) {
  1238. Value *Add =
  1239. Builder.CreateAdd(A, Constant::getAllOnesValue(A->getType()), "",
  1240. I.hasNoUnsignedWrap(), I.hasNoSignedWrap());
  1241. return BinaryOperator::CreateAnd(Add, A);
  1242. }
  1243. // Canonicalize ((A & -A) - 1) --> ((A - 1) & ~A)
  1244. // Forms all commutable operations, and simplifies ctpop -> cttz folds.
  1245. if (match(&I,
  1246. m_Add(m_OneUse(m_c_And(m_Value(A), m_OneUse(m_Neg(m_Deferred(A))))),
  1247. m_AllOnes()))) {
  1248. Constant *AllOnes = ConstantInt::getAllOnesValue(RHS->getType());
  1249. Value *Dec = Builder.CreateAdd(A, AllOnes);
  1250. Value *Not = Builder.CreateXor(A, AllOnes);
  1251. return BinaryOperator::CreateAnd(Dec, Not);
  1252. }
  1253. // Disguised reassociation/factorization:
  1254. // ~(A * C1) + A
  1255. // ((A * -C1) - 1) + A
  1256. // ((A * -C1) + A) - 1
  1257. // (A * (1 - C1)) - 1
  1258. if (match(&I,
  1259. m_c_Add(m_OneUse(m_Not(m_OneUse(m_Mul(m_Value(A), m_APInt(C1))))),
  1260. m_Deferred(A)))) {
  1261. Type *Ty = I.getType();
  1262. Constant *NewMulC = ConstantInt::get(Ty, 1 - *C1);
  1263. Value *NewMul = Builder.CreateMul(A, NewMulC);
  1264. return BinaryOperator::CreateAdd(NewMul, ConstantInt::getAllOnesValue(Ty));
  1265. }
  1266. // (A * -2**C) + B --> B - (A << C)
  1267. const APInt *NegPow2C;
  1268. if (match(&I, m_c_Add(m_OneUse(m_Mul(m_Value(A), m_NegatedPower2(NegPow2C))),
  1269. m_Value(B)))) {
  1270. Constant *ShiftAmtC = ConstantInt::get(Ty, NegPow2C->countTrailingZeros());
  1271. Value *Shl = Builder.CreateShl(A, ShiftAmtC);
  1272. return BinaryOperator::CreateSub(B, Shl);
  1273. }
  1274. // Canonicalize signum variant that ends in add:
  1275. // (A s>> (BW - 1)) + (zext (A s> 0)) --> (A s>> (BW - 1)) | (zext (A != 0))
  1276. ICmpInst::Predicate Pred;
  1277. uint64_t BitWidth = Ty->getScalarSizeInBits();
  1278. if (match(LHS, m_AShr(m_Value(A), m_SpecificIntAllowUndef(BitWidth - 1))) &&
  1279. match(RHS, m_OneUse(m_ZExt(
  1280. m_OneUse(m_ICmp(Pred, m_Specific(A), m_ZeroInt()))))) &&
  1281. Pred == CmpInst::ICMP_SGT) {
  1282. Value *NotZero = Builder.CreateIsNotNull(A, "isnotnull");
  1283. Value *Zext = Builder.CreateZExt(NotZero, Ty, "isnotnull.zext");
  1284. return BinaryOperator::CreateOr(LHS, Zext);
  1285. }
  1286. if (Instruction *Ashr = foldAddToAshr(I))
  1287. return Ashr;
  1288. // TODO(jingyue): Consider willNotOverflowSignedAdd and
  1289. // willNotOverflowUnsignedAdd to reduce the number of invocations of
  1290. // computeKnownBits.
  1291. bool Changed = false;
  1292. if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
  1293. Changed = true;
  1294. I.setHasNoSignedWrap(true);
  1295. }
  1296. if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
  1297. Changed = true;
  1298. I.setHasNoUnsignedWrap(true);
  1299. }
  1300. if (Instruction *V = canonicalizeLowbitMask(I, Builder))
  1301. return V;
  1302. if (Instruction *V =
  1303. canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
  1304. return V;
  1305. if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
  1306. return SatAdd;
  1307. // usub.sat(A, B) + B => umax(A, B)
  1308. if (match(&I, m_c_BinOp(
  1309. m_OneUse(m_Intrinsic<Intrinsic::usub_sat>(m_Value(A), m_Value(B))),
  1310. m_Deferred(B)))) {
  1311. return replaceInstUsesWith(I,
  1312. Builder.CreateIntrinsic(Intrinsic::umax, {I.getType()}, {A, B}));
  1313. }
  1314. // ctpop(A) + ctpop(B) => ctpop(A | B) if A and B have no bits set in common.
  1315. if (match(LHS, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(A)))) &&
  1316. match(RHS, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(B)))) &&
  1317. haveNoCommonBitsSet(A, B, DL, &AC, &I, &DT))
  1318. return replaceInstUsesWith(
  1319. I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
  1320. {Builder.CreateOr(A, B)}));
  1321. return Changed ? &I : nullptr;
  1322. }
  1323. /// Eliminate an op from a linear interpolation (lerp) pattern.
  1324. static Instruction *factorizeLerp(BinaryOperator &I,
  1325. InstCombiner::BuilderTy &Builder) {
  1326. Value *X, *Y, *Z;
  1327. if (!match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_Value(Y),
  1328. m_OneUse(m_FSub(m_FPOne(),
  1329. m_Value(Z))))),
  1330. m_OneUse(m_c_FMul(m_Value(X), m_Deferred(Z))))))
  1331. return nullptr;
  1332. // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
  1333. Value *XY = Builder.CreateFSubFMF(X, Y, &I);
  1334. Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
  1335. return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
  1336. }
  1337. /// Factor a common operand out of fadd/fsub of fmul/fdiv.
  1338. static Instruction *factorizeFAddFSub(BinaryOperator &I,
  1339. InstCombiner::BuilderTy &Builder) {
  1340. assert((I.getOpcode() == Instruction::FAdd ||
  1341. I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
  1342. assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
  1343. "FP factorization requires FMF");
  1344. if (Instruction *Lerp = factorizeLerp(I, Builder))
  1345. return Lerp;
  1346. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1347. if (!Op0->hasOneUse() || !Op1->hasOneUse())
  1348. return nullptr;
  1349. Value *X, *Y, *Z;
  1350. bool IsFMul;
  1351. if ((match(Op0, m_FMul(m_Value(X), m_Value(Z))) &&
  1352. match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))) ||
  1353. (match(Op0, m_FMul(m_Value(Z), m_Value(X))) &&
  1354. match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))))
  1355. IsFMul = true;
  1356. else if (match(Op0, m_FDiv(m_Value(X), m_Value(Z))) &&
  1357. match(Op1, m_FDiv(m_Value(Y), m_Specific(Z))))
  1358. IsFMul = false;
  1359. else
  1360. return nullptr;
  1361. // (X * Z) + (Y * Z) --> (X + Y) * Z
  1362. // (X * Z) - (Y * Z) --> (X - Y) * Z
  1363. // (X / Z) + (Y / Z) --> (X + Y) / Z
  1364. // (X / Z) - (Y / Z) --> (X - Y) / Z
  1365. bool IsFAdd = I.getOpcode() == Instruction::FAdd;
  1366. Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
  1367. : Builder.CreateFSubFMF(X, Y, &I);
  1368. // Bail out if we just created a denormal constant.
  1369. // TODO: This is copied from a previous implementation. Is it necessary?
  1370. const APFloat *C;
  1371. if (match(XY, m_APFloat(C)) && !C->isNormal())
  1372. return nullptr;
  1373. return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
  1374. : BinaryOperator::CreateFDivFMF(XY, Z, &I);
  1375. }
  1376. Instruction *InstCombinerImpl::visitFAdd(BinaryOperator &I) {
  1377. if (Value *V = simplifyFAddInst(I.getOperand(0), I.getOperand(1),
  1378. I.getFastMathFlags(),
  1379. SQ.getWithInstruction(&I)))
  1380. return replaceInstUsesWith(I, V);
  1381. if (SimplifyAssociativeOrCommutative(I))
  1382. return &I;
  1383. if (Instruction *X = foldVectorBinop(I))
  1384. return X;
  1385. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  1386. return Phi;
  1387. if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
  1388. return FoldedFAdd;
  1389. // (-X) + Y --> Y - X
  1390. Value *X, *Y;
  1391. if (match(&I, m_c_FAdd(m_FNeg(m_Value(X)), m_Value(Y))))
  1392. return BinaryOperator::CreateFSubFMF(Y, X, &I);
  1393. // Similar to above, but look through fmul/fdiv for the negated term.
  1394. // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
  1395. Value *Z;
  1396. if (match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))),
  1397. m_Value(Z)))) {
  1398. Value *XY = Builder.CreateFMulFMF(X, Y, &I);
  1399. return BinaryOperator::CreateFSubFMF(Z, XY, &I);
  1400. }
  1401. // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
  1402. // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
  1403. if (match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y))),
  1404. m_Value(Z))) ||
  1405. match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))),
  1406. m_Value(Z)))) {
  1407. Value *XY = Builder.CreateFDivFMF(X, Y, &I);
  1408. return BinaryOperator::CreateFSubFMF(Z, XY, &I);
  1409. }
  1410. // Check for (fadd double (sitofp x), y), see if we can merge this into an
  1411. // integer add followed by a promotion.
  1412. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  1413. if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
  1414. Value *LHSIntVal = LHSConv->getOperand(0);
  1415. Type *FPType = LHSConv->getType();
  1416. // TODO: This check is overly conservative. In many cases known bits
  1417. // analysis can tell us that the result of the addition has less significant
  1418. // bits than the integer type can hold.
  1419. auto IsValidPromotion = [](Type *FTy, Type *ITy) {
  1420. Type *FScalarTy = FTy->getScalarType();
  1421. Type *IScalarTy = ITy->getScalarType();
  1422. // Do we have enough bits in the significand to represent the result of
  1423. // the integer addition?
  1424. unsigned MaxRepresentableBits =
  1425. APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
  1426. return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
  1427. };
  1428. // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
  1429. // ... if the constant fits in the integer value. This is useful for things
  1430. // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
  1431. // requires a constant pool load, and generally allows the add to be better
  1432. // instcombined.
  1433. if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
  1434. if (IsValidPromotion(FPType, LHSIntVal->getType())) {
  1435. Constant *CI =
  1436. ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
  1437. if (LHSConv->hasOneUse() &&
  1438. ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
  1439. willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
  1440. // Insert the new integer add.
  1441. Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
  1442. return new SIToFPInst(NewAdd, I.getType());
  1443. }
  1444. }
  1445. // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
  1446. if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
  1447. Value *RHSIntVal = RHSConv->getOperand(0);
  1448. // It's enough to check LHS types only because we require int types to
  1449. // be the same for this transform.
  1450. if (IsValidPromotion(FPType, LHSIntVal->getType())) {
  1451. // Only do this if x/y have the same type, if at least one of them has a
  1452. // single use (so we don't increase the number of int->fp conversions),
  1453. // and if the integer add will not overflow.
  1454. if (LHSIntVal->getType() == RHSIntVal->getType() &&
  1455. (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
  1456. willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
  1457. // Insert the new integer add.
  1458. Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
  1459. return new SIToFPInst(NewAdd, I.getType());
  1460. }
  1461. }
  1462. }
  1463. }
  1464. // Handle specials cases for FAdd with selects feeding the operation
  1465. if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
  1466. return replaceInstUsesWith(I, V);
  1467. if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
  1468. if (Instruction *F = factorizeFAddFSub(I, Builder))
  1469. return F;
  1470. // Try to fold fadd into start value of reduction intrinsic.
  1471. if (match(&I, m_c_FAdd(m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(
  1472. m_AnyZeroFP(), m_Value(X))),
  1473. m_Value(Y)))) {
  1474. // fadd (rdx 0.0, X), Y --> rdx Y, X
  1475. return replaceInstUsesWith(
  1476. I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
  1477. {X->getType()}, {Y, X}, &I));
  1478. }
  1479. const APFloat *StartC, *C;
  1480. if (match(LHS, m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(
  1481. m_APFloat(StartC), m_Value(X)))) &&
  1482. match(RHS, m_APFloat(C))) {
  1483. // fadd (rdx StartC, X), C --> rdx (C + StartC), X
  1484. Constant *NewStartC = ConstantFP::get(I.getType(), *C + *StartC);
  1485. return replaceInstUsesWith(
  1486. I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
  1487. {X->getType()}, {NewStartC, X}, &I));
  1488. }
  1489. // (X * MulC) + X --> X * (MulC + 1.0)
  1490. Constant *MulC;
  1491. if (match(&I, m_c_FAdd(m_FMul(m_Value(X), m_ImmConstant(MulC)),
  1492. m_Deferred(X)))) {
  1493. if (Constant *NewMulC = ConstantFoldBinaryOpOperands(
  1494. Instruction::FAdd, MulC, ConstantFP::get(I.getType(), 1.0), DL))
  1495. return BinaryOperator::CreateFMulFMF(X, NewMulC, &I);
  1496. }
  1497. // (-X - Y) + (X + Z) --> Z - Y
  1498. if (match(&I, m_c_FAdd(m_FSub(m_FNeg(m_Value(X)), m_Value(Y)),
  1499. m_c_FAdd(m_Deferred(X), m_Value(Z)))))
  1500. return BinaryOperator::CreateFSubFMF(Z, Y, &I);
  1501. if (Value *V = FAddCombine(Builder).simplify(&I))
  1502. return replaceInstUsesWith(I, V);
  1503. }
  1504. return nullptr;
  1505. }
  1506. /// Optimize pointer differences into the same array into a size. Consider:
  1507. /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
  1508. /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
  1509. Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
  1510. Type *Ty, bool IsNUW) {
  1511. // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
  1512. // this.
  1513. bool Swapped = false;
  1514. GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
  1515. if (!isa<GEPOperator>(LHS) && isa<GEPOperator>(RHS)) {
  1516. std::swap(LHS, RHS);
  1517. Swapped = true;
  1518. }
  1519. // Require at least one GEP with a common base pointer on both sides.
  1520. if (auto *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
  1521. // (gep X, ...) - X
  1522. if (LHSGEP->getOperand(0)->stripPointerCasts() ==
  1523. RHS->stripPointerCasts()) {
  1524. GEP1 = LHSGEP;
  1525. } else if (auto *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
  1526. // (gep X, ...) - (gep X, ...)
  1527. if (LHSGEP->getOperand(0)->stripPointerCasts() ==
  1528. RHSGEP->getOperand(0)->stripPointerCasts()) {
  1529. GEP1 = LHSGEP;
  1530. GEP2 = RHSGEP;
  1531. }
  1532. }
  1533. }
  1534. if (!GEP1)
  1535. return nullptr;
  1536. if (GEP2) {
  1537. // (gep X, ...) - (gep X, ...)
  1538. //
  1539. // Avoid duplicating the arithmetic if there are more than one non-constant
  1540. // indices between the two GEPs and either GEP has a non-constant index and
  1541. // multiple users. If zero non-constant index, the result is a constant and
  1542. // there is no duplication. If one non-constant index, the result is an add
  1543. // or sub with a constant, which is no larger than the original code, and
  1544. // there's no duplicated arithmetic, even if either GEP has multiple
  1545. // users. If more than one non-constant indices combined, as long as the GEP
  1546. // with at least one non-constant index doesn't have multiple users, there
  1547. // is no duplication.
  1548. unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
  1549. unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
  1550. if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
  1551. ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
  1552. (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
  1553. return nullptr;
  1554. }
  1555. }
  1556. // Emit the offset of the GEP and an intptr_t.
  1557. Value *Result = EmitGEPOffset(GEP1);
  1558. // If this is a single inbounds GEP and the original sub was nuw,
  1559. // then the final multiplication is also nuw.
  1560. if (auto *I = dyn_cast<Instruction>(Result))
  1561. if (IsNUW && !GEP2 && !Swapped && GEP1->isInBounds() &&
  1562. I->getOpcode() == Instruction::Mul)
  1563. I->setHasNoUnsignedWrap();
  1564. // If we have a 2nd GEP of the same base pointer, subtract the offsets.
  1565. // If both GEPs are inbounds, then the subtract does not have signed overflow.
  1566. if (GEP2) {
  1567. Value *Offset = EmitGEPOffset(GEP2);
  1568. Result = Builder.CreateSub(Result, Offset, "gepdiff", /* NUW */ false,
  1569. GEP1->isInBounds() && GEP2->isInBounds());
  1570. }
  1571. // If we have p - gep(p, ...) then we have to negate the result.
  1572. if (Swapped)
  1573. Result = Builder.CreateNeg(Result, "diff.neg");
  1574. return Builder.CreateIntCast(Result, Ty, true);
  1575. }
  1576. static Instruction *foldSubOfMinMax(BinaryOperator &I,
  1577. InstCombiner::BuilderTy &Builder) {
  1578. Value *Op0 = I.getOperand(0);
  1579. Value *Op1 = I.getOperand(1);
  1580. Type *Ty = I.getType();
  1581. auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op1);
  1582. if (!MinMax)
  1583. return nullptr;
  1584. // sub(add(X,Y), s/umin(X,Y)) --> s/umax(X,Y)
  1585. // sub(add(X,Y), s/umax(X,Y)) --> s/umin(X,Y)
  1586. Value *X = MinMax->getLHS();
  1587. Value *Y = MinMax->getRHS();
  1588. if (match(Op0, m_c_Add(m_Specific(X), m_Specific(Y))) &&
  1589. (Op0->hasOneUse() || Op1->hasOneUse())) {
  1590. Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
  1591. Function *F = Intrinsic::getDeclaration(I.getModule(), InvID, Ty);
  1592. return CallInst::Create(F, {X, Y});
  1593. }
  1594. // sub(add(X,Y),umin(Y,Z)) --> add(X,usub.sat(Y,Z))
  1595. // sub(add(X,Z),umin(Y,Z)) --> add(X,usub.sat(Z,Y))
  1596. Value *Z;
  1597. if (match(Op1, m_OneUse(m_UMin(m_Value(Y), m_Value(Z))))) {
  1598. if (match(Op0, m_OneUse(m_c_Add(m_Specific(Y), m_Value(X))))) {
  1599. Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Y, Z});
  1600. return BinaryOperator::CreateAdd(X, USub);
  1601. }
  1602. if (match(Op0, m_OneUse(m_c_Add(m_Specific(Z), m_Value(X))))) {
  1603. Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Z, Y});
  1604. return BinaryOperator::CreateAdd(X, USub);
  1605. }
  1606. }
  1607. // sub Op0, smin((sub nsw Op0, Z), 0) --> smax Op0, Z
  1608. // sub Op0, smax((sub nsw Op0, Z), 0) --> smin Op0, Z
  1609. if (MinMax->isSigned() && match(Y, m_ZeroInt()) &&
  1610. match(X, m_NSWSub(m_Specific(Op0), m_Value(Z)))) {
  1611. Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
  1612. Function *F = Intrinsic::getDeclaration(I.getModule(), InvID, Ty);
  1613. return CallInst::Create(F, {Op0, Z});
  1614. }
  1615. return nullptr;
  1616. }
  1617. Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
  1618. if (Value *V = simplifySubInst(I.getOperand(0), I.getOperand(1),
  1619. I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
  1620. SQ.getWithInstruction(&I)))
  1621. return replaceInstUsesWith(I, V);
  1622. if (Instruction *X = foldVectorBinop(I))
  1623. return X;
  1624. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  1625. return Phi;
  1626. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1627. // If this is a 'B = x-(-A)', change to B = x+A.
  1628. // We deal with this without involving Negator to preserve NSW flag.
  1629. if (Value *V = dyn_castNegVal(Op1)) {
  1630. BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
  1631. if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
  1632. assert(BO->getOpcode() == Instruction::Sub &&
  1633. "Expected a subtraction operator!");
  1634. if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
  1635. Res->setHasNoSignedWrap(true);
  1636. } else {
  1637. if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
  1638. Res->setHasNoSignedWrap(true);
  1639. }
  1640. return Res;
  1641. }
  1642. // Try this before Negator to preserve NSW flag.
  1643. if (Instruction *R = factorizeMathWithShlOps(I, Builder))
  1644. return R;
  1645. Constant *C;
  1646. if (match(Op0, m_ImmConstant(C))) {
  1647. Value *X;
  1648. Constant *C2;
  1649. // C-(X+C2) --> (C-C2)-X
  1650. if (match(Op1, m_Add(m_Value(X), m_ImmConstant(C2))))
  1651. return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
  1652. }
  1653. auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
  1654. if (Instruction *Ext = narrowMathIfNoOverflow(I))
  1655. return Ext;
  1656. bool Changed = false;
  1657. if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
  1658. Changed = true;
  1659. I.setHasNoSignedWrap(true);
  1660. }
  1661. if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
  1662. Changed = true;
  1663. I.setHasNoUnsignedWrap(true);
  1664. }
  1665. return Changed ? &I : nullptr;
  1666. };
  1667. // First, let's try to interpret `sub a, b` as `add a, (sub 0, b)`,
  1668. // and let's try to sink `(sub 0, b)` into `b` itself. But only if this isn't
  1669. // a pure negation used by a select that looks like abs/nabs.
  1670. bool IsNegation = match(Op0, m_ZeroInt());
  1671. if (!IsNegation || none_of(I.users(), [&I, Op1](const User *U) {
  1672. const Instruction *UI = dyn_cast<Instruction>(U);
  1673. if (!UI)
  1674. return false;
  1675. return match(UI,
  1676. m_Select(m_Value(), m_Specific(Op1), m_Specific(&I))) ||
  1677. match(UI, m_Select(m_Value(), m_Specific(&I), m_Specific(Op1)));
  1678. })) {
  1679. if (Value *NegOp1 = Negator::Negate(IsNegation, Op1, *this))
  1680. return BinaryOperator::CreateAdd(NegOp1, Op0);
  1681. }
  1682. if (IsNegation)
  1683. return TryToNarrowDeduceFlags(); // Should have been handled in Negator!
  1684. // (A*B)-(A*C) -> A*(B-C) etc
  1685. if (Value *V = foldUsingDistributiveLaws(I))
  1686. return replaceInstUsesWith(I, V);
  1687. if (I.getType()->isIntOrIntVectorTy(1))
  1688. return BinaryOperator::CreateXor(Op0, Op1);
  1689. // Replace (-1 - A) with (~A).
  1690. if (match(Op0, m_AllOnes()))
  1691. return BinaryOperator::CreateNot(Op1);
  1692. // (X + -1) - Y --> ~Y + X
  1693. Value *X, *Y;
  1694. if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
  1695. return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
  1696. // Reassociate sub/add sequences to create more add instructions and
  1697. // reduce dependency chains:
  1698. // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
  1699. Value *Z;
  1700. if (match(Op0, m_OneUse(m_c_Add(m_OneUse(m_Sub(m_Value(X), m_Value(Y))),
  1701. m_Value(Z))))) {
  1702. Value *XZ = Builder.CreateAdd(X, Z);
  1703. Value *YW = Builder.CreateAdd(Y, Op1);
  1704. return BinaryOperator::CreateSub(XZ, YW);
  1705. }
  1706. // ((X - Y) - Op1) --> X - (Y + Op1)
  1707. if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y))))) {
  1708. Value *Add = Builder.CreateAdd(Y, Op1);
  1709. return BinaryOperator::CreateSub(X, Add);
  1710. }
  1711. // (~X) - (~Y) --> Y - X
  1712. // This is placed after the other reassociations and explicitly excludes a
  1713. // sub-of-sub pattern to avoid infinite looping.
  1714. if (isFreeToInvert(Op0, Op0->hasOneUse()) &&
  1715. isFreeToInvert(Op1, Op1->hasOneUse()) &&
  1716. !match(Op0, m_Sub(m_ImmConstant(), m_Value()))) {
  1717. Value *NotOp0 = Builder.CreateNot(Op0);
  1718. Value *NotOp1 = Builder.CreateNot(Op1);
  1719. return BinaryOperator::CreateSub(NotOp1, NotOp0);
  1720. }
  1721. auto m_AddRdx = [](Value *&Vec) {
  1722. return m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_add>(m_Value(Vec)));
  1723. };
  1724. Value *V0, *V1;
  1725. if (match(Op0, m_AddRdx(V0)) && match(Op1, m_AddRdx(V1)) &&
  1726. V0->getType() == V1->getType()) {
  1727. // Difference of sums is sum of differences:
  1728. // add_rdx(V0) - add_rdx(V1) --> add_rdx(V0 - V1)
  1729. Value *Sub = Builder.CreateSub(V0, V1);
  1730. Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_add,
  1731. {Sub->getType()}, {Sub});
  1732. return replaceInstUsesWith(I, Rdx);
  1733. }
  1734. if (Constant *C = dyn_cast<Constant>(Op0)) {
  1735. Value *X;
  1736. if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
  1737. // C - (zext bool) --> bool ? C - 1 : C
  1738. return SelectInst::Create(X, InstCombiner::SubOne(C), C);
  1739. if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
  1740. // C - (sext bool) --> bool ? C + 1 : C
  1741. return SelectInst::Create(X, InstCombiner::AddOne(C), C);
  1742. // C - ~X == X + (1+C)
  1743. if (match(Op1, m_Not(m_Value(X))))
  1744. return BinaryOperator::CreateAdd(X, InstCombiner::AddOne(C));
  1745. // Try to fold constant sub into select arguments.
  1746. if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
  1747. if (Instruction *R = FoldOpIntoSelect(I, SI))
  1748. return R;
  1749. // Try to fold constant sub into PHI values.
  1750. if (PHINode *PN = dyn_cast<PHINode>(Op1))
  1751. if (Instruction *R = foldOpIntoPhi(I, PN))
  1752. return R;
  1753. Constant *C2;
  1754. // C-(C2-X) --> X+(C-C2)
  1755. if (match(Op1, m_Sub(m_ImmConstant(C2), m_Value(X))))
  1756. return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
  1757. }
  1758. const APInt *Op0C;
  1759. if (match(Op0, m_APInt(Op0C))) {
  1760. if (Op0C->isMask()) {
  1761. // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
  1762. // zero.
  1763. KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
  1764. if ((*Op0C | RHSKnown.Zero).isAllOnes())
  1765. return BinaryOperator::CreateXor(Op1, Op0);
  1766. }
  1767. // C - ((C3 -nuw X) & C2) --> (C - (C2 & C3)) + (X & C2) when:
  1768. // (C3 - ((C2 & C3) - 1)) is pow2
  1769. // ((C2 + C3) & ((C2 & C3) - 1)) == ((C2 & C3) - 1)
  1770. // C2 is negative pow2 || sub nuw
  1771. const APInt *C2, *C3;
  1772. BinaryOperator *InnerSub;
  1773. if (match(Op1, m_OneUse(m_And(m_BinOp(InnerSub), m_APInt(C2)))) &&
  1774. match(InnerSub, m_Sub(m_APInt(C3), m_Value(X))) &&
  1775. (InnerSub->hasNoUnsignedWrap() || C2->isNegatedPowerOf2())) {
  1776. APInt C2AndC3 = *C2 & *C3;
  1777. APInt C2AndC3Minus1 = C2AndC3 - 1;
  1778. APInt C2AddC3 = *C2 + *C3;
  1779. if ((*C3 - C2AndC3Minus1).isPowerOf2() &&
  1780. C2AndC3Minus1.isSubsetOf(C2AddC3)) {
  1781. Value *And = Builder.CreateAnd(X, ConstantInt::get(I.getType(), *C2));
  1782. return BinaryOperator::CreateAdd(
  1783. And, ConstantInt::get(I.getType(), *Op0C - C2AndC3));
  1784. }
  1785. }
  1786. }
  1787. {
  1788. Value *Y;
  1789. // X-(X+Y) == -Y X-(Y+X) == -Y
  1790. if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
  1791. return BinaryOperator::CreateNeg(Y);
  1792. // (X-Y)-X == -Y
  1793. if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
  1794. return BinaryOperator::CreateNeg(Y);
  1795. }
  1796. // (sub (or A, B) (and A, B)) --> (xor A, B)
  1797. {
  1798. Value *A, *B;
  1799. if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
  1800. match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
  1801. return BinaryOperator::CreateXor(A, B);
  1802. }
  1803. // (sub (add A, B) (or A, B)) --> (and A, B)
  1804. {
  1805. Value *A, *B;
  1806. if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
  1807. match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
  1808. return BinaryOperator::CreateAnd(A, B);
  1809. }
  1810. // (sub (add A, B) (and A, B)) --> (or A, B)
  1811. {
  1812. Value *A, *B;
  1813. if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
  1814. match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
  1815. return BinaryOperator::CreateOr(A, B);
  1816. }
  1817. // (sub (and A, B) (or A, B)) --> neg (xor A, B)
  1818. {
  1819. Value *A, *B;
  1820. if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
  1821. match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
  1822. (Op0->hasOneUse() || Op1->hasOneUse()))
  1823. return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
  1824. }
  1825. // (sub (or A, B), (xor A, B)) --> (and A, B)
  1826. {
  1827. Value *A, *B;
  1828. if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
  1829. match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
  1830. return BinaryOperator::CreateAnd(A, B);
  1831. }
  1832. // (sub (xor A, B) (or A, B)) --> neg (and A, B)
  1833. {
  1834. Value *A, *B;
  1835. if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
  1836. match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
  1837. (Op0->hasOneUse() || Op1->hasOneUse()))
  1838. return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
  1839. }
  1840. {
  1841. Value *Y;
  1842. // ((X | Y) - X) --> (~X & Y)
  1843. if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
  1844. return BinaryOperator::CreateAnd(
  1845. Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
  1846. }
  1847. {
  1848. // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
  1849. Value *X;
  1850. if (match(Op0, m_OneUse(m_c_And(m_Specific(Op1),
  1851. m_OneUse(m_Neg(m_Value(X))))))) {
  1852. return BinaryOperator::CreateNeg(Builder.CreateAnd(
  1853. Op1, Builder.CreateAdd(X, Constant::getAllOnesValue(I.getType()))));
  1854. }
  1855. }
  1856. {
  1857. // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
  1858. Constant *C;
  1859. if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_Constant(C))))) {
  1860. return BinaryOperator::CreateNeg(
  1861. Builder.CreateAnd(Op1, Builder.CreateNot(C)));
  1862. }
  1863. }
  1864. if (Instruction *R = foldSubOfMinMax(I, Builder))
  1865. return R;
  1866. {
  1867. // If we have a subtraction between some value and a select between
  1868. // said value and something else, sink subtraction into select hands, i.e.:
  1869. // sub (select %Cond, %TrueVal, %FalseVal), %Op1
  1870. // ->
  1871. // select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
  1872. // or
  1873. // sub %Op0, (select %Cond, %TrueVal, %FalseVal)
  1874. // ->
  1875. // select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
  1876. // This will result in select between new subtraction and 0.
  1877. auto SinkSubIntoSelect =
  1878. [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
  1879. auto SubBuilder) -> Instruction * {
  1880. Value *Cond, *TrueVal, *FalseVal;
  1881. if (!match(Select, m_OneUse(m_Select(m_Value(Cond), m_Value(TrueVal),
  1882. m_Value(FalseVal)))))
  1883. return nullptr;
  1884. if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
  1885. return nullptr;
  1886. // While it is really tempting to just create two subtractions and let
  1887. // InstCombine fold one of those to 0, it isn't possible to do so
  1888. // because of worklist visitation order. So ugly it is.
  1889. bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
  1890. Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
  1891. Constant *Zero = Constant::getNullValue(Ty);
  1892. SelectInst *NewSel =
  1893. SelectInst::Create(Cond, OtherHandOfSubIsTrueVal ? Zero : NewSub,
  1894. OtherHandOfSubIsTrueVal ? NewSub : Zero);
  1895. // Preserve prof metadata if any.
  1896. NewSel->copyMetadata(cast<Instruction>(*Select));
  1897. return NewSel;
  1898. };
  1899. if (Instruction *NewSel = SinkSubIntoSelect(
  1900. /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
  1901. [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
  1902. return Builder->CreateSub(OtherHandOfSelect,
  1903. /*OtherHandOfSub=*/Op1);
  1904. }))
  1905. return NewSel;
  1906. if (Instruction *NewSel = SinkSubIntoSelect(
  1907. /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
  1908. [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
  1909. return Builder->CreateSub(/*OtherHandOfSub=*/Op0,
  1910. OtherHandOfSelect);
  1911. }))
  1912. return NewSel;
  1913. }
  1914. // (X - (X & Y)) --> (X & ~Y)
  1915. if (match(Op1, m_c_And(m_Specific(Op0), m_Value(Y))) &&
  1916. (Op1->hasOneUse() || isa<Constant>(Y)))
  1917. return BinaryOperator::CreateAnd(
  1918. Op0, Builder.CreateNot(Y, Y->getName() + ".not"));
  1919. // ~X - Min/Max(~X, Y) -> ~Min/Max(X, ~Y) - X
  1920. // ~X - Min/Max(Y, ~X) -> ~Min/Max(X, ~Y) - X
  1921. // Min/Max(~X, Y) - ~X -> X - ~Min/Max(X, ~Y)
  1922. // Min/Max(Y, ~X) - ~X -> X - ~Min/Max(X, ~Y)
  1923. // As long as Y is freely invertible, this will be neutral or a win.
  1924. // Note: We don't generate the inverse max/min, just create the 'not' of
  1925. // it and let other folds do the rest.
  1926. if (match(Op0, m_Not(m_Value(X))) &&
  1927. match(Op1, m_c_MaxOrMin(m_Specific(Op0), m_Value(Y))) &&
  1928. !Op0->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
  1929. Value *Not = Builder.CreateNot(Op1);
  1930. return BinaryOperator::CreateSub(Not, X);
  1931. }
  1932. if (match(Op1, m_Not(m_Value(X))) &&
  1933. match(Op0, m_c_MaxOrMin(m_Specific(Op1), m_Value(Y))) &&
  1934. !Op1->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
  1935. Value *Not = Builder.CreateNot(Op0);
  1936. return BinaryOperator::CreateSub(X, Not);
  1937. }
  1938. // Optimize pointer differences into the same array into a size. Consider:
  1939. // &A[10] - &A[0]: we should compile this to "10".
  1940. Value *LHSOp, *RHSOp;
  1941. if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
  1942. match(Op1, m_PtrToInt(m_Value(RHSOp))))
  1943. if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
  1944. I.hasNoUnsignedWrap()))
  1945. return replaceInstUsesWith(I, Res);
  1946. // trunc(p)-trunc(q) -> trunc(p-q)
  1947. if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
  1948. match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
  1949. if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
  1950. /* IsNUW */ false))
  1951. return replaceInstUsesWith(I, Res);
  1952. // Canonicalize a shifty way to code absolute value to the common pattern.
  1953. // There are 2 potential commuted variants.
  1954. // We're relying on the fact that we only do this transform when the shift has
  1955. // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
  1956. // instructions).
  1957. Value *A;
  1958. const APInt *ShAmt;
  1959. Type *Ty = I.getType();
  1960. unsigned BitWidth = Ty->getScalarSizeInBits();
  1961. if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
  1962. Op1->hasNUses(2) && *ShAmt == BitWidth - 1 &&
  1963. match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
  1964. // B = ashr i32 A, 31 ; smear the sign bit
  1965. // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
  1966. // --> (A < 0) ? -A : A
  1967. Value *IsNeg = Builder.CreateIsNeg(A);
  1968. // Copy the nuw/nsw flags from the sub to the negate.
  1969. Value *NegA = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
  1970. I.hasNoSignedWrap());
  1971. return SelectInst::Create(IsNeg, NegA, A);
  1972. }
  1973. // If we are subtracting a low-bit masked subset of some value from an add
  1974. // of that same value with no low bits changed, that is clearing some low bits
  1975. // of the sum:
  1976. // sub (X + AddC), (X & AndC) --> and (X + AddC), ~AndC
  1977. const APInt *AddC, *AndC;
  1978. if (match(Op0, m_Add(m_Value(X), m_APInt(AddC))) &&
  1979. match(Op1, m_And(m_Specific(X), m_APInt(AndC)))) {
  1980. unsigned Cttz = AddC->countTrailingZeros();
  1981. APInt HighMask(APInt::getHighBitsSet(BitWidth, BitWidth - Cttz));
  1982. if ((HighMask & *AndC).isZero())
  1983. return BinaryOperator::CreateAnd(Op0, ConstantInt::get(Ty, ~(*AndC)));
  1984. }
  1985. if (Instruction *V =
  1986. canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
  1987. return V;
  1988. // X - usub.sat(X, Y) => umin(X, Y)
  1989. if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::usub_sat>(m_Specific(Op0),
  1990. m_Value(Y)))))
  1991. return replaceInstUsesWith(
  1992. I, Builder.CreateIntrinsic(Intrinsic::umin, {I.getType()}, {Op0, Y}));
  1993. // umax(X, Op1) - Op1 --> usub.sat(X, Op1)
  1994. // TODO: The one-use restriction is not strictly necessary, but it may
  1995. // require improving other pattern matching and/or codegen.
  1996. if (match(Op0, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op1)))))
  1997. return replaceInstUsesWith(
  1998. I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op1}));
  1999. // Op0 - umin(X, Op0) --> usub.sat(Op0, X)
  2000. if (match(Op1, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op0)))))
  2001. return replaceInstUsesWith(
  2002. I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op0, X}));
  2003. // Op0 - umax(X, Op0) --> 0 - usub.sat(X, Op0)
  2004. if (match(Op1, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op0))))) {
  2005. Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op0});
  2006. return BinaryOperator::CreateNeg(USub);
  2007. }
  2008. // umin(X, Op1) - Op1 --> 0 - usub.sat(Op1, X)
  2009. if (match(Op0, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op1))))) {
  2010. Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op1, X});
  2011. return BinaryOperator::CreateNeg(USub);
  2012. }
  2013. // C - ctpop(X) => ctpop(~X) if C is bitwidth
  2014. if (match(Op0, m_SpecificInt(BitWidth)) &&
  2015. match(Op1, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(X)))))
  2016. return replaceInstUsesWith(
  2017. I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
  2018. {Builder.CreateNot(X)}));
  2019. // Reduce multiplies for difference-of-squares by factoring:
  2020. // (X * X) - (Y * Y) --> (X + Y) * (X - Y)
  2021. if (match(Op0, m_OneUse(m_Mul(m_Value(X), m_Deferred(X)))) &&
  2022. match(Op1, m_OneUse(m_Mul(m_Value(Y), m_Deferred(Y))))) {
  2023. auto *OBO0 = cast<OverflowingBinaryOperator>(Op0);
  2024. auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
  2025. bool PropagateNSW = I.hasNoSignedWrap() && OBO0->hasNoSignedWrap() &&
  2026. OBO1->hasNoSignedWrap() && BitWidth > 2;
  2027. bool PropagateNUW = I.hasNoUnsignedWrap() && OBO0->hasNoUnsignedWrap() &&
  2028. OBO1->hasNoUnsignedWrap() && BitWidth > 1;
  2029. Value *Add = Builder.CreateAdd(X, Y, "add", PropagateNUW, PropagateNSW);
  2030. Value *Sub = Builder.CreateSub(X, Y, "sub", PropagateNUW, PropagateNSW);
  2031. Value *Mul = Builder.CreateMul(Add, Sub, "", PropagateNUW, PropagateNSW);
  2032. return replaceInstUsesWith(I, Mul);
  2033. }
  2034. return TryToNarrowDeduceFlags();
  2035. }
  2036. /// This eliminates floating-point negation in either 'fneg(X)' or
  2037. /// 'fsub(-0.0, X)' form by combining into a constant operand.
  2038. static Instruction *foldFNegIntoConstant(Instruction &I, const DataLayout &DL) {
  2039. // This is limited with one-use because fneg is assumed better for
  2040. // reassociation and cheaper in codegen than fmul/fdiv.
  2041. // TODO: Should the m_OneUse restriction be removed?
  2042. Instruction *FNegOp;
  2043. if (!match(&I, m_FNeg(m_OneUse(m_Instruction(FNegOp)))))
  2044. return nullptr;
  2045. Value *X;
  2046. Constant *C;
  2047. // Fold negation into constant operand.
  2048. // -(X * C) --> X * (-C)
  2049. if (match(FNegOp, m_FMul(m_Value(X), m_Constant(C))))
  2050. if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
  2051. return BinaryOperator::CreateFMulFMF(X, NegC, &I);
  2052. // -(X / C) --> X / (-C)
  2053. if (match(FNegOp, m_FDiv(m_Value(X), m_Constant(C))))
  2054. if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
  2055. return BinaryOperator::CreateFDivFMF(X, NegC, &I);
  2056. // -(C / X) --> (-C) / X
  2057. if (match(FNegOp, m_FDiv(m_Constant(C), m_Value(X))))
  2058. if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
  2059. Instruction *FDiv = BinaryOperator::CreateFDivFMF(NegC, X, &I);
  2060. // Intersect 'nsz' and 'ninf' because those special value exceptions may
  2061. // not apply to the fdiv. Everything else propagates from the fneg.
  2062. // TODO: We could propagate nsz/ninf from fdiv alone?
  2063. FastMathFlags FMF = I.getFastMathFlags();
  2064. FastMathFlags OpFMF = FNegOp->getFastMathFlags();
  2065. FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
  2066. FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
  2067. return FDiv;
  2068. }
  2069. // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
  2070. // -(X + C) --> -X + -C --> -C - X
  2071. if (I.hasNoSignedZeros() && match(FNegOp, m_FAdd(m_Value(X), m_Constant(C))))
  2072. if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
  2073. return BinaryOperator::CreateFSubFMF(NegC, X, &I);
  2074. return nullptr;
  2075. }
  2076. static Instruction *hoistFNegAboveFMulFDiv(Instruction &I,
  2077. InstCombiner::BuilderTy &Builder) {
  2078. Value *FNeg;
  2079. if (!match(&I, m_FNeg(m_Value(FNeg))))
  2080. return nullptr;
  2081. Value *X, *Y;
  2082. if (match(FNeg, m_OneUse(m_FMul(m_Value(X), m_Value(Y)))))
  2083. return BinaryOperator::CreateFMulFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
  2084. if (match(FNeg, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))))
  2085. return BinaryOperator::CreateFDivFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
  2086. return nullptr;
  2087. }
  2088. Instruction *InstCombinerImpl::visitFNeg(UnaryOperator &I) {
  2089. Value *Op = I.getOperand(0);
  2090. if (Value *V = simplifyFNegInst(Op, I.getFastMathFlags(),
  2091. getSimplifyQuery().getWithInstruction(&I)))
  2092. return replaceInstUsesWith(I, V);
  2093. if (Instruction *X = foldFNegIntoConstant(I, DL))
  2094. return X;
  2095. Value *X, *Y;
  2096. // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
  2097. if (I.hasNoSignedZeros() &&
  2098. match(Op, m_OneUse(m_FSub(m_Value(X), m_Value(Y)))))
  2099. return BinaryOperator::CreateFSubFMF(Y, X, &I);
  2100. if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
  2101. return R;
  2102. Value *OneUse;
  2103. if (!match(Op, m_OneUse(m_Value(OneUse))))
  2104. return nullptr;
  2105. // Try to eliminate fneg if at least 1 arm of the select is negated.
  2106. Value *Cond;
  2107. if (match(OneUse, m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))) {
  2108. // Unlike most transforms, this one is not safe to propagate nsz unless
  2109. // it is present on the original select. We union the flags from the select
  2110. // and fneg and then remove nsz if needed.
  2111. auto propagateSelectFMF = [&](SelectInst *S, bool CommonOperand) {
  2112. S->copyFastMathFlags(&I);
  2113. if (auto *OldSel = dyn_cast<SelectInst>(Op)) {
  2114. FastMathFlags FMF = I.getFastMathFlags();
  2115. FMF |= OldSel->getFastMathFlags();
  2116. S->setFastMathFlags(FMF);
  2117. if (!OldSel->hasNoSignedZeros() && !CommonOperand &&
  2118. !isGuaranteedNotToBeUndefOrPoison(OldSel->getCondition()))
  2119. S->setHasNoSignedZeros(false);
  2120. }
  2121. };
  2122. // -(Cond ? -P : Y) --> Cond ? P : -Y
  2123. Value *P;
  2124. if (match(X, m_FNeg(m_Value(P)))) {
  2125. Value *NegY = Builder.CreateFNegFMF(Y, &I, Y->getName() + ".neg");
  2126. SelectInst *NewSel = SelectInst::Create(Cond, P, NegY);
  2127. propagateSelectFMF(NewSel, P == Y);
  2128. return NewSel;
  2129. }
  2130. // -(Cond ? X : -P) --> Cond ? -X : P
  2131. if (match(Y, m_FNeg(m_Value(P)))) {
  2132. Value *NegX = Builder.CreateFNegFMF(X, &I, X->getName() + ".neg");
  2133. SelectInst *NewSel = SelectInst::Create(Cond, NegX, P);
  2134. propagateSelectFMF(NewSel, P == X);
  2135. return NewSel;
  2136. }
  2137. }
  2138. // fneg (copysign x, y) -> copysign x, (fneg y)
  2139. if (match(OneUse, m_CopySign(m_Value(X), m_Value(Y)))) {
  2140. // The source copysign has an additional value input, so we can't propagate
  2141. // flags the copysign doesn't also have.
  2142. FastMathFlags FMF = I.getFastMathFlags();
  2143. FMF &= cast<FPMathOperator>(OneUse)->getFastMathFlags();
  2144. IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
  2145. Builder.setFastMathFlags(FMF);
  2146. Value *NegY = Builder.CreateFNeg(Y);
  2147. Value *NewCopySign = Builder.CreateCopySign(X, NegY);
  2148. return replaceInstUsesWith(I, NewCopySign);
  2149. }
  2150. return nullptr;
  2151. }
  2152. Instruction *InstCombinerImpl::visitFSub(BinaryOperator &I) {
  2153. if (Value *V = simplifyFSubInst(I.getOperand(0), I.getOperand(1),
  2154. I.getFastMathFlags(),
  2155. getSimplifyQuery().getWithInstruction(&I)))
  2156. return replaceInstUsesWith(I, V);
  2157. if (Instruction *X = foldVectorBinop(I))
  2158. return X;
  2159. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  2160. return Phi;
  2161. // Subtraction from -0.0 is the canonical form of fneg.
  2162. // fsub -0.0, X ==> fneg X
  2163. // fsub nsz 0.0, X ==> fneg nsz X
  2164. //
  2165. // FIXME This matcher does not respect FTZ or DAZ yet:
  2166. // fsub -0.0, Denorm ==> +-0
  2167. // fneg Denorm ==> -Denorm
  2168. Value *Op;
  2169. if (match(&I, m_FNeg(m_Value(Op))))
  2170. return UnaryOperator::CreateFNegFMF(Op, &I);
  2171. if (Instruction *X = foldFNegIntoConstant(I, DL))
  2172. return X;
  2173. if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
  2174. return R;
  2175. Value *X, *Y;
  2176. Constant *C;
  2177. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  2178. // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
  2179. // Canonicalize to fadd to make analysis easier.
  2180. // This can also help codegen because fadd is commutative.
  2181. // Note that if this fsub was really an fneg, the fadd with -0.0 will get
  2182. // killed later. We still limit that particular transform with 'hasOneUse'
  2183. // because an fneg is assumed better/cheaper than a generic fsub.
  2184. if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) {
  2185. if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
  2186. Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
  2187. return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
  2188. }
  2189. }
  2190. // (-X) - Op1 --> -(X + Op1)
  2191. if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Op0) &&
  2192. match(Op0, m_OneUse(m_FNeg(m_Value(X))))) {
  2193. Value *FAdd = Builder.CreateFAddFMF(X, Op1, &I);
  2194. return UnaryOperator::CreateFNegFMF(FAdd, &I);
  2195. }
  2196. if (isa<Constant>(Op0))
  2197. if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
  2198. if (Instruction *NV = FoldOpIntoSelect(I, SI))
  2199. return NV;
  2200. // X - C --> X + (-C)
  2201. // But don't transform constant expressions because there's an inverse fold
  2202. // for X + (-Y) --> X - Y.
  2203. if (match(Op1, m_ImmConstant(C)))
  2204. if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
  2205. return BinaryOperator::CreateFAddFMF(Op0, NegC, &I);
  2206. // X - (-Y) --> X + Y
  2207. if (match(Op1, m_FNeg(m_Value(Y))))
  2208. return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
  2209. // Similar to above, but look through a cast of the negated value:
  2210. // X - (fptrunc(-Y)) --> X + fptrunc(Y)
  2211. Type *Ty = I.getType();
  2212. if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
  2213. return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
  2214. // X - (fpext(-Y)) --> X + fpext(Y)
  2215. if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
  2216. return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
  2217. // Similar to above, but look through fmul/fdiv of the negated value:
  2218. // Op0 - (-X * Y) --> Op0 + (X * Y)
  2219. // Op0 - (Y * -X) --> Op0 + (X * Y)
  2220. if (match(Op1, m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))))) {
  2221. Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
  2222. return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
  2223. }
  2224. // Op0 - (-X / Y) --> Op0 + (X / Y)
  2225. // Op0 - (X / -Y) --> Op0 + (X / Y)
  2226. if (match(Op1, m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y)))) ||
  2227. match(Op1, m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))))) {
  2228. Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
  2229. return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
  2230. }
  2231. // Handle special cases for FSub with selects feeding the operation
  2232. if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
  2233. return replaceInstUsesWith(I, V);
  2234. if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
  2235. // (Y - X) - Y --> -X
  2236. if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
  2237. return UnaryOperator::CreateFNegFMF(X, &I);
  2238. // Y - (X + Y) --> -X
  2239. // Y - (Y + X) --> -X
  2240. if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
  2241. return UnaryOperator::CreateFNegFMF(X, &I);
  2242. // (X * C) - X --> X * (C - 1.0)
  2243. if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
  2244. if (Constant *CSubOne = ConstantFoldBinaryOpOperands(
  2245. Instruction::FSub, C, ConstantFP::get(Ty, 1.0), DL))
  2246. return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
  2247. }
  2248. // X - (X * C) --> X * (1.0 - C)
  2249. if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
  2250. if (Constant *OneSubC = ConstantFoldBinaryOpOperands(
  2251. Instruction::FSub, ConstantFP::get(Ty, 1.0), C, DL))
  2252. return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
  2253. }
  2254. // Reassociate fsub/fadd sequences to create more fadd instructions and
  2255. // reduce dependency chains:
  2256. // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
  2257. Value *Z;
  2258. if (match(Op0, m_OneUse(m_c_FAdd(m_OneUse(m_FSub(m_Value(X), m_Value(Y))),
  2259. m_Value(Z))))) {
  2260. Value *XZ = Builder.CreateFAddFMF(X, Z, &I);
  2261. Value *YW = Builder.CreateFAddFMF(Y, Op1, &I);
  2262. return BinaryOperator::CreateFSubFMF(XZ, YW, &I);
  2263. }
  2264. auto m_FaddRdx = [](Value *&Sum, Value *&Vec) {
  2265. return m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(m_Value(Sum),
  2266. m_Value(Vec)));
  2267. };
  2268. Value *A0, *A1, *V0, *V1;
  2269. if (match(Op0, m_FaddRdx(A0, V0)) && match(Op1, m_FaddRdx(A1, V1)) &&
  2270. V0->getType() == V1->getType()) {
  2271. // Difference of sums is sum of differences:
  2272. // add_rdx(A0, V0) - add_rdx(A1, V1) --> add_rdx(A0, V0 - V1) - A1
  2273. Value *Sub = Builder.CreateFSubFMF(V0, V1, &I);
  2274. Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
  2275. {Sub->getType()}, {A0, Sub}, &I);
  2276. return BinaryOperator::CreateFSubFMF(Rdx, A1, &I);
  2277. }
  2278. if (Instruction *F = factorizeFAddFSub(I, Builder))
  2279. return F;
  2280. // TODO: This performs reassociative folds for FP ops. Some fraction of the
  2281. // functionality has been subsumed by simple pattern matching here and in
  2282. // InstSimplify. We should let a dedicated reassociation pass handle more
  2283. // complex pattern matching and remove this from InstCombine.
  2284. if (Value *V = FAddCombine(Builder).simplify(&I))
  2285. return replaceInstUsesWith(I, V);
  2286. // (X - Y) - Op1 --> X - (Y + Op1)
  2287. if (match(Op0, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
  2288. Value *FAdd = Builder.CreateFAddFMF(Y, Op1, &I);
  2289. return BinaryOperator::CreateFSubFMF(X, FAdd, &I);
  2290. }
  2291. }
  2292. return nullptr;
  2293. }