APFloat.cpp 156 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923
  1. //===-- APFloat.cpp - Implement APFloat class -----------------------------===//
  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 a class to represent arbitrary precision floating
  10. // point values and provide a variety of arithmetic operations on them.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/APFloat.h"
  14. #include "llvm/ADT/APSInt.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/FoldingSet.h"
  17. #include "llvm/ADT/Hashing.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/Config/llvm-config.h"
  21. #include "llvm/Support/Debug.h"
  22. #include "llvm/Support/Error.h"
  23. #include "llvm/Support/MathExtras.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include <cstring>
  26. #include <limits.h>
  27. #define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
  28. do { \
  29. if (usesLayout<IEEEFloat>(getSemantics())) \
  30. return U.IEEE.METHOD_CALL; \
  31. if (usesLayout<DoubleAPFloat>(getSemantics())) \
  32. return U.Double.METHOD_CALL; \
  33. llvm_unreachable("Unexpected semantics"); \
  34. } while (false)
  35. using namespace llvm;
  36. /// A macro used to combine two fcCategory enums into one key which can be used
  37. /// in a switch statement to classify how the interaction of two APFloat's
  38. /// categories affects an operation.
  39. ///
  40. /// TODO: If clang source code is ever allowed to use constexpr in its own
  41. /// codebase, change this into a static inline function.
  42. #define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
  43. /* Assumed in hexadecimal significand parsing, and conversion to
  44. hexadecimal strings. */
  45. static_assert(APFloatBase::integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
  46. namespace llvm {
  47. /* Represents floating point arithmetic semantics. */
  48. struct fltSemantics {
  49. /* The largest E such that 2^E is representable; this matches the
  50. definition of IEEE 754. */
  51. APFloatBase::ExponentType maxExponent;
  52. /* The smallest E such that 2^E is a normalized number; this
  53. matches the definition of IEEE 754. */
  54. APFloatBase::ExponentType minExponent;
  55. /* Number of bits in the significand. This includes the integer
  56. bit. */
  57. unsigned int precision;
  58. /* Number of bits actually used in the semantics. */
  59. unsigned int sizeInBits;
  60. // Returns true if any number described by this semantics can be precisely
  61. // represented by the specified semantics.
  62. bool isRepresentableBy(const fltSemantics &S) const {
  63. return maxExponent <= S.maxExponent && minExponent >= S.minExponent &&
  64. precision <= S.precision;
  65. }
  66. };
  67. static const fltSemantics semIEEEhalf = {15, -14, 11, 16};
  68. static const fltSemantics semBFloat = {127, -126, 8, 16};
  69. static const fltSemantics semIEEEsingle = {127, -126, 24, 32};
  70. static const fltSemantics semIEEEdouble = {1023, -1022, 53, 64};
  71. static const fltSemantics semIEEEquad = {16383, -16382, 113, 128};
  72. static const fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80};
  73. static const fltSemantics semBogus = {0, 0, 0, 0};
  74. /* The IBM double-double semantics. Such a number consists of a pair of IEEE
  75. 64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal,
  76. (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo.
  77. Therefore it has two 53-bit mantissa parts that aren't necessarily adjacent
  78. to each other, and two 11-bit exponents.
  79. Note: we need to make the value different from semBogus as otherwise
  80. an unsafe optimization may collapse both values to a single address,
  81. and we heavily rely on them having distinct addresses. */
  82. static const fltSemantics semPPCDoubleDouble = {-1, 0, 0, 128};
  83. /* These are legacy semantics for the fallback, inaccrurate implementation of
  84. IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the
  85. operation. It's equivalent to having an IEEE number with consecutive 106
  86. bits of mantissa and 11 bits of exponent.
  87. It's not equivalent to IBM double-double. For example, a legit IBM
  88. double-double, 1 + epsilon:
  89. 1 + epsilon = 1 + (1 >> 1076)
  90. is not representable by a consecutive 106 bits of mantissa.
  91. Currently, these semantics are used in the following way:
  92. semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) ->
  93. (64-bit APInt, 64-bit APInt) -> (128-bit APInt) ->
  94. semPPCDoubleDoubleLegacy -> IEEE operations
  95. We use bitcastToAPInt() to get the bit representation (in APInt) of the
  96. underlying IEEEdouble, then use the APInt constructor to construct the
  97. legacy IEEE float.
  98. TODO: Implement all operations in semPPCDoubleDouble, and delete these
  99. semantics. */
  100. static const fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53,
  101. 53 + 53, 128};
  102. const llvm::fltSemantics &APFloatBase::EnumToSemantics(Semantics S) {
  103. switch (S) {
  104. case S_IEEEhalf:
  105. return IEEEhalf();
  106. case S_BFloat:
  107. return BFloat();
  108. case S_IEEEsingle:
  109. return IEEEsingle();
  110. case S_IEEEdouble:
  111. return IEEEdouble();
  112. case S_x87DoubleExtended:
  113. return x87DoubleExtended();
  114. case S_IEEEquad:
  115. return IEEEquad();
  116. case S_PPCDoubleDouble:
  117. return PPCDoubleDouble();
  118. }
  119. llvm_unreachable("Unrecognised floating semantics");
  120. }
  121. APFloatBase::Semantics
  122. APFloatBase::SemanticsToEnum(const llvm::fltSemantics &Sem) {
  123. if (&Sem == &llvm::APFloat::IEEEhalf())
  124. return S_IEEEhalf;
  125. else if (&Sem == &llvm::APFloat::BFloat())
  126. return S_BFloat;
  127. else if (&Sem == &llvm::APFloat::IEEEsingle())
  128. return S_IEEEsingle;
  129. else if (&Sem == &llvm::APFloat::IEEEdouble())
  130. return S_IEEEdouble;
  131. else if (&Sem == &llvm::APFloat::x87DoubleExtended())
  132. return S_x87DoubleExtended;
  133. else if (&Sem == &llvm::APFloat::IEEEquad())
  134. return S_IEEEquad;
  135. else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
  136. return S_PPCDoubleDouble;
  137. else
  138. llvm_unreachable("Unknown floating semantics");
  139. }
  140. const fltSemantics &APFloatBase::IEEEhalf() {
  141. return semIEEEhalf;
  142. }
  143. const fltSemantics &APFloatBase::BFloat() {
  144. return semBFloat;
  145. }
  146. const fltSemantics &APFloatBase::IEEEsingle() {
  147. return semIEEEsingle;
  148. }
  149. const fltSemantics &APFloatBase::IEEEdouble() {
  150. return semIEEEdouble;
  151. }
  152. const fltSemantics &APFloatBase::IEEEquad() {
  153. return semIEEEquad;
  154. }
  155. const fltSemantics &APFloatBase::x87DoubleExtended() {
  156. return semX87DoubleExtended;
  157. }
  158. const fltSemantics &APFloatBase::Bogus() {
  159. return semBogus;
  160. }
  161. const fltSemantics &APFloatBase::PPCDoubleDouble() {
  162. return semPPCDoubleDouble;
  163. }
  164. constexpr RoundingMode APFloatBase::rmNearestTiesToEven;
  165. constexpr RoundingMode APFloatBase::rmTowardPositive;
  166. constexpr RoundingMode APFloatBase::rmTowardNegative;
  167. constexpr RoundingMode APFloatBase::rmTowardZero;
  168. constexpr RoundingMode APFloatBase::rmNearestTiesToAway;
  169. /* A tight upper bound on number of parts required to hold the value
  170. pow(5, power) is
  171. power * 815 / (351 * integerPartWidth) + 1
  172. However, whilst the result may require only this many parts,
  173. because we are multiplying two values to get it, the
  174. multiplication may require an extra part with the excess part
  175. being zero (consider the trivial case of 1 * 1, tcFullMultiply
  176. requires two parts to hold the single-part result). So we add an
  177. extra one to guarantee enough space whilst multiplying. */
  178. const unsigned int maxExponent = 16383;
  179. const unsigned int maxPrecision = 113;
  180. const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
  181. const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815) / (351 * APFloatBase::integerPartWidth));
  182. unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
  183. return semantics.precision;
  184. }
  185. APFloatBase::ExponentType
  186. APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
  187. return semantics.maxExponent;
  188. }
  189. APFloatBase::ExponentType
  190. APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
  191. return semantics.minExponent;
  192. }
  193. unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
  194. return semantics.sizeInBits;
  195. }
  196. unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
  197. return Sem.sizeInBits;
  198. }
  199. /* A bunch of private, handy routines. */
  200. static inline Error createError(const Twine &Err) {
  201. return make_error<StringError>(Err, inconvertibleErrorCode());
  202. }
  203. static inline unsigned int
  204. partCountForBits(unsigned int bits)
  205. {
  206. return ((bits) + APFloatBase::integerPartWidth - 1) / APFloatBase::integerPartWidth;
  207. }
  208. /* Returns 0U-9U. Return values >= 10U are not digits. */
  209. static inline unsigned int
  210. decDigitValue(unsigned int c)
  211. {
  212. return c - '0';
  213. }
  214. /* Return the value of a decimal exponent of the form
  215. [+-]ddddddd.
  216. If the exponent overflows, returns a large exponent with the
  217. appropriate sign. */
  218. static Expected<int> readExponent(StringRef::iterator begin,
  219. StringRef::iterator end) {
  220. bool isNegative;
  221. unsigned int absExponent;
  222. const unsigned int overlargeExponent = 24000; /* FIXME. */
  223. StringRef::iterator p = begin;
  224. // Treat no exponent as 0 to match binutils
  225. if (p == end || ((*p == '-' || *p == '+') && (p + 1) == end)) {
  226. return 0;
  227. }
  228. isNegative = (*p == '-');
  229. if (*p == '-' || *p == '+') {
  230. p++;
  231. if (p == end)
  232. return createError("Exponent has no digits");
  233. }
  234. absExponent = decDigitValue(*p++);
  235. if (absExponent >= 10U)
  236. return createError("Invalid character in exponent");
  237. for (; p != end; ++p) {
  238. unsigned int value;
  239. value = decDigitValue(*p);
  240. if (value >= 10U)
  241. return createError("Invalid character in exponent");
  242. absExponent = absExponent * 10U + value;
  243. if (absExponent >= overlargeExponent) {
  244. absExponent = overlargeExponent;
  245. break;
  246. }
  247. }
  248. if (isNegative)
  249. return -(int) absExponent;
  250. else
  251. return (int) absExponent;
  252. }
  253. /* This is ugly and needs cleaning up, but I don't immediately see
  254. how whilst remaining safe. */
  255. static Expected<int> totalExponent(StringRef::iterator p,
  256. StringRef::iterator end,
  257. int exponentAdjustment) {
  258. int unsignedExponent;
  259. bool negative, overflow;
  260. int exponent = 0;
  261. if (p == end)
  262. return createError("Exponent has no digits");
  263. negative = *p == '-';
  264. if (*p == '-' || *p == '+') {
  265. p++;
  266. if (p == end)
  267. return createError("Exponent has no digits");
  268. }
  269. unsignedExponent = 0;
  270. overflow = false;
  271. for (; p != end; ++p) {
  272. unsigned int value;
  273. value = decDigitValue(*p);
  274. if (value >= 10U)
  275. return createError("Invalid character in exponent");
  276. unsignedExponent = unsignedExponent * 10 + value;
  277. if (unsignedExponent > 32767) {
  278. overflow = true;
  279. break;
  280. }
  281. }
  282. if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
  283. overflow = true;
  284. if (!overflow) {
  285. exponent = unsignedExponent;
  286. if (negative)
  287. exponent = -exponent;
  288. exponent += exponentAdjustment;
  289. if (exponent > 32767 || exponent < -32768)
  290. overflow = true;
  291. }
  292. if (overflow)
  293. exponent = negative ? -32768: 32767;
  294. return exponent;
  295. }
  296. static Expected<StringRef::iterator>
  297. skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
  298. StringRef::iterator *dot) {
  299. StringRef::iterator p = begin;
  300. *dot = end;
  301. while (p != end && *p == '0')
  302. p++;
  303. if (p != end && *p == '.') {
  304. *dot = p++;
  305. if (end - begin == 1)
  306. return createError("Significand has no digits");
  307. while (p != end && *p == '0')
  308. p++;
  309. }
  310. return p;
  311. }
  312. /* Given a normal decimal floating point number of the form
  313. dddd.dddd[eE][+-]ddd
  314. where the decimal point and exponent are optional, fill out the
  315. structure D. Exponent is appropriate if the significand is
  316. treated as an integer, and normalizedExponent if the significand
  317. is taken to have the decimal point after a single leading
  318. non-zero digit.
  319. If the value is zero, V->firstSigDigit points to a non-digit, and
  320. the return exponent is zero.
  321. */
  322. struct decimalInfo {
  323. const char *firstSigDigit;
  324. const char *lastSigDigit;
  325. int exponent;
  326. int normalizedExponent;
  327. };
  328. static Error interpretDecimal(StringRef::iterator begin,
  329. StringRef::iterator end, decimalInfo *D) {
  330. StringRef::iterator dot = end;
  331. auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot);
  332. if (!PtrOrErr)
  333. return PtrOrErr.takeError();
  334. StringRef::iterator p = *PtrOrErr;
  335. D->firstSigDigit = p;
  336. D->exponent = 0;
  337. D->normalizedExponent = 0;
  338. for (; p != end; ++p) {
  339. if (*p == '.') {
  340. if (dot != end)
  341. return createError("String contains multiple dots");
  342. dot = p++;
  343. if (p == end)
  344. break;
  345. }
  346. if (decDigitValue(*p) >= 10U)
  347. break;
  348. }
  349. if (p != end) {
  350. if (*p != 'e' && *p != 'E')
  351. return createError("Invalid character in significand");
  352. if (p == begin)
  353. return createError("Significand has no digits");
  354. if (dot != end && p - begin == 1)
  355. return createError("Significand has no digits");
  356. /* p points to the first non-digit in the string */
  357. auto ExpOrErr = readExponent(p + 1, end);
  358. if (!ExpOrErr)
  359. return ExpOrErr.takeError();
  360. D->exponent = *ExpOrErr;
  361. /* Implied decimal point? */
  362. if (dot == end)
  363. dot = p;
  364. }
  365. /* If number is all zeroes accept any exponent. */
  366. if (p != D->firstSigDigit) {
  367. /* Drop insignificant trailing zeroes. */
  368. if (p != begin) {
  369. do
  370. do
  371. p--;
  372. while (p != begin && *p == '0');
  373. while (p != begin && *p == '.');
  374. }
  375. /* Adjust the exponents for any decimal point. */
  376. D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
  377. D->normalizedExponent = (D->exponent +
  378. static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
  379. - (dot > D->firstSigDigit && dot < p)));
  380. }
  381. D->lastSigDigit = p;
  382. return Error::success();
  383. }
  384. /* Return the trailing fraction of a hexadecimal number.
  385. DIGITVALUE is the first hex digit of the fraction, P points to
  386. the next digit. */
  387. static Expected<lostFraction>
  388. trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
  389. unsigned int digitValue) {
  390. unsigned int hexDigit;
  391. /* If the first trailing digit isn't 0 or 8 we can work out the
  392. fraction immediately. */
  393. if (digitValue > 8)
  394. return lfMoreThanHalf;
  395. else if (digitValue < 8 && digitValue > 0)
  396. return lfLessThanHalf;
  397. // Otherwise we need to find the first non-zero digit.
  398. while (p != end && (*p == '0' || *p == '.'))
  399. p++;
  400. if (p == end)
  401. return createError("Invalid trailing hexadecimal fraction!");
  402. hexDigit = hexDigitValue(*p);
  403. /* If we ran off the end it is exactly zero or one-half, otherwise
  404. a little more. */
  405. if (hexDigit == -1U)
  406. return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
  407. else
  408. return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
  409. }
  410. /* Return the fraction lost were a bignum truncated losing the least
  411. significant BITS bits. */
  412. static lostFraction
  413. lostFractionThroughTruncation(const APFloatBase::integerPart *parts,
  414. unsigned int partCount,
  415. unsigned int bits)
  416. {
  417. unsigned int lsb;
  418. lsb = APInt::tcLSB(parts, partCount);
  419. /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
  420. if (bits <= lsb)
  421. return lfExactlyZero;
  422. if (bits == lsb + 1)
  423. return lfExactlyHalf;
  424. if (bits <= partCount * APFloatBase::integerPartWidth &&
  425. APInt::tcExtractBit(parts, bits - 1))
  426. return lfMoreThanHalf;
  427. return lfLessThanHalf;
  428. }
  429. /* Shift DST right BITS bits noting lost fraction. */
  430. static lostFraction
  431. shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
  432. {
  433. lostFraction lost_fraction;
  434. lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
  435. APInt::tcShiftRight(dst, parts, bits);
  436. return lost_fraction;
  437. }
  438. /* Combine the effect of two lost fractions. */
  439. static lostFraction
  440. combineLostFractions(lostFraction moreSignificant,
  441. lostFraction lessSignificant)
  442. {
  443. if (lessSignificant != lfExactlyZero) {
  444. if (moreSignificant == lfExactlyZero)
  445. moreSignificant = lfLessThanHalf;
  446. else if (moreSignificant == lfExactlyHalf)
  447. moreSignificant = lfMoreThanHalf;
  448. }
  449. return moreSignificant;
  450. }
  451. /* The error from the true value, in half-ulps, on multiplying two
  452. floating point numbers, which differ from the value they
  453. approximate by at most HUE1 and HUE2 half-ulps, is strictly less
  454. than the returned value.
  455. See "How to Read Floating Point Numbers Accurately" by William D
  456. Clinger. */
  457. static unsigned int
  458. HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
  459. {
  460. assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
  461. if (HUerr1 + HUerr2 == 0)
  462. return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
  463. else
  464. return inexactMultiply + 2 * (HUerr1 + HUerr2);
  465. }
  466. /* The number of ulps from the boundary (zero, or half if ISNEAREST)
  467. when the least significant BITS are truncated. BITS cannot be
  468. zero. */
  469. static APFloatBase::integerPart
  470. ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits,
  471. bool isNearest) {
  472. unsigned int count, partBits;
  473. APFloatBase::integerPart part, boundary;
  474. assert(bits != 0);
  475. bits--;
  476. count = bits / APFloatBase::integerPartWidth;
  477. partBits = bits % APFloatBase::integerPartWidth + 1;
  478. part = parts[count] & (~(APFloatBase::integerPart) 0 >> (APFloatBase::integerPartWidth - partBits));
  479. if (isNearest)
  480. boundary = (APFloatBase::integerPart) 1 << (partBits - 1);
  481. else
  482. boundary = 0;
  483. if (count == 0) {
  484. if (part - boundary <= boundary - part)
  485. return part - boundary;
  486. else
  487. return boundary - part;
  488. }
  489. if (part == boundary) {
  490. while (--count)
  491. if (parts[count])
  492. return ~(APFloatBase::integerPart) 0; /* A lot. */
  493. return parts[0];
  494. } else if (part == boundary - 1) {
  495. while (--count)
  496. if (~parts[count])
  497. return ~(APFloatBase::integerPart) 0; /* A lot. */
  498. return -parts[0];
  499. }
  500. return ~(APFloatBase::integerPart) 0; /* A lot. */
  501. }
  502. /* Place pow(5, power) in DST, and return the number of parts used.
  503. DST must be at least one part larger than size of the answer. */
  504. static unsigned int
  505. powerOf5(APFloatBase::integerPart *dst, unsigned int power) {
  506. static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
  507. APFloatBase::integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
  508. pow5s[0] = 78125 * 5;
  509. unsigned int partsCount[16] = { 1 };
  510. APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
  511. unsigned int result;
  512. assert(power <= maxExponent);
  513. p1 = dst;
  514. p2 = scratch;
  515. *p1 = firstEightPowers[power & 7];
  516. power >>= 3;
  517. result = 1;
  518. pow5 = pow5s;
  519. for (unsigned int n = 0; power; power >>= 1, n++) {
  520. unsigned int pc;
  521. pc = partsCount[n];
  522. /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
  523. if (pc == 0) {
  524. pc = partsCount[n - 1];
  525. APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
  526. pc *= 2;
  527. if (pow5[pc - 1] == 0)
  528. pc--;
  529. partsCount[n] = pc;
  530. }
  531. if (power & 1) {
  532. APFloatBase::integerPart *tmp;
  533. APInt::tcFullMultiply(p2, p1, pow5, result, pc);
  534. result += pc;
  535. if (p2[result - 1] == 0)
  536. result--;
  537. /* Now result is in p1 with partsCount parts and p2 is scratch
  538. space. */
  539. tmp = p1;
  540. p1 = p2;
  541. p2 = tmp;
  542. }
  543. pow5 += pc;
  544. }
  545. if (p1 != dst)
  546. APInt::tcAssign(dst, p1, result);
  547. return result;
  548. }
  549. /* Zero at the end to avoid modular arithmetic when adding one; used
  550. when rounding up during hexadecimal output. */
  551. static const char hexDigitsLower[] = "0123456789abcdef0";
  552. static const char hexDigitsUpper[] = "0123456789ABCDEF0";
  553. static const char infinityL[] = "infinity";
  554. static const char infinityU[] = "INFINITY";
  555. static const char NaNL[] = "nan";
  556. static const char NaNU[] = "NAN";
  557. /* Write out an integerPart in hexadecimal, starting with the most
  558. significant nibble. Write out exactly COUNT hexdigits, return
  559. COUNT. */
  560. static unsigned int
  561. partAsHex (char *dst, APFloatBase::integerPart part, unsigned int count,
  562. const char *hexDigitChars)
  563. {
  564. unsigned int result = count;
  565. assert(count != 0 && count <= APFloatBase::integerPartWidth / 4);
  566. part >>= (APFloatBase::integerPartWidth - 4 * count);
  567. while (count--) {
  568. dst[count] = hexDigitChars[part & 0xf];
  569. part >>= 4;
  570. }
  571. return result;
  572. }
  573. /* Write out an unsigned decimal integer. */
  574. static char *
  575. writeUnsignedDecimal (char *dst, unsigned int n)
  576. {
  577. char buff[40], *p;
  578. p = buff;
  579. do
  580. *p++ = '0' + n % 10;
  581. while (n /= 10);
  582. do
  583. *dst++ = *--p;
  584. while (p != buff);
  585. return dst;
  586. }
  587. /* Write out a signed decimal integer. */
  588. static char *
  589. writeSignedDecimal (char *dst, int value)
  590. {
  591. if (value < 0) {
  592. *dst++ = '-';
  593. dst = writeUnsignedDecimal(dst, -(unsigned) value);
  594. } else
  595. dst = writeUnsignedDecimal(dst, value);
  596. return dst;
  597. }
  598. namespace detail {
  599. /* Constructors. */
  600. void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
  601. unsigned int count;
  602. semantics = ourSemantics;
  603. count = partCount();
  604. if (count > 1)
  605. significand.parts = new integerPart[count];
  606. }
  607. void IEEEFloat::freeSignificand() {
  608. if (needsCleanup())
  609. delete [] significand.parts;
  610. }
  611. void IEEEFloat::assign(const IEEEFloat &rhs) {
  612. assert(semantics == rhs.semantics);
  613. sign = rhs.sign;
  614. category = rhs.category;
  615. exponent = rhs.exponent;
  616. if (isFiniteNonZero() || category == fcNaN)
  617. copySignificand(rhs);
  618. }
  619. void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
  620. assert(isFiniteNonZero() || category == fcNaN);
  621. assert(rhs.partCount() >= partCount());
  622. APInt::tcAssign(significandParts(), rhs.significandParts(),
  623. partCount());
  624. }
  625. /* Make this number a NaN, with an arbitrary but deterministic value
  626. for the significand. If double or longer, this is a signalling NaN,
  627. which may not be ideal. If float, this is QNaN(0). */
  628. void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
  629. category = fcNaN;
  630. sign = Negative;
  631. exponent = exponentNaN();
  632. integerPart *significand = significandParts();
  633. unsigned numParts = partCount();
  634. // Set the significand bits to the fill.
  635. if (!fill || fill->getNumWords() < numParts)
  636. APInt::tcSet(significand, 0, numParts);
  637. if (fill) {
  638. APInt::tcAssign(significand, fill->getRawData(),
  639. std::min(fill->getNumWords(), numParts));
  640. // Zero out the excess bits of the significand.
  641. unsigned bitsToPreserve = semantics->precision - 1;
  642. unsigned part = bitsToPreserve / 64;
  643. bitsToPreserve %= 64;
  644. significand[part] &= ((1ULL << bitsToPreserve) - 1);
  645. for (part++; part != numParts; ++part)
  646. significand[part] = 0;
  647. }
  648. unsigned QNaNBit = semantics->precision - 2;
  649. if (SNaN) {
  650. // We always have to clear the QNaN bit to make it an SNaN.
  651. APInt::tcClearBit(significand, QNaNBit);
  652. // If there are no bits set in the payload, we have to set
  653. // *something* to make it a NaN instead of an infinity;
  654. // conventionally, this is the next bit down from the QNaN bit.
  655. if (APInt::tcIsZero(significand, numParts))
  656. APInt::tcSetBit(significand, QNaNBit - 1);
  657. } else {
  658. // We always have to set the QNaN bit to make it a QNaN.
  659. APInt::tcSetBit(significand, QNaNBit);
  660. }
  661. // For x87 extended precision, we want to make a NaN, not a
  662. // pseudo-NaN. Maybe we should expose the ability to make
  663. // pseudo-NaNs?
  664. if (semantics == &semX87DoubleExtended)
  665. APInt::tcSetBit(significand, QNaNBit + 1);
  666. }
  667. IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
  668. if (this != &rhs) {
  669. if (semantics != rhs.semantics) {
  670. freeSignificand();
  671. initialize(rhs.semantics);
  672. }
  673. assign(rhs);
  674. }
  675. return *this;
  676. }
  677. IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
  678. freeSignificand();
  679. semantics = rhs.semantics;
  680. significand = rhs.significand;
  681. exponent = rhs.exponent;
  682. category = rhs.category;
  683. sign = rhs.sign;
  684. rhs.semantics = &semBogus;
  685. return *this;
  686. }
  687. bool IEEEFloat::isDenormal() const {
  688. return isFiniteNonZero() && (exponent == semantics->minExponent) &&
  689. (APInt::tcExtractBit(significandParts(),
  690. semantics->precision - 1) == 0);
  691. }
  692. bool IEEEFloat::isSmallest() const {
  693. // The smallest number by magnitude in our format will be the smallest
  694. // denormal, i.e. the floating point number with exponent being minimum
  695. // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
  696. return isFiniteNonZero() && exponent == semantics->minExponent &&
  697. significandMSB() == 0;
  698. }
  699. bool IEEEFloat::isSignificandAllOnes() const {
  700. // Test if the significand excluding the integral bit is all ones. This allows
  701. // us to test for binade boundaries.
  702. const integerPart *Parts = significandParts();
  703. const unsigned PartCount = partCountForBits(semantics->precision);
  704. for (unsigned i = 0; i < PartCount - 1; i++)
  705. if (~Parts[i])
  706. return false;
  707. // Set the unused high bits to all ones when we compare.
  708. const unsigned NumHighBits =
  709. PartCount*integerPartWidth - semantics->precision + 1;
  710. assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
  711. "Can not have more high bits to fill than integerPartWidth");
  712. const integerPart HighBitFill =
  713. ~integerPart(0) << (integerPartWidth - NumHighBits);
  714. if (~(Parts[PartCount - 1] | HighBitFill))
  715. return false;
  716. return true;
  717. }
  718. bool IEEEFloat::isSignificandAllZeros() const {
  719. // Test if the significand excluding the integral bit is all zeros. This
  720. // allows us to test for binade boundaries.
  721. const integerPart *Parts = significandParts();
  722. const unsigned PartCount = partCountForBits(semantics->precision);
  723. for (unsigned i = 0; i < PartCount - 1; i++)
  724. if (Parts[i])
  725. return false;
  726. // Compute how many bits are used in the final word.
  727. const unsigned NumHighBits =
  728. PartCount*integerPartWidth - semantics->precision + 1;
  729. assert(NumHighBits < integerPartWidth && "Can not have more high bits to "
  730. "clear than integerPartWidth");
  731. const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
  732. if (Parts[PartCount - 1] & HighBitMask)
  733. return false;
  734. return true;
  735. }
  736. bool IEEEFloat::isLargest() const {
  737. // The largest number by magnitude in our format will be the floating point
  738. // number with maximum exponent and with significand that is all ones.
  739. return isFiniteNonZero() && exponent == semantics->maxExponent
  740. && isSignificandAllOnes();
  741. }
  742. bool IEEEFloat::isInteger() const {
  743. // This could be made more efficient; I'm going for obviously correct.
  744. if (!isFinite()) return false;
  745. IEEEFloat truncated = *this;
  746. truncated.roundToIntegral(rmTowardZero);
  747. return compare(truncated) == cmpEqual;
  748. }
  749. bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
  750. if (this == &rhs)
  751. return true;
  752. if (semantics != rhs.semantics ||
  753. category != rhs.category ||
  754. sign != rhs.sign)
  755. return false;
  756. if (category==fcZero || category==fcInfinity)
  757. return true;
  758. if (isFiniteNonZero() && exponent != rhs.exponent)
  759. return false;
  760. return std::equal(significandParts(), significandParts() + partCount(),
  761. rhs.significandParts());
  762. }
  763. IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
  764. initialize(&ourSemantics);
  765. sign = 0;
  766. category = fcNormal;
  767. zeroSignificand();
  768. exponent = ourSemantics.precision - 1;
  769. significandParts()[0] = value;
  770. normalize(rmNearestTiesToEven, lfExactlyZero);
  771. }
  772. IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
  773. initialize(&ourSemantics);
  774. makeZero(false);
  775. }
  776. // Delegate to the previous constructor, because later copy constructor may
  777. // actually inspects category, which can't be garbage.
  778. IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
  779. : IEEEFloat(ourSemantics) {}
  780. IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
  781. initialize(rhs.semantics);
  782. assign(rhs);
  783. }
  784. IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
  785. *this = std::move(rhs);
  786. }
  787. IEEEFloat::~IEEEFloat() { freeSignificand(); }
  788. unsigned int IEEEFloat::partCount() const {
  789. return partCountForBits(semantics->precision + 1);
  790. }
  791. const IEEEFloat::integerPart *IEEEFloat::significandParts() const {
  792. return const_cast<IEEEFloat *>(this)->significandParts();
  793. }
  794. IEEEFloat::integerPart *IEEEFloat::significandParts() {
  795. if (partCount() > 1)
  796. return significand.parts;
  797. else
  798. return &significand.part;
  799. }
  800. void IEEEFloat::zeroSignificand() {
  801. APInt::tcSet(significandParts(), 0, partCount());
  802. }
  803. /* Increment an fcNormal floating point number's significand. */
  804. void IEEEFloat::incrementSignificand() {
  805. integerPart carry;
  806. carry = APInt::tcIncrement(significandParts(), partCount());
  807. /* Our callers should never cause us to overflow. */
  808. assert(carry == 0);
  809. (void)carry;
  810. }
  811. /* Add the significand of the RHS. Returns the carry flag. */
  812. IEEEFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
  813. integerPart *parts;
  814. parts = significandParts();
  815. assert(semantics == rhs.semantics);
  816. assert(exponent == rhs.exponent);
  817. return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
  818. }
  819. /* Subtract the significand of the RHS with a borrow flag. Returns
  820. the borrow flag. */
  821. IEEEFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
  822. integerPart borrow) {
  823. integerPart *parts;
  824. parts = significandParts();
  825. assert(semantics == rhs.semantics);
  826. assert(exponent == rhs.exponent);
  827. return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
  828. partCount());
  829. }
  830. /* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
  831. on to the full-precision result of the multiplication. Returns the
  832. lost fraction. */
  833. lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
  834. IEEEFloat addend) {
  835. unsigned int omsb; // One, not zero, based MSB.
  836. unsigned int partsCount, newPartsCount, precision;
  837. integerPart *lhsSignificand;
  838. integerPart scratch[4];
  839. integerPart *fullSignificand;
  840. lostFraction lost_fraction;
  841. bool ignored;
  842. assert(semantics == rhs.semantics);
  843. precision = semantics->precision;
  844. // Allocate space for twice as many bits as the original significand, plus one
  845. // extra bit for the addition to overflow into.
  846. newPartsCount = partCountForBits(precision * 2 + 1);
  847. if (newPartsCount > 4)
  848. fullSignificand = new integerPart[newPartsCount];
  849. else
  850. fullSignificand = scratch;
  851. lhsSignificand = significandParts();
  852. partsCount = partCount();
  853. APInt::tcFullMultiply(fullSignificand, lhsSignificand,
  854. rhs.significandParts(), partsCount, partsCount);
  855. lost_fraction = lfExactlyZero;
  856. omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
  857. exponent += rhs.exponent;
  858. // Assume the operands involved in the multiplication are single-precision
  859. // FP, and the two multiplicants are:
  860. // *this = a23 . a22 ... a0 * 2^e1
  861. // rhs = b23 . b22 ... b0 * 2^e2
  862. // the result of multiplication is:
  863. // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
  864. // Note that there are three significant bits at the left-hand side of the
  865. // radix point: two for the multiplication, and an overflow bit for the
  866. // addition (that will always be zero at this point). Move the radix point
  867. // toward left by two bits, and adjust exponent accordingly.
  868. exponent += 2;
  869. if (addend.isNonZero()) {
  870. // The intermediate result of the multiplication has "2 * precision"
  871. // signicant bit; adjust the addend to be consistent with mul result.
  872. //
  873. Significand savedSignificand = significand;
  874. const fltSemantics *savedSemantics = semantics;
  875. fltSemantics extendedSemantics;
  876. opStatus status;
  877. unsigned int extendedPrecision;
  878. // Normalize our MSB to one below the top bit to allow for overflow.
  879. extendedPrecision = 2 * precision + 1;
  880. if (omsb != extendedPrecision - 1) {
  881. assert(extendedPrecision > omsb);
  882. APInt::tcShiftLeft(fullSignificand, newPartsCount,
  883. (extendedPrecision - 1) - omsb);
  884. exponent -= (extendedPrecision - 1) - omsb;
  885. }
  886. /* Create new semantics. */
  887. extendedSemantics = *semantics;
  888. extendedSemantics.precision = extendedPrecision;
  889. if (newPartsCount == 1)
  890. significand.part = fullSignificand[0];
  891. else
  892. significand.parts = fullSignificand;
  893. semantics = &extendedSemantics;
  894. // Make a copy so we can convert it to the extended semantics.
  895. // Note that we cannot convert the addend directly, as the extendedSemantics
  896. // is a local variable (which we take a reference to).
  897. IEEEFloat extendedAddend(addend);
  898. status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
  899. assert(status == opOK);
  900. (void)status;
  901. // Shift the significand of the addend right by one bit. This guarantees
  902. // that the high bit of the significand is zero (same as fullSignificand),
  903. // so the addition will overflow (if it does overflow at all) into the top bit.
  904. lost_fraction = extendedAddend.shiftSignificandRight(1);
  905. assert(lost_fraction == lfExactlyZero &&
  906. "Lost precision while shifting addend for fused-multiply-add.");
  907. lost_fraction = addOrSubtractSignificand(extendedAddend, false);
  908. /* Restore our state. */
  909. if (newPartsCount == 1)
  910. fullSignificand[0] = significand.part;
  911. significand = savedSignificand;
  912. semantics = savedSemantics;
  913. omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
  914. }
  915. // Convert the result having "2 * precision" significant-bits back to the one
  916. // having "precision" significant-bits. First, move the radix point from
  917. // poision "2*precision - 1" to "precision - 1". The exponent need to be
  918. // adjusted by "2*precision - 1" - "precision - 1" = "precision".
  919. exponent -= precision + 1;
  920. // In case MSB resides at the left-hand side of radix point, shift the
  921. // mantissa right by some amount to make sure the MSB reside right before
  922. // the radix point (i.e. "MSB . rest-significant-bits").
  923. //
  924. // Note that the result is not normalized when "omsb < precision". So, the
  925. // caller needs to call IEEEFloat::normalize() if normalized value is
  926. // expected.
  927. if (omsb > precision) {
  928. unsigned int bits, significantParts;
  929. lostFraction lf;
  930. bits = omsb - precision;
  931. significantParts = partCountForBits(omsb);
  932. lf = shiftRight(fullSignificand, significantParts, bits);
  933. lost_fraction = combineLostFractions(lf, lost_fraction);
  934. exponent += bits;
  935. }
  936. APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
  937. if (newPartsCount > 4)
  938. delete [] fullSignificand;
  939. return lost_fraction;
  940. }
  941. lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs) {
  942. return multiplySignificand(rhs, IEEEFloat(*semantics));
  943. }
  944. /* Multiply the significands of LHS and RHS to DST. */
  945. lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
  946. unsigned int bit, i, partsCount;
  947. const integerPart *rhsSignificand;
  948. integerPart *lhsSignificand, *dividend, *divisor;
  949. integerPart scratch[4];
  950. lostFraction lost_fraction;
  951. assert(semantics == rhs.semantics);
  952. lhsSignificand = significandParts();
  953. rhsSignificand = rhs.significandParts();
  954. partsCount = partCount();
  955. if (partsCount > 2)
  956. dividend = new integerPart[partsCount * 2];
  957. else
  958. dividend = scratch;
  959. divisor = dividend + partsCount;
  960. /* Copy the dividend and divisor as they will be modified in-place. */
  961. for (i = 0; i < partsCount; i++) {
  962. dividend[i] = lhsSignificand[i];
  963. divisor[i] = rhsSignificand[i];
  964. lhsSignificand[i] = 0;
  965. }
  966. exponent -= rhs.exponent;
  967. unsigned int precision = semantics->precision;
  968. /* Normalize the divisor. */
  969. bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
  970. if (bit) {
  971. exponent += bit;
  972. APInt::tcShiftLeft(divisor, partsCount, bit);
  973. }
  974. /* Normalize the dividend. */
  975. bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
  976. if (bit) {
  977. exponent -= bit;
  978. APInt::tcShiftLeft(dividend, partsCount, bit);
  979. }
  980. /* Ensure the dividend >= divisor initially for the loop below.
  981. Incidentally, this means that the division loop below is
  982. guaranteed to set the integer bit to one. */
  983. if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
  984. exponent--;
  985. APInt::tcShiftLeft(dividend, partsCount, 1);
  986. assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
  987. }
  988. /* Long division. */
  989. for (bit = precision; bit; bit -= 1) {
  990. if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
  991. APInt::tcSubtract(dividend, divisor, 0, partsCount);
  992. APInt::tcSetBit(lhsSignificand, bit - 1);
  993. }
  994. APInt::tcShiftLeft(dividend, partsCount, 1);
  995. }
  996. /* Figure out the lost fraction. */
  997. int cmp = APInt::tcCompare(dividend, divisor, partsCount);
  998. if (cmp > 0)
  999. lost_fraction = lfMoreThanHalf;
  1000. else if (cmp == 0)
  1001. lost_fraction = lfExactlyHalf;
  1002. else if (APInt::tcIsZero(dividend, partsCount))
  1003. lost_fraction = lfExactlyZero;
  1004. else
  1005. lost_fraction = lfLessThanHalf;
  1006. if (partsCount > 2)
  1007. delete [] dividend;
  1008. return lost_fraction;
  1009. }
  1010. unsigned int IEEEFloat::significandMSB() const {
  1011. return APInt::tcMSB(significandParts(), partCount());
  1012. }
  1013. unsigned int IEEEFloat::significandLSB() const {
  1014. return APInt::tcLSB(significandParts(), partCount());
  1015. }
  1016. /* Note that a zero result is NOT normalized to fcZero. */
  1017. lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
  1018. /* Our exponent should not overflow. */
  1019. assert((ExponentType) (exponent + bits) >= exponent);
  1020. exponent += bits;
  1021. return shiftRight(significandParts(), partCount(), bits);
  1022. }
  1023. /* Shift the significand left BITS bits, subtract BITS from its exponent. */
  1024. void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
  1025. assert(bits < semantics->precision);
  1026. if (bits) {
  1027. unsigned int partsCount = partCount();
  1028. APInt::tcShiftLeft(significandParts(), partsCount, bits);
  1029. exponent -= bits;
  1030. assert(!APInt::tcIsZero(significandParts(), partsCount));
  1031. }
  1032. }
  1033. IEEEFloat::cmpResult
  1034. IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const {
  1035. int compare;
  1036. assert(semantics == rhs.semantics);
  1037. assert(isFiniteNonZero());
  1038. assert(rhs.isFiniteNonZero());
  1039. compare = exponent - rhs.exponent;
  1040. /* If exponents are equal, do an unsigned bignum comparison of the
  1041. significands. */
  1042. if (compare == 0)
  1043. compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
  1044. partCount());
  1045. if (compare > 0)
  1046. return cmpGreaterThan;
  1047. else if (compare < 0)
  1048. return cmpLessThan;
  1049. else
  1050. return cmpEqual;
  1051. }
  1052. /* Set the least significant BITS bits of a bignum, clear the
  1053. rest. */
  1054. static void tcSetLeastSignificantBits(APInt::WordType *dst, unsigned parts,
  1055. unsigned bits) {
  1056. unsigned i = 0;
  1057. while (bits > APInt::APINT_BITS_PER_WORD) {
  1058. dst[i++] = ~(APInt::WordType)0;
  1059. bits -= APInt::APINT_BITS_PER_WORD;
  1060. }
  1061. if (bits)
  1062. dst[i++] = ~(APInt::WordType)0 >> (APInt::APINT_BITS_PER_WORD - bits);
  1063. while (i < parts)
  1064. dst[i++] = 0;
  1065. }
  1066. /* Handle overflow. Sign is preserved. We either become infinity or
  1067. the largest finite number. */
  1068. IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
  1069. /* Infinity? */
  1070. if (rounding_mode == rmNearestTiesToEven ||
  1071. rounding_mode == rmNearestTiesToAway ||
  1072. (rounding_mode == rmTowardPositive && !sign) ||
  1073. (rounding_mode == rmTowardNegative && sign)) {
  1074. category = fcInfinity;
  1075. return (opStatus) (opOverflow | opInexact);
  1076. }
  1077. /* Otherwise we become the largest finite number. */
  1078. category = fcNormal;
  1079. exponent = semantics->maxExponent;
  1080. tcSetLeastSignificantBits(significandParts(), partCount(),
  1081. semantics->precision);
  1082. return opInexact;
  1083. }
  1084. /* Returns TRUE if, when truncating the current number, with BIT the
  1085. new LSB, with the given lost fraction and rounding mode, the result
  1086. would need to be rounded away from zero (i.e., by increasing the
  1087. signficand). This routine must work for fcZero of both signs, and
  1088. fcNormal numbers. */
  1089. bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
  1090. lostFraction lost_fraction,
  1091. unsigned int bit) const {
  1092. /* NaNs and infinities should not have lost fractions. */
  1093. assert(isFiniteNonZero() || category == fcZero);
  1094. /* Current callers never pass this so we don't handle it. */
  1095. assert(lost_fraction != lfExactlyZero);
  1096. switch (rounding_mode) {
  1097. case rmNearestTiesToAway:
  1098. return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
  1099. case rmNearestTiesToEven:
  1100. if (lost_fraction == lfMoreThanHalf)
  1101. return true;
  1102. /* Our zeroes don't have a significand to test. */
  1103. if (lost_fraction == lfExactlyHalf && category != fcZero)
  1104. return APInt::tcExtractBit(significandParts(), bit);
  1105. return false;
  1106. case rmTowardZero:
  1107. return false;
  1108. case rmTowardPositive:
  1109. return !sign;
  1110. case rmTowardNegative:
  1111. return sign;
  1112. default:
  1113. break;
  1114. }
  1115. llvm_unreachable("Invalid rounding mode found");
  1116. }
  1117. IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
  1118. lostFraction lost_fraction) {
  1119. unsigned int omsb; /* One, not zero, based MSB. */
  1120. int exponentChange;
  1121. if (!isFiniteNonZero())
  1122. return opOK;
  1123. /* Before rounding normalize the exponent of fcNormal numbers. */
  1124. omsb = significandMSB() + 1;
  1125. if (omsb) {
  1126. /* OMSB is numbered from 1. We want to place it in the integer
  1127. bit numbered PRECISION if possible, with a compensating change in
  1128. the exponent. */
  1129. exponentChange = omsb - semantics->precision;
  1130. /* If the resulting exponent is too high, overflow according to
  1131. the rounding mode. */
  1132. if (exponent + exponentChange > semantics->maxExponent)
  1133. return handleOverflow(rounding_mode);
  1134. /* Subnormal numbers have exponent minExponent, and their MSB
  1135. is forced based on that. */
  1136. if (exponent + exponentChange < semantics->minExponent)
  1137. exponentChange = semantics->minExponent - exponent;
  1138. /* Shifting left is easy as we don't lose precision. */
  1139. if (exponentChange < 0) {
  1140. assert(lost_fraction == lfExactlyZero);
  1141. shiftSignificandLeft(-exponentChange);
  1142. return opOK;
  1143. }
  1144. if (exponentChange > 0) {
  1145. lostFraction lf;
  1146. /* Shift right and capture any new lost fraction. */
  1147. lf = shiftSignificandRight(exponentChange);
  1148. lost_fraction = combineLostFractions(lf, lost_fraction);
  1149. /* Keep OMSB up-to-date. */
  1150. if (omsb > (unsigned) exponentChange)
  1151. omsb -= exponentChange;
  1152. else
  1153. omsb = 0;
  1154. }
  1155. }
  1156. /* Now round the number according to rounding_mode given the lost
  1157. fraction. */
  1158. /* As specified in IEEE 754, since we do not trap we do not report
  1159. underflow for exact results. */
  1160. if (lost_fraction == lfExactlyZero) {
  1161. /* Canonicalize zeroes. */
  1162. if (omsb == 0)
  1163. category = fcZero;
  1164. return opOK;
  1165. }
  1166. /* Increment the significand if we're rounding away from zero. */
  1167. if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
  1168. if (omsb == 0)
  1169. exponent = semantics->minExponent;
  1170. incrementSignificand();
  1171. omsb = significandMSB() + 1;
  1172. /* Did the significand increment overflow? */
  1173. if (omsb == (unsigned) semantics->precision + 1) {
  1174. /* Renormalize by incrementing the exponent and shifting our
  1175. significand right one. However if we already have the
  1176. maximum exponent we overflow to infinity. */
  1177. if (exponent == semantics->maxExponent) {
  1178. category = fcInfinity;
  1179. return (opStatus) (opOverflow | opInexact);
  1180. }
  1181. shiftSignificandRight(1);
  1182. return opInexact;
  1183. }
  1184. }
  1185. /* The normal case - we were and are not denormal, and any
  1186. significand increment above didn't overflow. */
  1187. if (omsb == semantics->precision)
  1188. return opInexact;
  1189. /* We have a non-zero denormal. */
  1190. assert(omsb < semantics->precision);
  1191. /* Canonicalize zeroes. */
  1192. if (omsb == 0)
  1193. category = fcZero;
  1194. /* The fcZero case is a denormal that underflowed to zero. */
  1195. return (opStatus) (opUnderflow | opInexact);
  1196. }
  1197. IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
  1198. bool subtract) {
  1199. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1200. default:
  1201. llvm_unreachable(nullptr);
  1202. case PackCategoriesIntoKey(fcZero, fcNaN):
  1203. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1204. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1205. assign(rhs);
  1206. LLVM_FALLTHROUGH;
  1207. case PackCategoriesIntoKey(fcNaN, fcZero):
  1208. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1209. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1210. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1211. if (isSignaling()) {
  1212. makeQuiet();
  1213. return opInvalidOp;
  1214. }
  1215. return rhs.isSignaling() ? opInvalidOp : opOK;
  1216. case PackCategoriesIntoKey(fcNormal, fcZero):
  1217. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1218. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1219. return opOK;
  1220. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1221. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1222. category = fcInfinity;
  1223. sign = rhs.sign ^ subtract;
  1224. return opOK;
  1225. case PackCategoriesIntoKey(fcZero, fcNormal):
  1226. assign(rhs);
  1227. sign = rhs.sign ^ subtract;
  1228. return opOK;
  1229. case PackCategoriesIntoKey(fcZero, fcZero):
  1230. /* Sign depends on rounding mode; handled by caller. */
  1231. return opOK;
  1232. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1233. /* Differently signed infinities can only be validly
  1234. subtracted. */
  1235. if (((sign ^ rhs.sign)!=0) != subtract) {
  1236. makeNaN();
  1237. return opInvalidOp;
  1238. }
  1239. return opOK;
  1240. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1241. return opDivByZero;
  1242. }
  1243. }
  1244. /* Add or subtract two normal numbers. */
  1245. lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
  1246. bool subtract) {
  1247. integerPart carry;
  1248. lostFraction lost_fraction;
  1249. int bits;
  1250. /* Determine if the operation on the absolute values is effectively
  1251. an addition or subtraction. */
  1252. subtract ^= static_cast<bool>(sign ^ rhs.sign);
  1253. /* Are we bigger exponent-wise than the RHS? */
  1254. bits = exponent - rhs.exponent;
  1255. /* Subtraction is more subtle than one might naively expect. */
  1256. if (subtract) {
  1257. IEEEFloat temp_rhs(rhs);
  1258. if (bits == 0)
  1259. lost_fraction = lfExactlyZero;
  1260. else if (bits > 0) {
  1261. lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
  1262. shiftSignificandLeft(1);
  1263. } else {
  1264. lost_fraction = shiftSignificandRight(-bits - 1);
  1265. temp_rhs.shiftSignificandLeft(1);
  1266. }
  1267. // Should we reverse the subtraction.
  1268. if (compareAbsoluteValue(temp_rhs) == cmpLessThan) {
  1269. carry = temp_rhs.subtractSignificand
  1270. (*this, lost_fraction != lfExactlyZero);
  1271. copySignificand(temp_rhs);
  1272. sign = !sign;
  1273. } else {
  1274. carry = subtractSignificand
  1275. (temp_rhs, lost_fraction != lfExactlyZero);
  1276. }
  1277. /* Invert the lost fraction - it was on the RHS and
  1278. subtracted. */
  1279. if (lost_fraction == lfLessThanHalf)
  1280. lost_fraction = lfMoreThanHalf;
  1281. else if (lost_fraction == lfMoreThanHalf)
  1282. lost_fraction = lfLessThanHalf;
  1283. /* The code above is intended to ensure that no borrow is
  1284. necessary. */
  1285. assert(!carry);
  1286. (void)carry;
  1287. } else {
  1288. if (bits > 0) {
  1289. IEEEFloat temp_rhs(rhs);
  1290. lost_fraction = temp_rhs.shiftSignificandRight(bits);
  1291. carry = addSignificand(temp_rhs);
  1292. } else {
  1293. lost_fraction = shiftSignificandRight(-bits);
  1294. carry = addSignificand(rhs);
  1295. }
  1296. /* We have a guard bit; generating a carry cannot happen. */
  1297. assert(!carry);
  1298. (void)carry;
  1299. }
  1300. return lost_fraction;
  1301. }
  1302. IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
  1303. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1304. default:
  1305. llvm_unreachable(nullptr);
  1306. case PackCategoriesIntoKey(fcZero, fcNaN):
  1307. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1308. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1309. assign(rhs);
  1310. sign = false;
  1311. LLVM_FALLTHROUGH;
  1312. case PackCategoriesIntoKey(fcNaN, fcZero):
  1313. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1314. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1315. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1316. sign ^= rhs.sign; // restore the original sign
  1317. if (isSignaling()) {
  1318. makeQuiet();
  1319. return opInvalidOp;
  1320. }
  1321. return rhs.isSignaling() ? opInvalidOp : opOK;
  1322. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1323. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1324. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1325. category = fcInfinity;
  1326. return opOK;
  1327. case PackCategoriesIntoKey(fcZero, fcNormal):
  1328. case PackCategoriesIntoKey(fcNormal, fcZero):
  1329. case PackCategoriesIntoKey(fcZero, fcZero):
  1330. category = fcZero;
  1331. return opOK;
  1332. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1333. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1334. makeNaN();
  1335. return opInvalidOp;
  1336. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1337. return opOK;
  1338. }
  1339. }
  1340. IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
  1341. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1342. default:
  1343. llvm_unreachable(nullptr);
  1344. case PackCategoriesIntoKey(fcZero, fcNaN):
  1345. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1346. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1347. assign(rhs);
  1348. sign = false;
  1349. LLVM_FALLTHROUGH;
  1350. case PackCategoriesIntoKey(fcNaN, fcZero):
  1351. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1352. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1353. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1354. sign ^= rhs.sign; // restore the original sign
  1355. if (isSignaling()) {
  1356. makeQuiet();
  1357. return opInvalidOp;
  1358. }
  1359. return rhs.isSignaling() ? opInvalidOp : opOK;
  1360. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1361. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1362. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1363. case PackCategoriesIntoKey(fcZero, fcNormal):
  1364. return opOK;
  1365. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1366. category = fcZero;
  1367. return opOK;
  1368. case PackCategoriesIntoKey(fcNormal, fcZero):
  1369. category = fcInfinity;
  1370. return opDivByZero;
  1371. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1372. case PackCategoriesIntoKey(fcZero, fcZero):
  1373. makeNaN();
  1374. return opInvalidOp;
  1375. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1376. return opOK;
  1377. }
  1378. }
  1379. IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
  1380. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1381. default:
  1382. llvm_unreachable(nullptr);
  1383. case PackCategoriesIntoKey(fcZero, fcNaN):
  1384. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1385. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1386. assign(rhs);
  1387. LLVM_FALLTHROUGH;
  1388. case PackCategoriesIntoKey(fcNaN, fcZero):
  1389. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1390. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1391. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1392. if (isSignaling()) {
  1393. makeQuiet();
  1394. return opInvalidOp;
  1395. }
  1396. return rhs.isSignaling() ? opInvalidOp : opOK;
  1397. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1398. case PackCategoriesIntoKey(fcZero, fcNormal):
  1399. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1400. return opOK;
  1401. case PackCategoriesIntoKey(fcNormal, fcZero):
  1402. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1403. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1404. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1405. case PackCategoriesIntoKey(fcZero, fcZero):
  1406. makeNaN();
  1407. return opInvalidOp;
  1408. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1409. return opOK;
  1410. }
  1411. }
  1412. IEEEFloat::opStatus IEEEFloat::remainderSpecials(const IEEEFloat &rhs) {
  1413. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1414. default:
  1415. llvm_unreachable(nullptr);
  1416. case PackCategoriesIntoKey(fcZero, fcNaN):
  1417. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1418. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1419. assign(rhs);
  1420. LLVM_FALLTHROUGH;
  1421. case PackCategoriesIntoKey(fcNaN, fcZero):
  1422. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1423. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1424. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1425. if (isSignaling()) {
  1426. makeQuiet();
  1427. return opInvalidOp;
  1428. }
  1429. return rhs.isSignaling() ? opInvalidOp : opOK;
  1430. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1431. case PackCategoriesIntoKey(fcZero, fcNormal):
  1432. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1433. return opOK;
  1434. case PackCategoriesIntoKey(fcNormal, fcZero):
  1435. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1436. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1437. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1438. case PackCategoriesIntoKey(fcZero, fcZero):
  1439. makeNaN();
  1440. return opInvalidOp;
  1441. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1442. return opDivByZero; // fake status, indicating this is not a special case
  1443. }
  1444. }
  1445. /* Change sign. */
  1446. void IEEEFloat::changeSign() {
  1447. /* Look mummy, this one's easy. */
  1448. sign = !sign;
  1449. }
  1450. /* Normalized addition or subtraction. */
  1451. IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
  1452. roundingMode rounding_mode,
  1453. bool subtract) {
  1454. opStatus fs;
  1455. fs = addOrSubtractSpecials(rhs, subtract);
  1456. /* This return code means it was not a simple case. */
  1457. if (fs == opDivByZero) {
  1458. lostFraction lost_fraction;
  1459. lost_fraction = addOrSubtractSignificand(rhs, subtract);
  1460. fs = normalize(rounding_mode, lost_fraction);
  1461. /* Can only be zero if we lost no fraction. */
  1462. assert(category != fcZero || lost_fraction == lfExactlyZero);
  1463. }
  1464. /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
  1465. positive zero unless rounding to minus infinity, except that
  1466. adding two like-signed zeroes gives that zero. */
  1467. if (category == fcZero) {
  1468. if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
  1469. sign = (rounding_mode == rmTowardNegative);
  1470. }
  1471. return fs;
  1472. }
  1473. /* Normalized addition. */
  1474. IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs,
  1475. roundingMode rounding_mode) {
  1476. return addOrSubtract(rhs, rounding_mode, false);
  1477. }
  1478. /* Normalized subtraction. */
  1479. IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs,
  1480. roundingMode rounding_mode) {
  1481. return addOrSubtract(rhs, rounding_mode, true);
  1482. }
  1483. /* Normalized multiply. */
  1484. IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs,
  1485. roundingMode rounding_mode) {
  1486. opStatus fs;
  1487. sign ^= rhs.sign;
  1488. fs = multiplySpecials(rhs);
  1489. if (isFiniteNonZero()) {
  1490. lostFraction lost_fraction = multiplySignificand(rhs);
  1491. fs = normalize(rounding_mode, lost_fraction);
  1492. if (lost_fraction != lfExactlyZero)
  1493. fs = (opStatus) (fs | opInexact);
  1494. }
  1495. return fs;
  1496. }
  1497. /* Normalized divide. */
  1498. IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs,
  1499. roundingMode rounding_mode) {
  1500. opStatus fs;
  1501. sign ^= rhs.sign;
  1502. fs = divideSpecials(rhs);
  1503. if (isFiniteNonZero()) {
  1504. lostFraction lost_fraction = divideSignificand(rhs);
  1505. fs = normalize(rounding_mode, lost_fraction);
  1506. if (lost_fraction != lfExactlyZero)
  1507. fs = (opStatus) (fs | opInexact);
  1508. }
  1509. return fs;
  1510. }
  1511. /* Normalized remainder. */
  1512. IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) {
  1513. opStatus fs;
  1514. unsigned int origSign = sign;
  1515. // First handle the special cases.
  1516. fs = remainderSpecials(rhs);
  1517. if (fs != opDivByZero)
  1518. return fs;
  1519. fs = opOK;
  1520. // Make sure the current value is less than twice the denom. If the addition
  1521. // did not succeed (an overflow has happened), which means that the finite
  1522. // value we currently posses must be less than twice the denom (as we are
  1523. // using the same semantics).
  1524. IEEEFloat P2 = rhs;
  1525. if (P2.add(rhs, rmNearestTiesToEven) == opOK) {
  1526. fs = mod(P2);
  1527. assert(fs == opOK);
  1528. }
  1529. // Lets work with absolute numbers.
  1530. IEEEFloat P = rhs;
  1531. P.sign = false;
  1532. sign = false;
  1533. //
  1534. // To calculate the remainder we use the following scheme.
  1535. //
  1536. // The remainder is defained as follows:
  1537. //
  1538. // remainder = numer - rquot * denom = x - r * p
  1539. //
  1540. // Where r is the result of: x/p, rounded toward the nearest integral value
  1541. // (with halfway cases rounded toward the even number).
  1542. //
  1543. // Currently, (after x mod 2p):
  1544. // r is the number of 2p's present inside x, which is inherently, an even
  1545. // number of p's.
  1546. //
  1547. // We may split the remaining calculation into 4 options:
  1548. // - if x < 0.5p then we round to the nearest number with is 0, and are done.
  1549. // - if x == 0.5p then we round to the nearest even number which is 0, and we
  1550. // are done as well.
  1551. // - if 0.5p < x < p then we round to nearest number which is 1, and we have
  1552. // to subtract 1p at least once.
  1553. // - if x >= p then we must subtract p at least once, as x must be a
  1554. // remainder.
  1555. //
  1556. // By now, we were done, or we added 1 to r, which in turn, now an odd number.
  1557. //
  1558. // We can now split the remaining calculation to the following 3 options:
  1559. // - if x < 0.5p then we round to the nearest number with is 0, and are done.
  1560. // - if x == 0.5p then we round to the nearest even number. As r is odd, we
  1561. // must round up to the next even number. so we must subtract p once more.
  1562. // - if x > 0.5p (and inherently x < p) then we must round r up to the next
  1563. // integral, and subtract p once more.
  1564. //
  1565. // Extend the semantics to prevent an overflow/underflow or inexact result.
  1566. bool losesInfo;
  1567. fltSemantics extendedSemantics = *semantics;
  1568. extendedSemantics.maxExponent++;
  1569. extendedSemantics.minExponent--;
  1570. extendedSemantics.precision += 2;
  1571. IEEEFloat VEx = *this;
  1572. fs = VEx.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
  1573. assert(fs == opOK && !losesInfo);
  1574. IEEEFloat PEx = P;
  1575. fs = PEx.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
  1576. assert(fs == opOK && !losesInfo);
  1577. // It is simpler to work with 2x instead of 0.5p, and we do not need to lose
  1578. // any fraction.
  1579. fs = VEx.add(VEx, rmNearestTiesToEven);
  1580. assert(fs == opOK);
  1581. if (VEx.compare(PEx) == cmpGreaterThan) {
  1582. fs = subtract(P, rmNearestTiesToEven);
  1583. assert(fs == opOK);
  1584. // Make VEx = this.add(this), but because we have different semantics, we do
  1585. // not want to `convert` again, so we just subtract PEx twice (which equals
  1586. // to the desired value).
  1587. fs = VEx.subtract(PEx, rmNearestTiesToEven);
  1588. assert(fs == opOK);
  1589. fs = VEx.subtract(PEx, rmNearestTiesToEven);
  1590. assert(fs == opOK);
  1591. cmpResult result = VEx.compare(PEx);
  1592. if (result == cmpGreaterThan || result == cmpEqual) {
  1593. fs = subtract(P, rmNearestTiesToEven);
  1594. assert(fs == opOK);
  1595. }
  1596. }
  1597. if (isZero())
  1598. sign = origSign; // IEEE754 requires this
  1599. else
  1600. sign ^= origSign;
  1601. return fs;
  1602. }
  1603. /* Normalized llvm frem (C fmod). */
  1604. IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) {
  1605. opStatus fs;
  1606. fs = modSpecials(rhs);
  1607. unsigned int origSign = sign;
  1608. while (isFiniteNonZero() && rhs.isFiniteNonZero() &&
  1609. compareAbsoluteValue(rhs) != cmpLessThan) {
  1610. IEEEFloat V = scalbn(rhs, ilogb(*this) - ilogb(rhs), rmNearestTiesToEven);
  1611. if (compareAbsoluteValue(V) == cmpLessThan)
  1612. V = scalbn(V, -1, rmNearestTiesToEven);
  1613. V.sign = sign;
  1614. fs = subtract(V, rmNearestTiesToEven);
  1615. assert(fs==opOK);
  1616. }
  1617. if (isZero())
  1618. sign = origSign; // fmod requires this
  1619. return fs;
  1620. }
  1621. /* Normalized fused-multiply-add. */
  1622. IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand,
  1623. const IEEEFloat &addend,
  1624. roundingMode rounding_mode) {
  1625. opStatus fs;
  1626. /* Post-multiplication sign, before addition. */
  1627. sign ^= multiplicand.sign;
  1628. /* If and only if all arguments are normal do we need to do an
  1629. extended-precision calculation. */
  1630. if (isFiniteNonZero() &&
  1631. multiplicand.isFiniteNonZero() &&
  1632. addend.isFinite()) {
  1633. lostFraction lost_fraction;
  1634. lost_fraction = multiplySignificand(multiplicand, addend);
  1635. fs = normalize(rounding_mode, lost_fraction);
  1636. if (lost_fraction != lfExactlyZero)
  1637. fs = (opStatus) (fs | opInexact);
  1638. /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
  1639. positive zero unless rounding to minus infinity, except that
  1640. adding two like-signed zeroes gives that zero. */
  1641. if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
  1642. sign = (rounding_mode == rmTowardNegative);
  1643. } else {
  1644. fs = multiplySpecials(multiplicand);
  1645. /* FS can only be opOK or opInvalidOp. There is no more work
  1646. to do in the latter case. The IEEE-754R standard says it is
  1647. implementation-defined in this case whether, if ADDEND is a
  1648. quiet NaN, we raise invalid op; this implementation does so.
  1649. If we need to do the addition we can do so with normal
  1650. precision. */
  1651. if (fs == opOK)
  1652. fs = addOrSubtract(addend, rounding_mode, false);
  1653. }
  1654. return fs;
  1655. }
  1656. /* Rounding-mode correct round to integral value. */
  1657. IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) {
  1658. opStatus fs;
  1659. if (isInfinity())
  1660. // [IEEE Std 754-2008 6.1]:
  1661. // The behavior of infinity in floating-point arithmetic is derived from the
  1662. // limiting cases of real arithmetic with operands of arbitrarily
  1663. // large magnitude, when such a limit exists.
  1664. // ...
  1665. // Operations on infinite operands are usually exact and therefore signal no
  1666. // exceptions ...
  1667. return opOK;
  1668. if (isNaN()) {
  1669. if (isSignaling()) {
  1670. // [IEEE Std 754-2008 6.2]:
  1671. // Under default exception handling, any operation signaling an invalid
  1672. // operation exception and for which a floating-point result is to be
  1673. // delivered shall deliver a quiet NaN.
  1674. makeQuiet();
  1675. // [IEEE Std 754-2008 6.2]:
  1676. // Signaling NaNs shall be reserved operands that, under default exception
  1677. // handling, signal the invalid operation exception(see 7.2) for every
  1678. // general-computational and signaling-computational operation except for
  1679. // the conversions described in 5.12.
  1680. return opInvalidOp;
  1681. } else {
  1682. // [IEEE Std 754-2008 6.2]:
  1683. // For an operation with quiet NaN inputs, other than maximum and minimum
  1684. // operations, if a floating-point result is to be delivered the result
  1685. // shall be a quiet NaN which should be one of the input NaNs.
  1686. // ...
  1687. // Every general-computational and quiet-computational operation involving
  1688. // one or more input NaNs, none of them signaling, shall signal no
  1689. // exception, except fusedMultiplyAdd might signal the invalid operation
  1690. // exception(see 7.2).
  1691. return opOK;
  1692. }
  1693. }
  1694. if (isZero()) {
  1695. // [IEEE Std 754-2008 6.3]:
  1696. // ... the sign of the result of conversions, the quantize operation, the
  1697. // roundToIntegral operations, and the roundToIntegralExact(see 5.3.1) is
  1698. // the sign of the first or only operand.
  1699. return opOK;
  1700. }
  1701. // If the exponent is large enough, we know that this value is already
  1702. // integral, and the arithmetic below would potentially cause it to saturate
  1703. // to +/-Inf. Bail out early instead.
  1704. if (exponent+1 >= (int)semanticsPrecision(*semantics))
  1705. return opOK;
  1706. // The algorithm here is quite simple: we add 2^(p-1), where p is the
  1707. // precision of our format, and then subtract it back off again. The choice
  1708. // of rounding modes for the addition/subtraction determines the rounding mode
  1709. // for our integral rounding as well.
  1710. // NOTE: When the input value is negative, we do subtraction followed by
  1711. // addition instead.
  1712. APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
  1713. IntegerConstant <<= semanticsPrecision(*semantics)-1;
  1714. IEEEFloat MagicConstant(*semantics);
  1715. fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
  1716. rmNearestTiesToEven);
  1717. assert(fs == opOK);
  1718. MagicConstant.sign = sign;
  1719. // Preserve the input sign so that we can handle the case of zero result
  1720. // correctly.
  1721. bool inputSign = isNegative();
  1722. fs = add(MagicConstant, rounding_mode);
  1723. // Current value and 'MagicConstant' are both integers, so the result of the
  1724. // subtraction is always exact according to Sterbenz' lemma.
  1725. subtract(MagicConstant, rounding_mode);
  1726. // Restore the input sign.
  1727. if (inputSign != isNegative())
  1728. changeSign();
  1729. return fs;
  1730. }
  1731. /* Comparison requires normalized numbers. */
  1732. IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const {
  1733. cmpResult result;
  1734. assert(semantics == rhs.semantics);
  1735. switch (PackCategoriesIntoKey(category, rhs.category)) {
  1736. default:
  1737. llvm_unreachable(nullptr);
  1738. case PackCategoriesIntoKey(fcNaN, fcZero):
  1739. case PackCategoriesIntoKey(fcNaN, fcNormal):
  1740. case PackCategoriesIntoKey(fcNaN, fcInfinity):
  1741. case PackCategoriesIntoKey(fcNaN, fcNaN):
  1742. case PackCategoriesIntoKey(fcZero, fcNaN):
  1743. case PackCategoriesIntoKey(fcNormal, fcNaN):
  1744. case PackCategoriesIntoKey(fcInfinity, fcNaN):
  1745. return cmpUnordered;
  1746. case PackCategoriesIntoKey(fcInfinity, fcNormal):
  1747. case PackCategoriesIntoKey(fcInfinity, fcZero):
  1748. case PackCategoriesIntoKey(fcNormal, fcZero):
  1749. if (sign)
  1750. return cmpLessThan;
  1751. else
  1752. return cmpGreaterThan;
  1753. case PackCategoriesIntoKey(fcNormal, fcInfinity):
  1754. case PackCategoriesIntoKey(fcZero, fcInfinity):
  1755. case PackCategoriesIntoKey(fcZero, fcNormal):
  1756. if (rhs.sign)
  1757. return cmpGreaterThan;
  1758. else
  1759. return cmpLessThan;
  1760. case PackCategoriesIntoKey(fcInfinity, fcInfinity):
  1761. if (sign == rhs.sign)
  1762. return cmpEqual;
  1763. else if (sign)
  1764. return cmpLessThan;
  1765. else
  1766. return cmpGreaterThan;
  1767. case PackCategoriesIntoKey(fcZero, fcZero):
  1768. return cmpEqual;
  1769. case PackCategoriesIntoKey(fcNormal, fcNormal):
  1770. break;
  1771. }
  1772. /* Two normal numbers. Do they have the same sign? */
  1773. if (sign != rhs.sign) {
  1774. if (sign)
  1775. result = cmpLessThan;
  1776. else
  1777. result = cmpGreaterThan;
  1778. } else {
  1779. /* Compare absolute values; invert result if negative. */
  1780. result = compareAbsoluteValue(rhs);
  1781. if (sign) {
  1782. if (result == cmpLessThan)
  1783. result = cmpGreaterThan;
  1784. else if (result == cmpGreaterThan)
  1785. result = cmpLessThan;
  1786. }
  1787. }
  1788. return result;
  1789. }
  1790. /// IEEEFloat::convert - convert a value of one floating point type to another.
  1791. /// The return value corresponds to the IEEE754 exceptions. *losesInfo
  1792. /// records whether the transformation lost information, i.e. whether
  1793. /// converting the result back to the original type will produce the
  1794. /// original value (this is almost the same as return value==fsOK, but there
  1795. /// are edge cases where this is not so).
  1796. IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics,
  1797. roundingMode rounding_mode,
  1798. bool *losesInfo) {
  1799. lostFraction lostFraction;
  1800. unsigned int newPartCount, oldPartCount;
  1801. opStatus fs;
  1802. int shift;
  1803. const fltSemantics &fromSemantics = *semantics;
  1804. lostFraction = lfExactlyZero;
  1805. newPartCount = partCountForBits(toSemantics.precision + 1);
  1806. oldPartCount = partCount();
  1807. shift = toSemantics.precision - fromSemantics.precision;
  1808. bool X86SpecialNan = false;
  1809. if (&fromSemantics == &semX87DoubleExtended &&
  1810. &toSemantics != &semX87DoubleExtended && category == fcNaN &&
  1811. (!(*significandParts() & 0x8000000000000000ULL) ||
  1812. !(*significandParts() & 0x4000000000000000ULL))) {
  1813. // x86 has some unusual NaNs which cannot be represented in any other
  1814. // format; note them here.
  1815. X86SpecialNan = true;
  1816. }
  1817. // If this is a truncation of a denormal number, and the target semantics
  1818. // has larger exponent range than the source semantics (this can happen
  1819. // when truncating from PowerPC double-double to double format), the
  1820. // right shift could lose result mantissa bits. Adjust exponent instead
  1821. // of performing excessive shift.
  1822. if (shift < 0 && isFiniteNonZero()) {
  1823. int exponentChange = significandMSB() + 1 - fromSemantics.precision;
  1824. if (exponent + exponentChange < toSemantics.minExponent)
  1825. exponentChange = toSemantics.minExponent - exponent;
  1826. if (exponentChange < shift)
  1827. exponentChange = shift;
  1828. if (exponentChange < 0) {
  1829. shift -= exponentChange;
  1830. exponent += exponentChange;
  1831. }
  1832. }
  1833. // If this is a truncation, perform the shift before we narrow the storage.
  1834. if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
  1835. lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
  1836. // Fix the storage so it can hold to new value.
  1837. if (newPartCount > oldPartCount) {
  1838. // The new type requires more storage; make it available.
  1839. integerPart *newParts;
  1840. newParts = new integerPart[newPartCount];
  1841. APInt::tcSet(newParts, 0, newPartCount);
  1842. if (isFiniteNonZero() || category==fcNaN)
  1843. APInt::tcAssign(newParts, significandParts(), oldPartCount);
  1844. freeSignificand();
  1845. significand.parts = newParts;
  1846. } else if (newPartCount == 1 && oldPartCount != 1) {
  1847. // Switch to built-in storage for a single part.
  1848. integerPart newPart = 0;
  1849. if (isFiniteNonZero() || category==fcNaN)
  1850. newPart = significandParts()[0];
  1851. freeSignificand();
  1852. significand.part = newPart;
  1853. }
  1854. // Now that we have the right storage, switch the semantics.
  1855. semantics = &toSemantics;
  1856. // If this is an extension, perform the shift now that the storage is
  1857. // available.
  1858. if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
  1859. APInt::tcShiftLeft(significandParts(), newPartCount, shift);
  1860. if (isFiniteNonZero()) {
  1861. fs = normalize(rounding_mode, lostFraction);
  1862. *losesInfo = (fs != opOK);
  1863. } else if (category == fcNaN) {
  1864. *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
  1865. // For x87 extended precision, we want to make a NaN, not a special NaN if
  1866. // the input wasn't special either.
  1867. if (!X86SpecialNan && semantics == &semX87DoubleExtended)
  1868. APInt::tcSetBit(significandParts(), semantics->precision - 1);
  1869. // Convert of sNaN creates qNaN and raises an exception (invalid op).
  1870. // This also guarantees that a sNaN does not become Inf on a truncation
  1871. // that loses all payload bits.
  1872. if (isSignaling()) {
  1873. makeQuiet();
  1874. fs = opInvalidOp;
  1875. } else {
  1876. fs = opOK;
  1877. }
  1878. } else {
  1879. *losesInfo = false;
  1880. fs = opOK;
  1881. }
  1882. return fs;
  1883. }
  1884. /* Convert a floating point number to an integer according to the
  1885. rounding mode. If the rounded integer value is out of range this
  1886. returns an invalid operation exception and the contents of the
  1887. destination parts are unspecified. If the rounded value is in
  1888. range but the floating point number is not the exact integer, the C
  1889. standard doesn't require an inexact exception to be raised. IEEE
  1890. 854 does require it so we do that.
  1891. Note that for conversions to integer type the C standard requires
  1892. round-to-zero to always be used. */
  1893. IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
  1894. MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned,
  1895. roundingMode rounding_mode, bool *isExact) const {
  1896. lostFraction lost_fraction;
  1897. const integerPart *src;
  1898. unsigned int dstPartsCount, truncatedBits;
  1899. *isExact = false;
  1900. /* Handle the three special cases first. */
  1901. if (category == fcInfinity || category == fcNaN)
  1902. return opInvalidOp;
  1903. dstPartsCount = partCountForBits(width);
  1904. assert(dstPartsCount <= parts.size() && "Integer too big");
  1905. if (category == fcZero) {
  1906. APInt::tcSet(parts.data(), 0, dstPartsCount);
  1907. // Negative zero can't be represented as an int.
  1908. *isExact = !sign;
  1909. return opOK;
  1910. }
  1911. src = significandParts();
  1912. /* Step 1: place our absolute value, with any fraction truncated, in
  1913. the destination. */
  1914. if (exponent < 0) {
  1915. /* Our absolute value is less than one; truncate everything. */
  1916. APInt::tcSet(parts.data(), 0, dstPartsCount);
  1917. /* For exponent -1 the integer bit represents .5, look at that.
  1918. For smaller exponents leftmost truncated bit is 0. */
  1919. truncatedBits = semantics->precision -1U - exponent;
  1920. } else {
  1921. /* We want the most significant (exponent + 1) bits; the rest are
  1922. truncated. */
  1923. unsigned int bits = exponent + 1U;
  1924. /* Hopelessly large in magnitude? */
  1925. if (bits > width)
  1926. return opInvalidOp;
  1927. if (bits < semantics->precision) {
  1928. /* We truncate (semantics->precision - bits) bits. */
  1929. truncatedBits = semantics->precision - bits;
  1930. APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
  1931. } else {
  1932. /* We want at least as many bits as are available. */
  1933. APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
  1934. 0);
  1935. APInt::tcShiftLeft(parts.data(), dstPartsCount,
  1936. bits - semantics->precision);
  1937. truncatedBits = 0;
  1938. }
  1939. }
  1940. /* Step 2: work out any lost fraction, and increment the absolute
  1941. value if we would round away from zero. */
  1942. if (truncatedBits) {
  1943. lost_fraction = lostFractionThroughTruncation(src, partCount(),
  1944. truncatedBits);
  1945. if (lost_fraction != lfExactlyZero &&
  1946. roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
  1947. if (APInt::tcIncrement(parts.data(), dstPartsCount))
  1948. return opInvalidOp; /* Overflow. */
  1949. }
  1950. } else {
  1951. lost_fraction = lfExactlyZero;
  1952. }
  1953. /* Step 3: check if we fit in the destination. */
  1954. unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
  1955. if (sign) {
  1956. if (!isSigned) {
  1957. /* Negative numbers cannot be represented as unsigned. */
  1958. if (omsb != 0)
  1959. return opInvalidOp;
  1960. } else {
  1961. /* It takes omsb bits to represent the unsigned integer value.
  1962. We lose a bit for the sign, but care is needed as the
  1963. maximally negative integer is a special case. */
  1964. if (omsb == width &&
  1965. APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb)
  1966. return opInvalidOp;
  1967. /* This case can happen because of rounding. */
  1968. if (omsb > width)
  1969. return opInvalidOp;
  1970. }
  1971. APInt::tcNegate (parts.data(), dstPartsCount);
  1972. } else {
  1973. if (omsb >= width + !isSigned)
  1974. return opInvalidOp;
  1975. }
  1976. if (lost_fraction == lfExactlyZero) {
  1977. *isExact = true;
  1978. return opOK;
  1979. } else
  1980. return opInexact;
  1981. }
  1982. /* Same as convertToSignExtendedInteger, except we provide
  1983. deterministic values in case of an invalid operation exception,
  1984. namely zero for NaNs and the minimal or maximal value respectively
  1985. for underflow or overflow.
  1986. The *isExact output tells whether the result is exact, in the sense
  1987. that converting it back to the original floating point type produces
  1988. the original value. This is almost equivalent to result==opOK,
  1989. except for negative zeroes.
  1990. */
  1991. IEEEFloat::opStatus
  1992. IEEEFloat::convertToInteger(MutableArrayRef<integerPart> parts,
  1993. unsigned int width, bool isSigned,
  1994. roundingMode rounding_mode, bool *isExact) const {
  1995. opStatus fs;
  1996. fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
  1997. isExact);
  1998. if (fs == opInvalidOp) {
  1999. unsigned int bits, dstPartsCount;
  2000. dstPartsCount = partCountForBits(width);
  2001. assert(dstPartsCount <= parts.size() && "Integer too big");
  2002. if (category == fcNaN)
  2003. bits = 0;
  2004. else if (sign)
  2005. bits = isSigned;
  2006. else
  2007. bits = width - isSigned;
  2008. tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
  2009. if (sign && isSigned)
  2010. APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
  2011. }
  2012. return fs;
  2013. }
  2014. /* Convert an unsigned integer SRC to a floating point number,
  2015. rounding according to ROUNDING_MODE. The sign of the floating
  2016. point number is not modified. */
  2017. IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts(
  2018. const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
  2019. unsigned int omsb, precision, dstCount;
  2020. integerPart *dst;
  2021. lostFraction lost_fraction;
  2022. category = fcNormal;
  2023. omsb = APInt::tcMSB(src, srcCount) + 1;
  2024. dst = significandParts();
  2025. dstCount = partCount();
  2026. precision = semantics->precision;
  2027. /* We want the most significant PRECISION bits of SRC. There may not
  2028. be that many; extract what we can. */
  2029. if (precision <= omsb) {
  2030. exponent = omsb - 1;
  2031. lost_fraction = lostFractionThroughTruncation(src, srcCount,
  2032. omsb - precision);
  2033. APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
  2034. } else {
  2035. exponent = precision - 1;
  2036. lost_fraction = lfExactlyZero;
  2037. APInt::tcExtract(dst, dstCount, src, omsb, 0);
  2038. }
  2039. return normalize(rounding_mode, lost_fraction);
  2040. }
  2041. IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned,
  2042. roundingMode rounding_mode) {
  2043. unsigned int partCount = Val.getNumWords();
  2044. APInt api = Val;
  2045. sign = false;
  2046. if (isSigned && api.isNegative()) {
  2047. sign = true;
  2048. api = -api;
  2049. }
  2050. return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
  2051. }
  2052. /* Convert a two's complement integer SRC to a floating point number,
  2053. rounding according to ROUNDING_MODE. ISSIGNED is true if the
  2054. integer is signed, in which case it must be sign-extended. */
  2055. IEEEFloat::opStatus
  2056. IEEEFloat::convertFromSignExtendedInteger(const integerPart *src,
  2057. unsigned int srcCount, bool isSigned,
  2058. roundingMode rounding_mode) {
  2059. opStatus status;
  2060. if (isSigned &&
  2061. APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
  2062. integerPart *copy;
  2063. /* If we're signed and negative negate a copy. */
  2064. sign = true;
  2065. copy = new integerPart[srcCount];
  2066. APInt::tcAssign(copy, src, srcCount);
  2067. APInt::tcNegate(copy, srcCount);
  2068. status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
  2069. delete [] copy;
  2070. } else {
  2071. sign = false;
  2072. status = convertFromUnsignedParts(src, srcCount, rounding_mode);
  2073. }
  2074. return status;
  2075. }
  2076. /* FIXME: should this just take a const APInt reference? */
  2077. IEEEFloat::opStatus
  2078. IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts,
  2079. unsigned int width, bool isSigned,
  2080. roundingMode rounding_mode) {
  2081. unsigned int partCount = partCountForBits(width);
  2082. APInt api = APInt(width, makeArrayRef(parts, partCount));
  2083. sign = false;
  2084. if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
  2085. sign = true;
  2086. api = -api;
  2087. }
  2088. return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
  2089. }
  2090. Expected<IEEEFloat::opStatus>
  2091. IEEEFloat::convertFromHexadecimalString(StringRef s,
  2092. roundingMode rounding_mode) {
  2093. lostFraction lost_fraction = lfExactlyZero;
  2094. category = fcNormal;
  2095. zeroSignificand();
  2096. exponent = 0;
  2097. integerPart *significand = significandParts();
  2098. unsigned partsCount = partCount();
  2099. unsigned bitPos = partsCount * integerPartWidth;
  2100. bool computedTrailingFraction = false;
  2101. // Skip leading zeroes and any (hexa)decimal point.
  2102. StringRef::iterator begin = s.begin();
  2103. StringRef::iterator end = s.end();
  2104. StringRef::iterator dot;
  2105. auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot);
  2106. if (!PtrOrErr)
  2107. return PtrOrErr.takeError();
  2108. StringRef::iterator p = *PtrOrErr;
  2109. StringRef::iterator firstSignificantDigit = p;
  2110. while (p != end) {
  2111. integerPart hex_value;
  2112. if (*p == '.') {
  2113. if (dot != end)
  2114. return createError("String contains multiple dots");
  2115. dot = p++;
  2116. continue;
  2117. }
  2118. hex_value = hexDigitValue(*p);
  2119. if (hex_value == -1U)
  2120. break;
  2121. p++;
  2122. // Store the number while we have space.
  2123. if (bitPos) {
  2124. bitPos -= 4;
  2125. hex_value <<= bitPos % integerPartWidth;
  2126. significand[bitPos / integerPartWidth] |= hex_value;
  2127. } else if (!computedTrailingFraction) {
  2128. auto FractOrErr = trailingHexadecimalFraction(p, end, hex_value);
  2129. if (!FractOrErr)
  2130. return FractOrErr.takeError();
  2131. lost_fraction = *FractOrErr;
  2132. computedTrailingFraction = true;
  2133. }
  2134. }
  2135. /* Hex floats require an exponent but not a hexadecimal point. */
  2136. if (p == end)
  2137. return createError("Hex strings require an exponent");
  2138. if (*p != 'p' && *p != 'P')
  2139. return createError("Invalid character in significand");
  2140. if (p == begin)
  2141. return createError("Significand has no digits");
  2142. if (dot != end && p - begin == 1)
  2143. return createError("Significand has no digits");
  2144. /* Ignore the exponent if we are zero. */
  2145. if (p != firstSignificantDigit) {
  2146. int expAdjustment;
  2147. /* Implicit hexadecimal point? */
  2148. if (dot == end)
  2149. dot = p;
  2150. /* Calculate the exponent adjustment implicit in the number of
  2151. significant digits. */
  2152. expAdjustment = static_cast<int>(dot - firstSignificantDigit);
  2153. if (expAdjustment < 0)
  2154. expAdjustment++;
  2155. expAdjustment = expAdjustment * 4 - 1;
  2156. /* Adjust for writing the significand starting at the most
  2157. significant nibble. */
  2158. expAdjustment += semantics->precision;
  2159. expAdjustment -= partsCount * integerPartWidth;
  2160. /* Adjust for the given exponent. */
  2161. auto ExpOrErr = totalExponent(p + 1, end, expAdjustment);
  2162. if (!ExpOrErr)
  2163. return ExpOrErr.takeError();
  2164. exponent = *ExpOrErr;
  2165. }
  2166. return normalize(rounding_mode, lost_fraction);
  2167. }
  2168. IEEEFloat::opStatus
  2169. IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
  2170. unsigned sigPartCount, int exp,
  2171. roundingMode rounding_mode) {
  2172. unsigned int parts, pow5PartCount;
  2173. fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
  2174. integerPart pow5Parts[maxPowerOfFiveParts];
  2175. bool isNearest;
  2176. isNearest = (rounding_mode == rmNearestTiesToEven ||
  2177. rounding_mode == rmNearestTiesToAway);
  2178. parts = partCountForBits(semantics->precision + 11);
  2179. /* Calculate pow(5, abs(exp)). */
  2180. pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
  2181. for (;; parts *= 2) {
  2182. opStatus sigStatus, powStatus;
  2183. unsigned int excessPrecision, truncatedBits;
  2184. calcSemantics.precision = parts * integerPartWidth - 1;
  2185. excessPrecision = calcSemantics.precision - semantics->precision;
  2186. truncatedBits = excessPrecision;
  2187. IEEEFloat decSig(calcSemantics, uninitialized);
  2188. decSig.makeZero(sign);
  2189. IEEEFloat pow5(calcSemantics);
  2190. sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
  2191. rmNearestTiesToEven);
  2192. powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
  2193. rmNearestTiesToEven);
  2194. /* Add exp, as 10^n = 5^n * 2^n. */
  2195. decSig.exponent += exp;
  2196. lostFraction calcLostFraction;
  2197. integerPart HUerr, HUdistance;
  2198. unsigned int powHUerr;
  2199. if (exp >= 0) {
  2200. /* multiplySignificand leaves the precision-th bit set to 1. */
  2201. calcLostFraction = decSig.multiplySignificand(pow5);
  2202. powHUerr = powStatus != opOK;
  2203. } else {
  2204. calcLostFraction = decSig.divideSignificand(pow5);
  2205. /* Denormal numbers have less precision. */
  2206. if (decSig.exponent < semantics->minExponent) {
  2207. excessPrecision += (semantics->minExponent - decSig.exponent);
  2208. truncatedBits = excessPrecision;
  2209. if (excessPrecision > calcSemantics.precision)
  2210. excessPrecision = calcSemantics.precision;
  2211. }
  2212. /* Extra half-ulp lost in reciprocal of exponent. */
  2213. powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
  2214. }
  2215. /* Both multiplySignificand and divideSignificand return the
  2216. result with the integer bit set. */
  2217. assert(APInt::tcExtractBit
  2218. (decSig.significandParts(), calcSemantics.precision - 1) == 1);
  2219. HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
  2220. powHUerr);
  2221. HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
  2222. excessPrecision, isNearest);
  2223. /* Are we guaranteed to round correctly if we truncate? */
  2224. if (HUdistance >= HUerr) {
  2225. APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
  2226. calcSemantics.precision - excessPrecision,
  2227. excessPrecision);
  2228. /* Take the exponent of decSig. If we tcExtract-ed less bits
  2229. above we must adjust our exponent to compensate for the
  2230. implicit right shift. */
  2231. exponent = (decSig.exponent + semantics->precision
  2232. - (calcSemantics.precision - excessPrecision));
  2233. calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
  2234. decSig.partCount(),
  2235. truncatedBits);
  2236. return normalize(rounding_mode, calcLostFraction);
  2237. }
  2238. }
  2239. }
  2240. Expected<IEEEFloat::opStatus>
  2241. IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
  2242. decimalInfo D;
  2243. opStatus fs;
  2244. /* Scan the text. */
  2245. StringRef::iterator p = str.begin();
  2246. if (Error Err = interpretDecimal(p, str.end(), &D))
  2247. return std::move(Err);
  2248. /* Handle the quick cases. First the case of no significant digits,
  2249. i.e. zero, and then exponents that are obviously too large or too
  2250. small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
  2251. definitely overflows if
  2252. (exp - 1) * L >= maxExponent
  2253. and definitely underflows to zero where
  2254. (exp + 1) * L <= minExponent - precision
  2255. With integer arithmetic the tightest bounds for L are
  2256. 93/28 < L < 196/59 [ numerator <= 256 ]
  2257. 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
  2258. */
  2259. // Test if we have a zero number allowing for strings with no null terminators
  2260. // and zero decimals with non-zero exponents.
  2261. //
  2262. // We computed firstSigDigit by ignoring all zeros and dots. Thus if
  2263. // D->firstSigDigit equals str.end(), every digit must be a zero and there can
  2264. // be at most one dot. On the other hand, if we have a zero with a non-zero
  2265. // exponent, then we know that D.firstSigDigit will be non-numeric.
  2266. if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
  2267. category = fcZero;
  2268. fs = opOK;
  2269. /* Check whether the normalized exponent is high enough to overflow
  2270. max during the log-rebasing in the max-exponent check below. */
  2271. } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
  2272. fs = handleOverflow(rounding_mode);
  2273. /* If it wasn't, then it also wasn't high enough to overflow max
  2274. during the log-rebasing in the min-exponent check. Check that it
  2275. won't overflow min in either check, then perform the min-exponent
  2276. check. */
  2277. } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
  2278. (D.normalizedExponent + 1) * 28738 <=
  2279. 8651 * (semantics->minExponent - (int) semantics->precision)) {
  2280. /* Underflow to zero and round. */
  2281. category = fcNormal;
  2282. zeroSignificand();
  2283. fs = normalize(rounding_mode, lfLessThanHalf);
  2284. /* We can finally safely perform the max-exponent check. */
  2285. } else if ((D.normalizedExponent - 1) * 42039
  2286. >= 12655 * semantics->maxExponent) {
  2287. /* Overflow and round. */
  2288. fs = handleOverflow(rounding_mode);
  2289. } else {
  2290. integerPart *decSignificand;
  2291. unsigned int partCount;
  2292. /* A tight upper bound on number of bits required to hold an
  2293. N-digit decimal integer is N * 196 / 59. Allocate enough space
  2294. to hold the full significand, and an extra part required by
  2295. tcMultiplyPart. */
  2296. partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
  2297. partCount = partCountForBits(1 + 196 * partCount / 59);
  2298. decSignificand = new integerPart[partCount + 1];
  2299. partCount = 0;
  2300. /* Convert to binary efficiently - we do almost all multiplication
  2301. in an integerPart. When this would overflow do we do a single
  2302. bignum multiplication, and then revert again to multiplication
  2303. in an integerPart. */
  2304. do {
  2305. integerPart decValue, val, multiplier;
  2306. val = 0;
  2307. multiplier = 1;
  2308. do {
  2309. if (*p == '.') {
  2310. p++;
  2311. if (p == str.end()) {
  2312. break;
  2313. }
  2314. }
  2315. decValue = decDigitValue(*p++);
  2316. if (decValue >= 10U) {
  2317. delete[] decSignificand;
  2318. return createError("Invalid character in significand");
  2319. }
  2320. multiplier *= 10;
  2321. val = val * 10 + decValue;
  2322. /* The maximum number that can be multiplied by ten with any
  2323. digit added without overflowing an integerPart. */
  2324. } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
  2325. /* Multiply out the current part. */
  2326. APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
  2327. partCount, partCount + 1, false);
  2328. /* If we used another part (likely but not guaranteed), increase
  2329. the count. */
  2330. if (decSignificand[partCount])
  2331. partCount++;
  2332. } while (p <= D.lastSigDigit);
  2333. category = fcNormal;
  2334. fs = roundSignificandWithExponent(decSignificand, partCount,
  2335. D.exponent, rounding_mode);
  2336. delete [] decSignificand;
  2337. }
  2338. return fs;
  2339. }
  2340. bool IEEEFloat::convertFromStringSpecials(StringRef str) {
  2341. const size_t MIN_NAME_SIZE = 3;
  2342. if (str.size() < MIN_NAME_SIZE)
  2343. return false;
  2344. if (str.equals("inf") || str.equals("INFINITY") || str.equals("+Inf")) {
  2345. makeInf(false);
  2346. return true;
  2347. }
  2348. bool IsNegative = str.front() == '-';
  2349. if (IsNegative) {
  2350. str = str.drop_front();
  2351. if (str.size() < MIN_NAME_SIZE)
  2352. return false;
  2353. if (str.equals("inf") || str.equals("INFINITY") || str.equals("Inf")) {
  2354. makeInf(true);
  2355. return true;
  2356. }
  2357. }
  2358. // If we have a 's' (or 'S') prefix, then this is a Signaling NaN.
  2359. bool IsSignaling = str.front() == 's' || str.front() == 'S';
  2360. if (IsSignaling) {
  2361. str = str.drop_front();
  2362. if (str.size() < MIN_NAME_SIZE)
  2363. return false;
  2364. }
  2365. if (str.startswith("nan") || str.startswith("NaN")) {
  2366. str = str.drop_front(3);
  2367. // A NaN without payload.
  2368. if (str.empty()) {
  2369. makeNaN(IsSignaling, IsNegative);
  2370. return true;
  2371. }
  2372. // Allow the payload to be inside parentheses.
  2373. if (str.front() == '(') {
  2374. // Parentheses should be balanced (and not empty).
  2375. if (str.size() <= 2 || str.back() != ')')
  2376. return false;
  2377. str = str.slice(1, str.size() - 1);
  2378. }
  2379. // Determine the payload number's radix.
  2380. unsigned Radix = 10;
  2381. if (str[0] == '0') {
  2382. if (str.size() > 1 && tolower(str[1]) == 'x') {
  2383. str = str.drop_front(2);
  2384. Radix = 16;
  2385. } else
  2386. Radix = 8;
  2387. }
  2388. // Parse the payload and make the NaN.
  2389. APInt Payload;
  2390. if (!str.getAsInteger(Radix, Payload)) {
  2391. makeNaN(IsSignaling, IsNegative, &Payload);
  2392. return true;
  2393. }
  2394. }
  2395. return false;
  2396. }
  2397. Expected<IEEEFloat::opStatus>
  2398. IEEEFloat::convertFromString(StringRef str, roundingMode rounding_mode) {
  2399. if (str.empty())
  2400. return createError("Invalid string length");
  2401. // Handle special cases.
  2402. if (convertFromStringSpecials(str))
  2403. return opOK;
  2404. /* Handle a leading minus sign. */
  2405. StringRef::iterator p = str.begin();
  2406. size_t slen = str.size();
  2407. sign = *p == '-' ? 1 : 0;
  2408. if (*p == '-' || *p == '+') {
  2409. p++;
  2410. slen--;
  2411. if (!slen)
  2412. return createError("String has no digits");
  2413. }
  2414. if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
  2415. if (slen == 2)
  2416. return createError("Invalid string");
  2417. return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
  2418. rounding_mode);
  2419. }
  2420. return convertFromDecimalString(StringRef(p, slen), rounding_mode);
  2421. }
  2422. /* Write out a hexadecimal representation of the floating point value
  2423. to DST, which must be of sufficient size, in the C99 form
  2424. [-]0xh.hhhhp[+-]d. Return the number of characters written,
  2425. excluding the terminating NUL.
  2426. If UPPERCASE, the output is in upper case, otherwise in lower case.
  2427. HEXDIGITS digits appear altogether, rounding the value if
  2428. necessary. If HEXDIGITS is 0, the minimal precision to display the
  2429. number precisely is used instead. If nothing would appear after
  2430. the decimal point it is suppressed.
  2431. The decimal exponent is always printed and has at least one digit.
  2432. Zero values display an exponent of zero. Infinities and NaNs
  2433. appear as "infinity" or "nan" respectively.
  2434. The above rules are as specified by C99. There is ambiguity about
  2435. what the leading hexadecimal digit should be. This implementation
  2436. uses whatever is necessary so that the exponent is displayed as
  2437. stored. This implies the exponent will fall within the IEEE format
  2438. range, and the leading hexadecimal digit will be 0 (for denormals),
  2439. 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
  2440. any other digits zero).
  2441. */
  2442. unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
  2443. bool upperCase,
  2444. roundingMode rounding_mode) const {
  2445. char *p;
  2446. p = dst;
  2447. if (sign)
  2448. *dst++ = '-';
  2449. switch (category) {
  2450. case fcInfinity:
  2451. memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
  2452. dst += sizeof infinityL - 1;
  2453. break;
  2454. case fcNaN:
  2455. memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
  2456. dst += sizeof NaNU - 1;
  2457. break;
  2458. case fcZero:
  2459. *dst++ = '0';
  2460. *dst++ = upperCase ? 'X': 'x';
  2461. *dst++ = '0';
  2462. if (hexDigits > 1) {
  2463. *dst++ = '.';
  2464. memset (dst, '0', hexDigits - 1);
  2465. dst += hexDigits - 1;
  2466. }
  2467. *dst++ = upperCase ? 'P': 'p';
  2468. *dst++ = '0';
  2469. break;
  2470. case fcNormal:
  2471. dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
  2472. break;
  2473. }
  2474. *dst = 0;
  2475. return static_cast<unsigned int>(dst - p);
  2476. }
  2477. /* Does the hard work of outputting the correctly rounded hexadecimal
  2478. form of a normal floating point number with the specified number of
  2479. hexadecimal digits. If HEXDIGITS is zero the minimum number of
  2480. digits necessary to print the value precisely is output. */
  2481. char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
  2482. bool upperCase,
  2483. roundingMode rounding_mode) const {
  2484. unsigned int count, valueBits, shift, partsCount, outputDigits;
  2485. const char *hexDigitChars;
  2486. const integerPart *significand;
  2487. char *p;
  2488. bool roundUp;
  2489. *dst++ = '0';
  2490. *dst++ = upperCase ? 'X': 'x';
  2491. roundUp = false;
  2492. hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
  2493. significand = significandParts();
  2494. partsCount = partCount();
  2495. /* +3 because the first digit only uses the single integer bit, so
  2496. we have 3 virtual zero most-significant-bits. */
  2497. valueBits = semantics->precision + 3;
  2498. shift = integerPartWidth - valueBits % integerPartWidth;
  2499. /* The natural number of digits required ignoring trailing
  2500. insignificant zeroes. */
  2501. outputDigits = (valueBits - significandLSB () + 3) / 4;
  2502. /* hexDigits of zero means use the required number for the
  2503. precision. Otherwise, see if we are truncating. If we are,
  2504. find out if we need to round away from zero. */
  2505. if (hexDigits) {
  2506. if (hexDigits < outputDigits) {
  2507. /* We are dropping non-zero bits, so need to check how to round.
  2508. "bits" is the number of dropped bits. */
  2509. unsigned int bits;
  2510. lostFraction fraction;
  2511. bits = valueBits - hexDigits * 4;
  2512. fraction = lostFractionThroughTruncation (significand, partsCount, bits);
  2513. roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
  2514. }
  2515. outputDigits = hexDigits;
  2516. }
  2517. /* Write the digits consecutively, and start writing in the location
  2518. of the hexadecimal point. We move the most significant digit
  2519. left and add the hexadecimal point later. */
  2520. p = ++dst;
  2521. count = (valueBits + integerPartWidth - 1) / integerPartWidth;
  2522. while (outputDigits && count) {
  2523. integerPart part;
  2524. /* Put the most significant integerPartWidth bits in "part". */
  2525. if (--count == partsCount)
  2526. part = 0; /* An imaginary higher zero part. */
  2527. else
  2528. part = significand[count] << shift;
  2529. if (count && shift)
  2530. part |= significand[count - 1] >> (integerPartWidth - shift);
  2531. /* Convert as much of "part" to hexdigits as we can. */
  2532. unsigned int curDigits = integerPartWidth / 4;
  2533. if (curDigits > outputDigits)
  2534. curDigits = outputDigits;
  2535. dst += partAsHex (dst, part, curDigits, hexDigitChars);
  2536. outputDigits -= curDigits;
  2537. }
  2538. if (roundUp) {
  2539. char *q = dst;
  2540. /* Note that hexDigitChars has a trailing '0'. */
  2541. do {
  2542. q--;
  2543. *q = hexDigitChars[hexDigitValue (*q) + 1];
  2544. } while (*q == '0');
  2545. assert(q >= p);
  2546. } else {
  2547. /* Add trailing zeroes. */
  2548. memset (dst, '0', outputDigits);
  2549. dst += outputDigits;
  2550. }
  2551. /* Move the most significant digit to before the point, and if there
  2552. is something after the decimal point add it. This must come
  2553. after rounding above. */
  2554. p[-1] = p[0];
  2555. if (dst -1 == p)
  2556. dst--;
  2557. else
  2558. p[0] = '.';
  2559. /* Finally output the exponent. */
  2560. *dst++ = upperCase ? 'P': 'p';
  2561. return writeSignedDecimal (dst, exponent);
  2562. }
  2563. hash_code hash_value(const IEEEFloat &Arg) {
  2564. if (!Arg.isFiniteNonZero())
  2565. return hash_combine((uint8_t)Arg.category,
  2566. // NaN has no sign, fix it at zero.
  2567. Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
  2568. Arg.semantics->precision);
  2569. // Normal floats need their exponent and significand hashed.
  2570. return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
  2571. Arg.semantics->precision, Arg.exponent,
  2572. hash_combine_range(
  2573. Arg.significandParts(),
  2574. Arg.significandParts() + Arg.partCount()));
  2575. }
  2576. // Conversion from APFloat to/from host float/double. It may eventually be
  2577. // possible to eliminate these and have everybody deal with APFloats, but that
  2578. // will take a while. This approach will not easily extend to long double.
  2579. // Current implementation requires integerPartWidth==64, which is correct at
  2580. // the moment but could be made more general.
  2581. // Denormals have exponent minExponent in APFloat, but minExponent-1 in
  2582. // the actual IEEE respresentations. We compensate for that here.
  2583. APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
  2584. assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended);
  2585. assert(partCount()==2);
  2586. uint64_t myexponent, mysignificand;
  2587. if (isFiniteNonZero()) {
  2588. myexponent = exponent+16383; //bias
  2589. mysignificand = significandParts()[0];
  2590. if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
  2591. myexponent = 0; // denormal
  2592. } else if (category==fcZero) {
  2593. myexponent = 0;
  2594. mysignificand = 0;
  2595. } else if (category==fcInfinity) {
  2596. myexponent = 0x7fff;
  2597. mysignificand = 0x8000000000000000ULL;
  2598. } else {
  2599. assert(category == fcNaN && "Unknown category");
  2600. myexponent = 0x7fff;
  2601. mysignificand = significandParts()[0];
  2602. }
  2603. uint64_t words[2];
  2604. words[0] = mysignificand;
  2605. words[1] = ((uint64_t)(sign & 1) << 15) |
  2606. (myexponent & 0x7fffLL);
  2607. return APInt(80, words);
  2608. }
  2609. APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const {
  2610. assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy);
  2611. assert(partCount()==2);
  2612. uint64_t words[2];
  2613. opStatus fs;
  2614. bool losesInfo;
  2615. // Convert number to double. To avoid spurious underflows, we re-
  2616. // normalize against the "double" minExponent first, and only *then*
  2617. // truncate the mantissa. The result of that second conversion
  2618. // may be inexact, but should never underflow.
  2619. // Declare fltSemantics before APFloat that uses it (and
  2620. // saves pointer to it) to ensure correct destruction order.
  2621. fltSemantics extendedSemantics = *semantics;
  2622. extendedSemantics.minExponent = semIEEEdouble.minExponent;
  2623. IEEEFloat extended(*this);
  2624. fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
  2625. assert(fs == opOK && !losesInfo);
  2626. (void)fs;
  2627. IEEEFloat u(extended);
  2628. fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
  2629. assert(fs == opOK || fs == opInexact);
  2630. (void)fs;
  2631. words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
  2632. // If conversion was exact or resulted in a special case, we're done;
  2633. // just set the second double to zero. Otherwise, re-convert back to
  2634. // the extended format and compute the difference. This now should
  2635. // convert exactly to double.
  2636. if (u.isFiniteNonZero() && losesInfo) {
  2637. fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
  2638. assert(fs == opOK && !losesInfo);
  2639. (void)fs;
  2640. IEEEFloat v(extended);
  2641. v.subtract(u, rmNearestTiesToEven);
  2642. fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
  2643. assert(fs == opOK && !losesInfo);
  2644. (void)fs;
  2645. words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
  2646. } else {
  2647. words[1] = 0;
  2648. }
  2649. return APInt(128, words);
  2650. }
  2651. APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
  2652. assert(semantics == (const llvm::fltSemantics*)&semIEEEquad);
  2653. assert(partCount()==2);
  2654. uint64_t myexponent, mysignificand, mysignificand2;
  2655. if (isFiniteNonZero()) {
  2656. myexponent = exponent+16383; //bias
  2657. mysignificand = significandParts()[0];
  2658. mysignificand2 = significandParts()[1];
  2659. if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
  2660. myexponent = 0; // denormal
  2661. } else if (category==fcZero) {
  2662. myexponent = 0;
  2663. mysignificand = mysignificand2 = 0;
  2664. } else if (category==fcInfinity) {
  2665. myexponent = 0x7fff;
  2666. mysignificand = mysignificand2 = 0;
  2667. } else {
  2668. assert(category == fcNaN && "Unknown category!");
  2669. myexponent = 0x7fff;
  2670. mysignificand = significandParts()[0];
  2671. mysignificand2 = significandParts()[1];
  2672. }
  2673. uint64_t words[2];
  2674. words[0] = mysignificand;
  2675. words[1] = ((uint64_t)(sign & 1) << 63) |
  2676. ((myexponent & 0x7fff) << 48) |
  2677. (mysignificand2 & 0xffffffffffffLL);
  2678. return APInt(128, words);
  2679. }
  2680. APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
  2681. assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble);
  2682. assert(partCount()==1);
  2683. uint64_t myexponent, mysignificand;
  2684. if (isFiniteNonZero()) {
  2685. myexponent = exponent+1023; //bias
  2686. mysignificand = *significandParts();
  2687. if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
  2688. myexponent = 0; // denormal
  2689. } else if (category==fcZero) {
  2690. myexponent = 0;
  2691. mysignificand = 0;
  2692. } else if (category==fcInfinity) {
  2693. myexponent = 0x7ff;
  2694. mysignificand = 0;
  2695. } else {
  2696. assert(category == fcNaN && "Unknown category!");
  2697. myexponent = 0x7ff;
  2698. mysignificand = *significandParts();
  2699. }
  2700. return APInt(64, ((((uint64_t)(sign & 1) << 63) |
  2701. ((myexponent & 0x7ff) << 52) |
  2702. (mysignificand & 0xfffffffffffffLL))));
  2703. }
  2704. APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
  2705. assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle);
  2706. assert(partCount()==1);
  2707. uint32_t myexponent, mysignificand;
  2708. if (isFiniteNonZero()) {
  2709. myexponent = exponent+127; //bias
  2710. mysignificand = (uint32_t)*significandParts();
  2711. if (myexponent == 1 && !(mysignificand & 0x800000))
  2712. myexponent = 0; // denormal
  2713. } else if (category==fcZero) {
  2714. myexponent = 0;
  2715. mysignificand = 0;
  2716. } else if (category==fcInfinity) {
  2717. myexponent = 0xff;
  2718. mysignificand = 0;
  2719. } else {
  2720. assert(category == fcNaN && "Unknown category!");
  2721. myexponent = 0xff;
  2722. mysignificand = (uint32_t)*significandParts();
  2723. }
  2724. return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
  2725. (mysignificand & 0x7fffff)));
  2726. }
  2727. APInt IEEEFloat::convertBFloatAPFloatToAPInt() const {
  2728. assert(semantics == (const llvm::fltSemantics *)&semBFloat);
  2729. assert(partCount() == 1);
  2730. uint32_t myexponent, mysignificand;
  2731. if (isFiniteNonZero()) {
  2732. myexponent = exponent + 127; // bias
  2733. mysignificand = (uint32_t)*significandParts();
  2734. if (myexponent == 1 && !(mysignificand & 0x80))
  2735. myexponent = 0; // denormal
  2736. } else if (category == fcZero) {
  2737. myexponent = 0;
  2738. mysignificand = 0;
  2739. } else if (category == fcInfinity) {
  2740. myexponent = 0xff;
  2741. mysignificand = 0;
  2742. } else {
  2743. assert(category == fcNaN && "Unknown category!");
  2744. myexponent = 0xff;
  2745. mysignificand = (uint32_t)*significandParts();
  2746. }
  2747. return APInt(16, (((sign & 1) << 15) | ((myexponent & 0xff) << 7) |
  2748. (mysignificand & 0x7f)));
  2749. }
  2750. APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
  2751. assert(semantics == (const llvm::fltSemantics*)&semIEEEhalf);
  2752. assert(partCount()==1);
  2753. uint32_t myexponent, mysignificand;
  2754. if (isFiniteNonZero()) {
  2755. myexponent = exponent+15; //bias
  2756. mysignificand = (uint32_t)*significandParts();
  2757. if (myexponent == 1 && !(mysignificand & 0x400))
  2758. myexponent = 0; // denormal
  2759. } else if (category==fcZero) {
  2760. myexponent = 0;
  2761. mysignificand = 0;
  2762. } else if (category==fcInfinity) {
  2763. myexponent = 0x1f;
  2764. mysignificand = 0;
  2765. } else {
  2766. assert(category == fcNaN && "Unknown category!");
  2767. myexponent = 0x1f;
  2768. mysignificand = (uint32_t)*significandParts();
  2769. }
  2770. return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
  2771. (mysignificand & 0x3ff)));
  2772. }
  2773. // This function creates an APInt that is just a bit map of the floating
  2774. // point constant as it would appear in memory. It is not a conversion,
  2775. // and treating the result as a normal integer is unlikely to be useful.
  2776. APInt IEEEFloat::bitcastToAPInt() const {
  2777. if (semantics == (const llvm::fltSemantics*)&semIEEEhalf)
  2778. return convertHalfAPFloatToAPInt();
  2779. if (semantics == (const llvm::fltSemantics *)&semBFloat)
  2780. return convertBFloatAPFloatToAPInt();
  2781. if (semantics == (const llvm::fltSemantics*)&semIEEEsingle)
  2782. return convertFloatAPFloatToAPInt();
  2783. if (semantics == (const llvm::fltSemantics*)&semIEEEdouble)
  2784. return convertDoubleAPFloatToAPInt();
  2785. if (semantics == (const llvm::fltSemantics*)&semIEEEquad)
  2786. return convertQuadrupleAPFloatToAPInt();
  2787. if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy)
  2788. return convertPPCDoubleDoubleAPFloatToAPInt();
  2789. assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended &&
  2790. "unknown format!");
  2791. return convertF80LongDoubleAPFloatToAPInt();
  2792. }
  2793. float IEEEFloat::convertToFloat() const {
  2794. assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle &&
  2795. "Float semantics are not IEEEsingle");
  2796. APInt api = bitcastToAPInt();
  2797. return api.bitsToFloat();
  2798. }
  2799. double IEEEFloat::convertToDouble() const {
  2800. assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble &&
  2801. "Float semantics are not IEEEdouble");
  2802. APInt api = bitcastToAPInt();
  2803. return api.bitsToDouble();
  2804. }
  2805. /// Integer bit is explicit in this format. Intel hardware (387 and later)
  2806. /// does not support these bit patterns:
  2807. /// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
  2808. /// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
  2809. /// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
  2810. /// exponent = 0, integer bit 1 ("pseudodenormal")
  2811. /// At the moment, the first three are treated as NaNs, the last one as Normal.
  2812. void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
  2813. uint64_t i1 = api.getRawData()[0];
  2814. uint64_t i2 = api.getRawData()[1];
  2815. uint64_t myexponent = (i2 & 0x7fff);
  2816. uint64_t mysignificand = i1;
  2817. uint8_t myintegerbit = mysignificand >> 63;
  2818. initialize(&semX87DoubleExtended);
  2819. assert(partCount()==2);
  2820. sign = static_cast<unsigned int>(i2>>15);
  2821. if (myexponent == 0 && mysignificand == 0) {
  2822. makeZero(sign);
  2823. } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
  2824. makeInf(sign);
  2825. } else if ((myexponent == 0x7fff && mysignificand != 0x8000000000000000ULL) ||
  2826. (myexponent != 0x7fff && myexponent != 0 && myintegerbit == 0)) {
  2827. category = fcNaN;
  2828. exponent = exponentNaN();
  2829. significandParts()[0] = mysignificand;
  2830. significandParts()[1] = 0;
  2831. } else {
  2832. category = fcNormal;
  2833. exponent = myexponent - 16383;
  2834. significandParts()[0] = mysignificand;
  2835. significandParts()[1] = 0;
  2836. if (myexponent==0) // denormal
  2837. exponent = -16382;
  2838. }
  2839. }
  2840. void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) {
  2841. uint64_t i1 = api.getRawData()[0];
  2842. uint64_t i2 = api.getRawData()[1];
  2843. opStatus fs;
  2844. bool losesInfo;
  2845. // Get the first double and convert to our format.
  2846. initFromDoubleAPInt(APInt(64, i1));
  2847. fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
  2848. assert(fs == opOK && !losesInfo);
  2849. (void)fs;
  2850. // Unless we have a special case, add in second double.
  2851. if (isFiniteNonZero()) {
  2852. IEEEFloat v(semIEEEdouble, APInt(64, i2));
  2853. fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
  2854. assert(fs == opOK && !losesInfo);
  2855. (void)fs;
  2856. add(v, rmNearestTiesToEven);
  2857. }
  2858. }
  2859. void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
  2860. uint64_t i1 = api.getRawData()[0];
  2861. uint64_t i2 = api.getRawData()[1];
  2862. uint64_t myexponent = (i2 >> 48) & 0x7fff;
  2863. uint64_t mysignificand = i1;
  2864. uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
  2865. initialize(&semIEEEquad);
  2866. assert(partCount()==2);
  2867. sign = static_cast<unsigned int>(i2>>63);
  2868. if (myexponent==0 &&
  2869. (mysignificand==0 && mysignificand2==0)) {
  2870. makeZero(sign);
  2871. } else if (myexponent==0x7fff &&
  2872. (mysignificand==0 && mysignificand2==0)) {
  2873. makeInf(sign);
  2874. } else if (myexponent==0x7fff &&
  2875. (mysignificand!=0 || mysignificand2 !=0)) {
  2876. category = fcNaN;
  2877. exponent = exponentNaN();
  2878. significandParts()[0] = mysignificand;
  2879. significandParts()[1] = mysignificand2;
  2880. } else {
  2881. category = fcNormal;
  2882. exponent = myexponent - 16383;
  2883. significandParts()[0] = mysignificand;
  2884. significandParts()[1] = mysignificand2;
  2885. if (myexponent==0) // denormal
  2886. exponent = -16382;
  2887. else
  2888. significandParts()[1] |= 0x1000000000000LL; // integer bit
  2889. }
  2890. }
  2891. void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
  2892. uint64_t i = *api.getRawData();
  2893. uint64_t myexponent = (i >> 52) & 0x7ff;
  2894. uint64_t mysignificand = i & 0xfffffffffffffLL;
  2895. initialize(&semIEEEdouble);
  2896. assert(partCount()==1);
  2897. sign = static_cast<unsigned int>(i>>63);
  2898. if (myexponent==0 && mysignificand==0) {
  2899. makeZero(sign);
  2900. } else if (myexponent==0x7ff && mysignificand==0) {
  2901. makeInf(sign);
  2902. } else if (myexponent==0x7ff && mysignificand!=0) {
  2903. category = fcNaN;
  2904. exponent = exponentNaN();
  2905. *significandParts() = mysignificand;
  2906. } else {
  2907. category = fcNormal;
  2908. exponent = myexponent - 1023;
  2909. *significandParts() = mysignificand;
  2910. if (myexponent==0) // denormal
  2911. exponent = -1022;
  2912. else
  2913. *significandParts() |= 0x10000000000000LL; // integer bit
  2914. }
  2915. }
  2916. void IEEEFloat::initFromFloatAPInt(const APInt &api) {
  2917. uint32_t i = (uint32_t)*api.getRawData();
  2918. uint32_t myexponent = (i >> 23) & 0xff;
  2919. uint32_t mysignificand = i & 0x7fffff;
  2920. initialize(&semIEEEsingle);
  2921. assert(partCount()==1);
  2922. sign = i >> 31;
  2923. if (myexponent==0 && mysignificand==0) {
  2924. makeZero(sign);
  2925. } else if (myexponent==0xff && mysignificand==0) {
  2926. makeInf(sign);
  2927. } else if (myexponent==0xff && mysignificand!=0) {
  2928. category = fcNaN;
  2929. exponent = exponentNaN();
  2930. *significandParts() = mysignificand;
  2931. } else {
  2932. category = fcNormal;
  2933. exponent = myexponent - 127; //bias
  2934. *significandParts() = mysignificand;
  2935. if (myexponent==0) // denormal
  2936. exponent = -126;
  2937. else
  2938. *significandParts() |= 0x800000; // integer bit
  2939. }
  2940. }
  2941. void IEEEFloat::initFromBFloatAPInt(const APInt &api) {
  2942. uint32_t i = (uint32_t)*api.getRawData();
  2943. uint32_t myexponent = (i >> 7) & 0xff;
  2944. uint32_t mysignificand = i & 0x7f;
  2945. initialize(&semBFloat);
  2946. assert(partCount() == 1);
  2947. sign = i >> 15;
  2948. if (myexponent == 0 && mysignificand == 0) {
  2949. makeZero(sign);
  2950. } else if (myexponent == 0xff && mysignificand == 0) {
  2951. makeInf(sign);
  2952. } else if (myexponent == 0xff && mysignificand != 0) {
  2953. category = fcNaN;
  2954. exponent = exponentNaN();
  2955. *significandParts() = mysignificand;
  2956. } else {
  2957. category = fcNormal;
  2958. exponent = myexponent - 127; // bias
  2959. *significandParts() = mysignificand;
  2960. if (myexponent == 0) // denormal
  2961. exponent = -126;
  2962. else
  2963. *significandParts() |= 0x80; // integer bit
  2964. }
  2965. }
  2966. void IEEEFloat::initFromHalfAPInt(const APInt &api) {
  2967. uint32_t i = (uint32_t)*api.getRawData();
  2968. uint32_t myexponent = (i >> 10) & 0x1f;
  2969. uint32_t mysignificand = i & 0x3ff;
  2970. initialize(&semIEEEhalf);
  2971. assert(partCount()==1);
  2972. sign = i >> 15;
  2973. if (myexponent==0 && mysignificand==0) {
  2974. makeZero(sign);
  2975. } else if (myexponent==0x1f && mysignificand==0) {
  2976. makeInf(sign);
  2977. } else if (myexponent==0x1f && mysignificand!=0) {
  2978. category = fcNaN;
  2979. exponent = exponentNaN();
  2980. *significandParts() = mysignificand;
  2981. } else {
  2982. category = fcNormal;
  2983. exponent = myexponent - 15; //bias
  2984. *significandParts() = mysignificand;
  2985. if (myexponent==0) // denormal
  2986. exponent = -14;
  2987. else
  2988. *significandParts() |= 0x400; // integer bit
  2989. }
  2990. }
  2991. /// Treat api as containing the bits of a floating point number. Currently
  2992. /// we infer the floating point type from the size of the APInt. The
  2993. /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
  2994. /// when the size is anything else).
  2995. void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
  2996. assert(api.getBitWidth() == Sem->sizeInBits);
  2997. if (Sem == &semIEEEhalf)
  2998. return initFromHalfAPInt(api);
  2999. if (Sem == &semBFloat)
  3000. return initFromBFloatAPInt(api);
  3001. if (Sem == &semIEEEsingle)
  3002. return initFromFloatAPInt(api);
  3003. if (Sem == &semIEEEdouble)
  3004. return initFromDoubleAPInt(api);
  3005. if (Sem == &semX87DoubleExtended)
  3006. return initFromF80LongDoubleAPInt(api);
  3007. if (Sem == &semIEEEquad)
  3008. return initFromQuadrupleAPInt(api);
  3009. if (Sem == &semPPCDoubleDoubleLegacy)
  3010. return initFromPPCDoubleDoubleAPInt(api);
  3011. llvm_unreachable(nullptr);
  3012. }
  3013. /// Make this number the largest magnitude normal number in the given
  3014. /// semantics.
  3015. void IEEEFloat::makeLargest(bool Negative) {
  3016. // We want (in interchange format):
  3017. // sign = {Negative}
  3018. // exponent = 1..10
  3019. // significand = 1..1
  3020. category = fcNormal;
  3021. sign = Negative;
  3022. exponent = semantics->maxExponent;
  3023. // Use memset to set all but the highest integerPart to all ones.
  3024. integerPart *significand = significandParts();
  3025. unsigned PartCount = partCount();
  3026. memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
  3027. // Set the high integerPart especially setting all unused top bits for
  3028. // internal consistency.
  3029. const unsigned NumUnusedHighBits =
  3030. PartCount*integerPartWidth - semantics->precision;
  3031. significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
  3032. ? (~integerPart(0) >> NumUnusedHighBits)
  3033. : 0;
  3034. }
  3035. /// Make this number the smallest magnitude denormal number in the given
  3036. /// semantics.
  3037. void IEEEFloat::makeSmallest(bool Negative) {
  3038. // We want (in interchange format):
  3039. // sign = {Negative}
  3040. // exponent = 0..0
  3041. // significand = 0..01
  3042. category = fcNormal;
  3043. sign = Negative;
  3044. exponent = semantics->minExponent;
  3045. APInt::tcSet(significandParts(), 1, partCount());
  3046. }
  3047. void IEEEFloat::makeSmallestNormalized(bool Negative) {
  3048. // We want (in interchange format):
  3049. // sign = {Negative}
  3050. // exponent = 0..0
  3051. // significand = 10..0
  3052. category = fcNormal;
  3053. zeroSignificand();
  3054. sign = Negative;
  3055. exponent = semantics->minExponent;
  3056. significandParts()[partCountForBits(semantics->precision) - 1] |=
  3057. (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth));
  3058. }
  3059. IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
  3060. initFromAPInt(&Sem, API);
  3061. }
  3062. IEEEFloat::IEEEFloat(float f) {
  3063. initFromAPInt(&semIEEEsingle, APInt::floatToBits(f));
  3064. }
  3065. IEEEFloat::IEEEFloat(double d) {
  3066. initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d));
  3067. }
  3068. namespace {
  3069. void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
  3070. Buffer.append(Str.begin(), Str.end());
  3071. }
  3072. /// Removes data from the given significand until it is no more
  3073. /// precise than is required for the desired precision.
  3074. void AdjustToPrecision(APInt &significand,
  3075. int &exp, unsigned FormatPrecision) {
  3076. unsigned bits = significand.getActiveBits();
  3077. // 196/59 is a very slight overestimate of lg_2(10).
  3078. unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
  3079. if (bits <= bitsRequired) return;
  3080. unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
  3081. if (!tensRemovable) return;
  3082. exp += tensRemovable;
  3083. APInt divisor(significand.getBitWidth(), 1);
  3084. APInt powten(significand.getBitWidth(), 10);
  3085. while (true) {
  3086. if (tensRemovable & 1)
  3087. divisor *= powten;
  3088. tensRemovable >>= 1;
  3089. if (!tensRemovable) break;
  3090. powten *= powten;
  3091. }
  3092. significand = significand.udiv(divisor);
  3093. // Truncate the significand down to its active bit count.
  3094. significand = significand.trunc(significand.getActiveBits());
  3095. }
  3096. void AdjustToPrecision(SmallVectorImpl<char> &buffer,
  3097. int &exp, unsigned FormatPrecision) {
  3098. unsigned N = buffer.size();
  3099. if (N <= FormatPrecision) return;
  3100. // The most significant figures are the last ones in the buffer.
  3101. unsigned FirstSignificant = N - FormatPrecision;
  3102. // Round.
  3103. // FIXME: this probably shouldn't use 'round half up'.
  3104. // Rounding down is just a truncation, except we also want to drop
  3105. // trailing zeros from the new result.
  3106. if (buffer[FirstSignificant - 1] < '5') {
  3107. while (FirstSignificant < N && buffer[FirstSignificant] == '0')
  3108. FirstSignificant++;
  3109. exp += FirstSignificant;
  3110. buffer.erase(&buffer[0], &buffer[FirstSignificant]);
  3111. return;
  3112. }
  3113. // Rounding up requires a decimal add-with-carry. If we continue
  3114. // the carry, the newly-introduced zeros will just be truncated.
  3115. for (unsigned I = FirstSignificant; I != N; ++I) {
  3116. if (buffer[I] == '9') {
  3117. FirstSignificant++;
  3118. } else {
  3119. buffer[I]++;
  3120. break;
  3121. }
  3122. }
  3123. // If we carried through, we have exactly one digit of precision.
  3124. if (FirstSignificant == N) {
  3125. exp += FirstSignificant;
  3126. buffer.clear();
  3127. buffer.push_back('1');
  3128. return;
  3129. }
  3130. exp += FirstSignificant;
  3131. buffer.erase(&buffer[0], &buffer[FirstSignificant]);
  3132. }
  3133. } // namespace
  3134. void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
  3135. unsigned FormatMaxPadding, bool TruncateZero) const {
  3136. switch (category) {
  3137. case fcInfinity:
  3138. if (isNegative())
  3139. return append(Str, "-Inf");
  3140. else
  3141. return append(Str, "+Inf");
  3142. case fcNaN: return append(Str, "NaN");
  3143. case fcZero:
  3144. if (isNegative())
  3145. Str.push_back('-');
  3146. if (!FormatMaxPadding) {
  3147. if (TruncateZero)
  3148. append(Str, "0.0E+0");
  3149. else {
  3150. append(Str, "0.0");
  3151. if (FormatPrecision > 1)
  3152. Str.append(FormatPrecision - 1, '0');
  3153. append(Str, "e+00");
  3154. }
  3155. } else
  3156. Str.push_back('0');
  3157. return;
  3158. case fcNormal:
  3159. break;
  3160. }
  3161. if (isNegative())
  3162. Str.push_back('-');
  3163. // Decompose the number into an APInt and an exponent.
  3164. int exp = exponent - ((int) semantics->precision - 1);
  3165. APInt significand(semantics->precision,
  3166. makeArrayRef(significandParts(),
  3167. partCountForBits(semantics->precision)));
  3168. // Set FormatPrecision if zero. We want to do this before we
  3169. // truncate trailing zeros, as those are part of the precision.
  3170. if (!FormatPrecision) {
  3171. // We use enough digits so the number can be round-tripped back to an
  3172. // APFloat. The formula comes from "How to Print Floating-Point Numbers
  3173. // Accurately" by Steele and White.
  3174. // FIXME: Using a formula based purely on the precision is conservative;
  3175. // we can print fewer digits depending on the actual value being printed.
  3176. // FormatPrecision = 2 + floor(significandBits / lg_2(10))
  3177. FormatPrecision = 2 + semantics->precision * 59 / 196;
  3178. }
  3179. // Ignore trailing binary zeros.
  3180. int trailingZeros = significand.countTrailingZeros();
  3181. exp += trailingZeros;
  3182. significand.lshrInPlace(trailingZeros);
  3183. // Change the exponent from 2^e to 10^e.
  3184. if (exp == 0) {
  3185. // Nothing to do.
  3186. } else if (exp > 0) {
  3187. // Just shift left.
  3188. significand = significand.zext(semantics->precision + exp);
  3189. significand <<= exp;
  3190. exp = 0;
  3191. } else { /* exp < 0 */
  3192. int texp = -exp;
  3193. // We transform this using the identity:
  3194. // (N)(2^-e) == (N)(5^e)(10^-e)
  3195. // This means we have to multiply N (the significand) by 5^e.
  3196. // To avoid overflow, we have to operate on numbers large
  3197. // enough to store N * 5^e:
  3198. // log2(N * 5^e) == log2(N) + e * log2(5)
  3199. // <= semantics->precision + e * 137 / 59
  3200. // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
  3201. unsigned precision = semantics->precision + (137 * texp + 136) / 59;
  3202. // Multiply significand by 5^e.
  3203. // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
  3204. significand = significand.zext(precision);
  3205. APInt five_to_the_i(precision, 5);
  3206. while (true) {
  3207. if (texp & 1) significand *= five_to_the_i;
  3208. texp >>= 1;
  3209. if (!texp) break;
  3210. five_to_the_i *= five_to_the_i;
  3211. }
  3212. }
  3213. AdjustToPrecision(significand, exp, FormatPrecision);
  3214. SmallVector<char, 256> buffer;
  3215. // Fill the buffer.
  3216. unsigned precision = significand.getBitWidth();
  3217. APInt ten(precision, 10);
  3218. APInt digit(precision, 0);
  3219. bool inTrail = true;
  3220. while (significand != 0) {
  3221. // digit <- significand % 10
  3222. // significand <- significand / 10
  3223. APInt::udivrem(significand, ten, significand, digit);
  3224. unsigned d = digit.getZExtValue();
  3225. // Drop trailing zeros.
  3226. if (inTrail && !d) exp++;
  3227. else {
  3228. buffer.push_back((char) ('0' + d));
  3229. inTrail = false;
  3230. }
  3231. }
  3232. assert(!buffer.empty() && "no characters in buffer!");
  3233. // Drop down to FormatPrecision.
  3234. // TODO: don't do more precise calculations above than are required.
  3235. AdjustToPrecision(buffer, exp, FormatPrecision);
  3236. unsigned NDigits = buffer.size();
  3237. // Check whether we should use scientific notation.
  3238. bool FormatScientific;
  3239. if (!FormatMaxPadding)
  3240. FormatScientific = true;
  3241. else {
  3242. if (exp >= 0) {
  3243. // 765e3 --> 765000
  3244. // ^^^
  3245. // But we shouldn't make the number look more precise than it is.
  3246. FormatScientific = ((unsigned) exp > FormatMaxPadding ||
  3247. NDigits + (unsigned) exp > FormatPrecision);
  3248. } else {
  3249. // Power of the most significant digit.
  3250. int MSD = exp + (int) (NDigits - 1);
  3251. if (MSD >= 0) {
  3252. // 765e-2 == 7.65
  3253. FormatScientific = false;
  3254. } else {
  3255. // 765e-5 == 0.00765
  3256. // ^ ^^
  3257. FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
  3258. }
  3259. }
  3260. }
  3261. // Scientific formatting is pretty straightforward.
  3262. if (FormatScientific) {
  3263. exp += (NDigits - 1);
  3264. Str.push_back(buffer[NDigits-1]);
  3265. Str.push_back('.');
  3266. if (NDigits == 1 && TruncateZero)
  3267. Str.push_back('0');
  3268. else
  3269. for (unsigned I = 1; I != NDigits; ++I)
  3270. Str.push_back(buffer[NDigits-1-I]);
  3271. // Fill with zeros up to FormatPrecision.
  3272. if (!TruncateZero && FormatPrecision > NDigits - 1)
  3273. Str.append(FormatPrecision - NDigits + 1, '0');
  3274. // For !TruncateZero we use lower 'e'.
  3275. Str.push_back(TruncateZero ? 'E' : 'e');
  3276. Str.push_back(exp >= 0 ? '+' : '-');
  3277. if (exp < 0) exp = -exp;
  3278. SmallVector<char, 6> expbuf;
  3279. do {
  3280. expbuf.push_back((char) ('0' + (exp % 10)));
  3281. exp /= 10;
  3282. } while (exp);
  3283. // Exponent always at least two digits if we do not truncate zeros.
  3284. if (!TruncateZero && expbuf.size() < 2)
  3285. expbuf.push_back('0');
  3286. for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
  3287. Str.push_back(expbuf[E-1-I]);
  3288. return;
  3289. }
  3290. // Non-scientific, positive exponents.
  3291. if (exp >= 0) {
  3292. for (unsigned I = 0; I != NDigits; ++I)
  3293. Str.push_back(buffer[NDigits-1-I]);
  3294. for (unsigned I = 0; I != (unsigned) exp; ++I)
  3295. Str.push_back('0');
  3296. return;
  3297. }
  3298. // Non-scientific, negative exponents.
  3299. // The number of digits to the left of the decimal point.
  3300. int NWholeDigits = exp + (int) NDigits;
  3301. unsigned I = 0;
  3302. if (NWholeDigits > 0) {
  3303. for (; I != (unsigned) NWholeDigits; ++I)
  3304. Str.push_back(buffer[NDigits-I-1]);
  3305. Str.push_back('.');
  3306. } else {
  3307. unsigned NZeros = 1 + (unsigned) -NWholeDigits;
  3308. Str.push_back('0');
  3309. Str.push_back('.');
  3310. for (unsigned Z = 1; Z != NZeros; ++Z)
  3311. Str.push_back('0');
  3312. }
  3313. for (; I != NDigits; ++I)
  3314. Str.push_back(buffer[NDigits-I-1]);
  3315. }
  3316. bool IEEEFloat::getExactInverse(APFloat *inv) const {
  3317. // Special floats and denormals have no exact inverse.
  3318. if (!isFiniteNonZero())
  3319. return false;
  3320. // Check that the number is a power of two by making sure that only the
  3321. // integer bit is set in the significand.
  3322. if (significandLSB() != semantics->precision - 1)
  3323. return false;
  3324. // Get the inverse.
  3325. IEEEFloat reciprocal(*semantics, 1ULL);
  3326. if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
  3327. return false;
  3328. // Avoid multiplication with a denormal, it is not safe on all platforms and
  3329. // may be slower than a normal division.
  3330. if (reciprocal.isDenormal())
  3331. return false;
  3332. assert(reciprocal.isFiniteNonZero() &&
  3333. reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
  3334. if (inv)
  3335. *inv = APFloat(reciprocal, *semantics);
  3336. return true;
  3337. }
  3338. bool IEEEFloat::isSignaling() const {
  3339. if (!isNaN())
  3340. return false;
  3341. // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
  3342. // first bit of the trailing significand being 0.
  3343. return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
  3344. }
  3345. /// IEEE-754R 2008 5.3.1: nextUp/nextDown.
  3346. ///
  3347. /// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
  3348. /// appropriate sign switching before/after the computation.
  3349. IEEEFloat::opStatus IEEEFloat::next(bool nextDown) {
  3350. // If we are performing nextDown, swap sign so we have -x.
  3351. if (nextDown)
  3352. changeSign();
  3353. // Compute nextUp(x)
  3354. opStatus result = opOK;
  3355. // Handle each float category separately.
  3356. switch (category) {
  3357. case fcInfinity:
  3358. // nextUp(+inf) = +inf
  3359. if (!isNegative())
  3360. break;
  3361. // nextUp(-inf) = -getLargest()
  3362. makeLargest(true);
  3363. break;
  3364. case fcNaN:
  3365. // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
  3366. // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
  3367. // change the payload.
  3368. if (isSignaling()) {
  3369. result = opInvalidOp;
  3370. // For consistency, propagate the sign of the sNaN to the qNaN.
  3371. makeNaN(false, isNegative(), nullptr);
  3372. }
  3373. break;
  3374. case fcZero:
  3375. // nextUp(pm 0) = +getSmallest()
  3376. makeSmallest(false);
  3377. break;
  3378. case fcNormal:
  3379. // nextUp(-getSmallest()) = -0
  3380. if (isSmallest() && isNegative()) {
  3381. APInt::tcSet(significandParts(), 0, partCount());
  3382. category = fcZero;
  3383. exponent = 0;
  3384. break;
  3385. }
  3386. // nextUp(getLargest()) == INFINITY
  3387. if (isLargest() && !isNegative()) {
  3388. APInt::tcSet(significandParts(), 0, partCount());
  3389. category = fcInfinity;
  3390. exponent = semantics->maxExponent + 1;
  3391. break;
  3392. }
  3393. // nextUp(normal) == normal + inc.
  3394. if (isNegative()) {
  3395. // If we are negative, we need to decrement the significand.
  3396. // We only cross a binade boundary that requires adjusting the exponent
  3397. // if:
  3398. // 1. exponent != semantics->minExponent. This implies we are not in the
  3399. // smallest binade or are dealing with denormals.
  3400. // 2. Our significand excluding the integral bit is all zeros.
  3401. bool WillCrossBinadeBoundary =
  3402. exponent != semantics->minExponent && isSignificandAllZeros();
  3403. // Decrement the significand.
  3404. //
  3405. // We always do this since:
  3406. // 1. If we are dealing with a non-binade decrement, by definition we
  3407. // just decrement the significand.
  3408. // 2. If we are dealing with a normal -> normal binade decrement, since
  3409. // we have an explicit integral bit the fact that all bits but the
  3410. // integral bit are zero implies that subtracting one will yield a
  3411. // significand with 0 integral bit and 1 in all other spots. Thus we
  3412. // must just adjust the exponent and set the integral bit to 1.
  3413. // 3. If we are dealing with a normal -> denormal binade decrement,
  3414. // since we set the integral bit to 0 when we represent denormals, we
  3415. // just decrement the significand.
  3416. integerPart *Parts = significandParts();
  3417. APInt::tcDecrement(Parts, partCount());
  3418. if (WillCrossBinadeBoundary) {
  3419. // Our result is a normal number. Do the following:
  3420. // 1. Set the integral bit to 1.
  3421. // 2. Decrement the exponent.
  3422. APInt::tcSetBit(Parts, semantics->precision - 1);
  3423. exponent--;
  3424. }
  3425. } else {
  3426. // If we are positive, we need to increment the significand.
  3427. // We only cross a binade boundary that requires adjusting the exponent if
  3428. // the input is not a denormal and all of said input's significand bits
  3429. // are set. If all of said conditions are true: clear the significand, set
  3430. // the integral bit to 1, and increment the exponent. If we have a
  3431. // denormal always increment since moving denormals and the numbers in the
  3432. // smallest normal binade have the same exponent in our representation.
  3433. bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
  3434. if (WillCrossBinadeBoundary) {
  3435. integerPart *Parts = significandParts();
  3436. APInt::tcSet(Parts, 0, partCount());
  3437. APInt::tcSetBit(Parts, semantics->precision - 1);
  3438. assert(exponent != semantics->maxExponent &&
  3439. "We can not increment an exponent beyond the maxExponent allowed"
  3440. " by the given floating point semantics.");
  3441. exponent++;
  3442. } else {
  3443. incrementSignificand();
  3444. }
  3445. }
  3446. break;
  3447. }
  3448. // If we are performing nextDown, swap sign so we have -nextUp(-x)
  3449. if (nextDown)
  3450. changeSign();
  3451. return result;
  3452. }
  3453. APFloatBase::ExponentType IEEEFloat::exponentNaN() const {
  3454. return semantics->maxExponent + 1;
  3455. }
  3456. APFloatBase::ExponentType IEEEFloat::exponentInf() const {
  3457. return semantics->maxExponent + 1;
  3458. }
  3459. APFloatBase::ExponentType IEEEFloat::exponentZero() const {
  3460. return semantics->minExponent - 1;
  3461. }
  3462. void IEEEFloat::makeInf(bool Negative) {
  3463. category = fcInfinity;
  3464. sign = Negative;
  3465. exponent = exponentInf();
  3466. APInt::tcSet(significandParts(), 0, partCount());
  3467. }
  3468. void IEEEFloat::makeZero(bool Negative) {
  3469. category = fcZero;
  3470. sign = Negative;
  3471. exponent = exponentZero();
  3472. APInt::tcSet(significandParts(), 0, partCount());
  3473. }
  3474. void IEEEFloat::makeQuiet() {
  3475. assert(isNaN());
  3476. APInt::tcSetBit(significandParts(), semantics->precision - 2);
  3477. }
  3478. int ilogb(const IEEEFloat &Arg) {
  3479. if (Arg.isNaN())
  3480. return IEEEFloat::IEK_NaN;
  3481. if (Arg.isZero())
  3482. return IEEEFloat::IEK_Zero;
  3483. if (Arg.isInfinity())
  3484. return IEEEFloat::IEK_Inf;
  3485. if (!Arg.isDenormal())
  3486. return Arg.exponent;
  3487. IEEEFloat Normalized(Arg);
  3488. int SignificandBits = Arg.getSemantics().precision - 1;
  3489. Normalized.exponent += SignificandBits;
  3490. Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero);
  3491. return Normalized.exponent - SignificandBits;
  3492. }
  3493. IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) {
  3494. auto MaxExp = X.getSemantics().maxExponent;
  3495. auto MinExp = X.getSemantics().minExponent;
  3496. // If Exp is wildly out-of-scale, simply adding it to X.exponent will
  3497. // overflow; clamp it to a safe range before adding, but ensure that the range
  3498. // is large enough that the clamp does not change the result. The range we
  3499. // need to support is the difference between the largest possible exponent and
  3500. // the normalized exponent of half the smallest denormal.
  3501. int SignificandBits = X.getSemantics().precision - 1;
  3502. int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
  3503. // Clamp to one past the range ends to let normalize handle overlflow.
  3504. X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement);
  3505. X.normalize(RoundingMode, lfExactlyZero);
  3506. if (X.isNaN())
  3507. X.makeQuiet();
  3508. return X;
  3509. }
  3510. IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) {
  3511. Exp = ilogb(Val);
  3512. // Quiet signalling nans.
  3513. if (Exp == IEEEFloat::IEK_NaN) {
  3514. IEEEFloat Quiet(Val);
  3515. Quiet.makeQuiet();
  3516. return Quiet;
  3517. }
  3518. if (Exp == IEEEFloat::IEK_Inf)
  3519. return Val;
  3520. // 1 is added because frexp is defined to return a normalized fraction in
  3521. // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
  3522. Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1;
  3523. return scalbn(Val, -Exp, RM);
  3524. }
  3525. DoubleAPFloat::DoubleAPFloat(const fltSemantics &S)
  3526. : Semantics(&S),
  3527. Floats(new APFloat[2]{APFloat(semIEEEdouble), APFloat(semIEEEdouble)}) {
  3528. assert(Semantics == &semPPCDoubleDouble);
  3529. }
  3530. DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag)
  3531. : Semantics(&S),
  3532. Floats(new APFloat[2]{APFloat(semIEEEdouble, uninitialized),
  3533. APFloat(semIEEEdouble, uninitialized)}) {
  3534. assert(Semantics == &semPPCDoubleDouble);
  3535. }
  3536. DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I)
  3537. : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, I),
  3538. APFloat(semIEEEdouble)}) {
  3539. assert(Semantics == &semPPCDoubleDouble);
  3540. }
  3541. DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I)
  3542. : Semantics(&S),
  3543. Floats(new APFloat[2]{
  3544. APFloat(semIEEEdouble, APInt(64, I.getRawData()[0])),
  3545. APFloat(semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
  3546. assert(Semantics == &semPPCDoubleDouble);
  3547. }
  3548. DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First,
  3549. APFloat &&Second)
  3550. : Semantics(&S),
  3551. Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
  3552. assert(Semantics == &semPPCDoubleDouble);
  3553. assert(&Floats[0].getSemantics() == &semIEEEdouble);
  3554. assert(&Floats[1].getSemantics() == &semIEEEdouble);
  3555. }
  3556. DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS)
  3557. : Semantics(RHS.Semantics),
  3558. Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
  3559. APFloat(RHS.Floats[1])}
  3560. : nullptr) {
  3561. assert(Semantics == &semPPCDoubleDouble);
  3562. }
  3563. DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS)
  3564. : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
  3565. RHS.Semantics = &semBogus;
  3566. assert(Semantics == &semPPCDoubleDouble);
  3567. }
  3568. DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) {
  3569. if (Semantics == RHS.Semantics && RHS.Floats) {
  3570. Floats[0] = RHS.Floats[0];
  3571. Floats[1] = RHS.Floats[1];
  3572. } else if (this != &RHS) {
  3573. this->~DoubleAPFloat();
  3574. new (this) DoubleAPFloat(RHS);
  3575. }
  3576. return *this;
  3577. }
  3578. // Implement addition, subtraction, multiplication and division based on:
  3579. // "Software for Doubled-Precision Floating-Point Computations",
  3580. // by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
  3581. APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
  3582. const APFloat &c, const APFloat &cc,
  3583. roundingMode RM) {
  3584. int Status = opOK;
  3585. APFloat z = a;
  3586. Status |= z.add(c, RM);
  3587. if (!z.isFinite()) {
  3588. if (!z.isInfinity()) {
  3589. Floats[0] = std::move(z);
  3590. Floats[1].makeZero(/* Neg = */ false);
  3591. return (opStatus)Status;
  3592. }
  3593. Status = opOK;
  3594. auto AComparedToC = a.compareAbsoluteValue(c);
  3595. z = cc;
  3596. Status |= z.add(aa, RM);
  3597. if (AComparedToC == APFloat::cmpGreaterThan) {
  3598. // z = cc + aa + c + a;
  3599. Status |= z.add(c, RM);
  3600. Status |= z.add(a, RM);
  3601. } else {
  3602. // z = cc + aa + a + c;
  3603. Status |= z.add(a, RM);
  3604. Status |= z.add(c, RM);
  3605. }
  3606. if (!z.isFinite()) {
  3607. Floats[0] = std::move(z);
  3608. Floats[1].makeZero(/* Neg = */ false);
  3609. return (opStatus)Status;
  3610. }
  3611. Floats[0] = z;
  3612. APFloat zz = aa;
  3613. Status |= zz.add(cc, RM);
  3614. if (AComparedToC == APFloat::cmpGreaterThan) {
  3615. // Floats[1] = a - z + c + zz;
  3616. Floats[1] = a;
  3617. Status |= Floats[1].subtract(z, RM);
  3618. Status |= Floats[1].add(c, RM);
  3619. Status |= Floats[1].add(zz, RM);
  3620. } else {
  3621. // Floats[1] = c - z + a + zz;
  3622. Floats[1] = c;
  3623. Status |= Floats[1].subtract(z, RM);
  3624. Status |= Floats[1].add(a, RM);
  3625. Status |= Floats[1].add(zz, RM);
  3626. }
  3627. } else {
  3628. // q = a - z;
  3629. APFloat q = a;
  3630. Status |= q.subtract(z, RM);
  3631. // zz = q + c + (a - (q + z)) + aa + cc;
  3632. // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
  3633. auto zz = q;
  3634. Status |= zz.add(c, RM);
  3635. Status |= q.add(z, RM);
  3636. Status |= q.subtract(a, RM);
  3637. q.changeSign();
  3638. Status |= zz.add(q, RM);
  3639. Status |= zz.add(aa, RM);
  3640. Status |= zz.add(cc, RM);
  3641. if (zz.isZero() && !zz.isNegative()) {
  3642. Floats[0] = std::move(z);
  3643. Floats[1].makeZero(/* Neg = */ false);
  3644. return opOK;
  3645. }
  3646. Floats[0] = z;
  3647. Status |= Floats[0].add(zz, RM);
  3648. if (!Floats[0].isFinite()) {
  3649. Floats[1].makeZero(/* Neg = */ false);
  3650. return (opStatus)Status;
  3651. }
  3652. Floats[1] = std::move(z);
  3653. Status |= Floats[1].subtract(Floats[0], RM);
  3654. Status |= Floats[1].add(zz, RM);
  3655. }
  3656. return (opStatus)Status;
  3657. }
  3658. APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
  3659. const DoubleAPFloat &RHS,
  3660. DoubleAPFloat &Out,
  3661. roundingMode RM) {
  3662. if (LHS.getCategory() == fcNaN) {
  3663. Out = LHS;
  3664. return opOK;
  3665. }
  3666. if (RHS.getCategory() == fcNaN) {
  3667. Out = RHS;
  3668. return opOK;
  3669. }
  3670. if (LHS.getCategory() == fcZero) {
  3671. Out = RHS;
  3672. return opOK;
  3673. }
  3674. if (RHS.getCategory() == fcZero) {
  3675. Out = LHS;
  3676. return opOK;
  3677. }
  3678. if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
  3679. LHS.isNegative() != RHS.isNegative()) {
  3680. Out.makeNaN(false, Out.isNegative(), nullptr);
  3681. return opInvalidOp;
  3682. }
  3683. if (LHS.getCategory() == fcInfinity) {
  3684. Out = LHS;
  3685. return opOK;
  3686. }
  3687. if (RHS.getCategory() == fcInfinity) {
  3688. Out = RHS;
  3689. return opOK;
  3690. }
  3691. assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
  3692. APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
  3693. CC(RHS.Floats[1]);
  3694. assert(&A.getSemantics() == &semIEEEdouble);
  3695. assert(&AA.getSemantics() == &semIEEEdouble);
  3696. assert(&C.getSemantics() == &semIEEEdouble);
  3697. assert(&CC.getSemantics() == &semIEEEdouble);
  3698. assert(&Out.Floats[0].getSemantics() == &semIEEEdouble);
  3699. assert(&Out.Floats[1].getSemantics() == &semIEEEdouble);
  3700. return Out.addImpl(A, AA, C, CC, RM);
  3701. }
  3702. APFloat::opStatus DoubleAPFloat::add(const DoubleAPFloat &RHS,
  3703. roundingMode RM) {
  3704. return addWithSpecial(*this, RHS, *this, RM);
  3705. }
  3706. APFloat::opStatus DoubleAPFloat::subtract(const DoubleAPFloat &RHS,
  3707. roundingMode RM) {
  3708. changeSign();
  3709. auto Ret = add(RHS, RM);
  3710. changeSign();
  3711. return Ret;
  3712. }
  3713. APFloat::opStatus DoubleAPFloat::multiply(const DoubleAPFloat &RHS,
  3714. APFloat::roundingMode RM) {
  3715. const auto &LHS = *this;
  3716. auto &Out = *this;
  3717. /* Interesting observation: For special categories, finding the lowest
  3718. common ancestor of the following layered graph gives the correct
  3719. return category:
  3720. NaN
  3721. / \
  3722. Zero Inf
  3723. \ /
  3724. Normal
  3725. e.g. NaN * NaN = NaN
  3726. Zero * Inf = NaN
  3727. Normal * Zero = Zero
  3728. Normal * Inf = Inf
  3729. */
  3730. if (LHS.getCategory() == fcNaN) {
  3731. Out = LHS;
  3732. return opOK;
  3733. }
  3734. if (RHS.getCategory() == fcNaN) {
  3735. Out = RHS;
  3736. return opOK;
  3737. }
  3738. if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
  3739. (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
  3740. Out.makeNaN(false, false, nullptr);
  3741. return opOK;
  3742. }
  3743. if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
  3744. Out = LHS;
  3745. return opOK;
  3746. }
  3747. if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
  3748. Out = RHS;
  3749. return opOK;
  3750. }
  3751. assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
  3752. "Special cases not handled exhaustively");
  3753. int Status = opOK;
  3754. APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
  3755. // t = a * c
  3756. APFloat T = A;
  3757. Status |= T.multiply(C, RM);
  3758. if (!T.isFiniteNonZero()) {
  3759. Floats[0] = T;
  3760. Floats[1].makeZero(/* Neg = */ false);
  3761. return (opStatus)Status;
  3762. }
  3763. // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
  3764. APFloat Tau = A;
  3765. T.changeSign();
  3766. Status |= Tau.fusedMultiplyAdd(C, T, RM);
  3767. T.changeSign();
  3768. {
  3769. // v = a * d
  3770. APFloat V = A;
  3771. Status |= V.multiply(D, RM);
  3772. // w = b * c
  3773. APFloat W = B;
  3774. Status |= W.multiply(C, RM);
  3775. Status |= V.add(W, RM);
  3776. // tau += v + w
  3777. Status |= Tau.add(V, RM);
  3778. }
  3779. // u = t + tau
  3780. APFloat U = T;
  3781. Status |= U.add(Tau, RM);
  3782. Floats[0] = U;
  3783. if (!U.isFinite()) {
  3784. Floats[1].makeZero(/* Neg = */ false);
  3785. } else {
  3786. // Floats[1] = (t - u) + tau
  3787. Status |= T.subtract(U, RM);
  3788. Status |= T.add(Tau, RM);
  3789. Floats[1] = T;
  3790. }
  3791. return (opStatus)Status;
  3792. }
  3793. APFloat::opStatus DoubleAPFloat::divide(const DoubleAPFloat &RHS,
  3794. APFloat::roundingMode RM) {
  3795. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3796. APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
  3797. auto Ret =
  3798. Tmp.divide(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
  3799. *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
  3800. return Ret;
  3801. }
  3802. APFloat::opStatus DoubleAPFloat::remainder(const DoubleAPFloat &RHS) {
  3803. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3804. APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
  3805. auto Ret =
  3806. Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
  3807. *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
  3808. return Ret;
  3809. }
  3810. APFloat::opStatus DoubleAPFloat::mod(const DoubleAPFloat &RHS) {
  3811. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3812. APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
  3813. auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
  3814. *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
  3815. return Ret;
  3816. }
  3817. APFloat::opStatus
  3818. DoubleAPFloat::fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
  3819. const DoubleAPFloat &Addend,
  3820. APFloat::roundingMode RM) {
  3821. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3822. APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
  3823. auto Ret = Tmp.fusedMultiplyAdd(
  3824. APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()),
  3825. APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM);
  3826. *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
  3827. return Ret;
  3828. }
  3829. APFloat::opStatus DoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) {
  3830. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3831. APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
  3832. auto Ret = Tmp.roundToIntegral(RM);
  3833. *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
  3834. return Ret;
  3835. }
  3836. void DoubleAPFloat::changeSign() {
  3837. Floats[0].changeSign();
  3838. Floats[1].changeSign();
  3839. }
  3840. APFloat::cmpResult
  3841. DoubleAPFloat::compareAbsoluteValue(const DoubleAPFloat &RHS) const {
  3842. auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
  3843. if (Result != cmpEqual)
  3844. return Result;
  3845. Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
  3846. if (Result == cmpLessThan || Result == cmpGreaterThan) {
  3847. auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
  3848. auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative();
  3849. if (Against && !RHSAgainst)
  3850. return cmpLessThan;
  3851. if (!Against && RHSAgainst)
  3852. return cmpGreaterThan;
  3853. if (!Against && !RHSAgainst)
  3854. return Result;
  3855. if (Against && RHSAgainst)
  3856. return (cmpResult)(cmpLessThan + cmpGreaterThan - Result);
  3857. }
  3858. return Result;
  3859. }
  3860. APFloat::fltCategory DoubleAPFloat::getCategory() const {
  3861. return Floats[0].getCategory();
  3862. }
  3863. bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
  3864. void DoubleAPFloat::makeInf(bool Neg) {
  3865. Floats[0].makeInf(Neg);
  3866. Floats[1].makeZero(/* Neg = */ false);
  3867. }
  3868. void DoubleAPFloat::makeZero(bool Neg) {
  3869. Floats[0].makeZero(Neg);
  3870. Floats[1].makeZero(/* Neg = */ false);
  3871. }
  3872. void DoubleAPFloat::makeLargest(bool Neg) {
  3873. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3874. Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
  3875. Floats[1] = APFloat(semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
  3876. if (Neg)
  3877. changeSign();
  3878. }
  3879. void DoubleAPFloat::makeSmallest(bool Neg) {
  3880. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3881. Floats[0].makeSmallest(Neg);
  3882. Floats[1].makeZero(/* Neg = */ false);
  3883. }
  3884. void DoubleAPFloat::makeSmallestNormalized(bool Neg) {
  3885. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3886. Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x0360000000000000ull));
  3887. if (Neg)
  3888. Floats[0].changeSign();
  3889. Floats[1].makeZero(/* Neg = */ false);
  3890. }
  3891. void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
  3892. Floats[0].makeNaN(SNaN, Neg, fill);
  3893. Floats[1].makeZero(/* Neg = */ false);
  3894. }
  3895. APFloat::cmpResult DoubleAPFloat::compare(const DoubleAPFloat &RHS) const {
  3896. auto Result = Floats[0].compare(RHS.Floats[0]);
  3897. // |Float[0]| > |Float[1]|
  3898. if (Result == APFloat::cmpEqual)
  3899. return Floats[1].compare(RHS.Floats[1]);
  3900. return Result;
  3901. }
  3902. bool DoubleAPFloat::bitwiseIsEqual(const DoubleAPFloat &RHS) const {
  3903. return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
  3904. Floats[1].bitwiseIsEqual(RHS.Floats[1]);
  3905. }
  3906. hash_code hash_value(const DoubleAPFloat &Arg) {
  3907. if (Arg.Floats)
  3908. return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
  3909. return hash_combine(Arg.Semantics);
  3910. }
  3911. APInt DoubleAPFloat::bitcastToAPInt() const {
  3912. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3913. uint64_t Data[] = {
  3914. Floats[0].bitcastToAPInt().getRawData()[0],
  3915. Floats[1].bitcastToAPInt().getRawData()[0],
  3916. };
  3917. return APInt(128, 2, Data);
  3918. }
  3919. Expected<APFloat::opStatus> DoubleAPFloat::convertFromString(StringRef S,
  3920. roundingMode RM) {
  3921. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3922. APFloat Tmp(semPPCDoubleDoubleLegacy);
  3923. auto Ret = Tmp.convertFromString(S, RM);
  3924. *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
  3925. return Ret;
  3926. }
  3927. APFloat::opStatus DoubleAPFloat::next(bool nextDown) {
  3928. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3929. APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
  3930. auto Ret = Tmp.next(nextDown);
  3931. *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
  3932. return Ret;
  3933. }
  3934. APFloat::opStatus
  3935. DoubleAPFloat::convertToInteger(MutableArrayRef<integerPart> Input,
  3936. unsigned int Width, bool IsSigned,
  3937. roundingMode RM, bool *IsExact) const {
  3938. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3939. return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
  3940. .convertToInteger(Input, Width, IsSigned, RM, IsExact);
  3941. }
  3942. APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input,
  3943. bool IsSigned,
  3944. roundingMode RM) {
  3945. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3946. APFloat Tmp(semPPCDoubleDoubleLegacy);
  3947. auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM);
  3948. *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
  3949. return Ret;
  3950. }
  3951. APFloat::opStatus
  3952. DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input,
  3953. unsigned int InputSize,
  3954. bool IsSigned, roundingMode RM) {
  3955. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3956. APFloat Tmp(semPPCDoubleDoubleLegacy);
  3957. auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM);
  3958. *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
  3959. return Ret;
  3960. }
  3961. APFloat::opStatus
  3962. DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input,
  3963. unsigned int InputSize,
  3964. bool IsSigned, roundingMode RM) {
  3965. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3966. APFloat Tmp(semPPCDoubleDoubleLegacy);
  3967. auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM);
  3968. *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
  3969. return Ret;
  3970. }
  3971. unsigned int DoubleAPFloat::convertToHexString(char *DST,
  3972. unsigned int HexDigits,
  3973. bool UpperCase,
  3974. roundingMode RM) const {
  3975. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  3976. return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
  3977. .convertToHexString(DST, HexDigits, UpperCase, RM);
  3978. }
  3979. bool DoubleAPFloat::isDenormal() const {
  3980. return getCategory() == fcNormal &&
  3981. (Floats[0].isDenormal() || Floats[1].isDenormal() ||
  3982. // (double)(Hi + Lo) == Hi defines a normal number.
  3983. Floats[0] != Floats[0] + Floats[1]);
  3984. }
  3985. bool DoubleAPFloat::isSmallest() const {
  3986. if (getCategory() != fcNormal)
  3987. return false;
  3988. DoubleAPFloat Tmp(*this);
  3989. Tmp.makeSmallest(this->isNegative());
  3990. return Tmp.compare(*this) == cmpEqual;
  3991. }
  3992. bool DoubleAPFloat::isLargest() const {
  3993. if (getCategory() != fcNormal)
  3994. return false;
  3995. DoubleAPFloat Tmp(*this);
  3996. Tmp.makeLargest(this->isNegative());
  3997. return Tmp.compare(*this) == cmpEqual;
  3998. }
  3999. bool DoubleAPFloat::isInteger() const {
  4000. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  4001. return Floats[0].isInteger() && Floats[1].isInteger();
  4002. }
  4003. void DoubleAPFloat::toString(SmallVectorImpl<char> &Str,
  4004. unsigned FormatPrecision,
  4005. unsigned FormatMaxPadding,
  4006. bool TruncateZero) const {
  4007. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  4008. APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
  4009. .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
  4010. }
  4011. bool DoubleAPFloat::getExactInverse(APFloat *inv) const {
  4012. assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  4013. APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
  4014. if (!inv)
  4015. return Tmp.getExactInverse(nullptr);
  4016. APFloat Inv(semPPCDoubleDoubleLegacy);
  4017. auto Ret = Tmp.getExactInverse(&Inv);
  4018. *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt());
  4019. return Ret;
  4020. }
  4021. DoubleAPFloat scalbn(const DoubleAPFloat &Arg, int Exp,
  4022. APFloat::roundingMode RM) {
  4023. assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  4024. return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM),
  4025. scalbn(Arg.Floats[1], Exp, RM));
  4026. }
  4027. DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
  4028. APFloat::roundingMode RM) {
  4029. assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
  4030. APFloat First = frexp(Arg.Floats[0], Exp, RM);
  4031. APFloat Second = Arg.Floats[1];
  4032. if (Arg.getCategory() == APFloat::fcNormal)
  4033. Second = scalbn(Second, -Exp, RM);
  4034. return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second));
  4035. }
  4036. } // namespace detail
  4037. APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
  4038. if (usesLayout<IEEEFloat>(Semantics)) {
  4039. new (&IEEE) IEEEFloat(std::move(F));
  4040. return;
  4041. }
  4042. if (usesLayout<DoubleAPFloat>(Semantics)) {
  4043. const fltSemantics& S = F.getSemantics();
  4044. new (&Double)
  4045. DoubleAPFloat(Semantics, APFloat(std::move(F), S),
  4046. APFloat(semIEEEdouble));
  4047. return;
  4048. }
  4049. llvm_unreachable("Unexpected semantics");
  4050. }
  4051. Expected<APFloat::opStatus> APFloat::convertFromString(StringRef Str,
  4052. roundingMode RM) {
  4053. APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM));
  4054. }
  4055. hash_code hash_value(const APFloat &Arg) {
  4056. if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
  4057. return hash_value(Arg.U.IEEE);
  4058. if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
  4059. return hash_value(Arg.U.Double);
  4060. llvm_unreachable("Unexpected semantics");
  4061. }
  4062. APFloat::APFloat(const fltSemantics &Semantics, StringRef S)
  4063. : APFloat(Semantics) {
  4064. auto StatusOrErr = convertFromString(S, rmNearestTiesToEven);
  4065. assert(StatusOrErr && "Invalid floating point representation");
  4066. consumeError(StatusOrErr.takeError());
  4067. }
  4068. APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics,
  4069. roundingMode RM, bool *losesInfo) {
  4070. if (&getSemantics() == &ToSemantics) {
  4071. *losesInfo = false;
  4072. return opOK;
  4073. }
  4074. if (usesLayout<IEEEFloat>(getSemantics()) &&
  4075. usesLayout<IEEEFloat>(ToSemantics))
  4076. return U.IEEE.convert(ToSemantics, RM, losesInfo);
  4077. if (usesLayout<IEEEFloat>(getSemantics()) &&
  4078. usesLayout<DoubleAPFloat>(ToSemantics)) {
  4079. assert(&ToSemantics == &semPPCDoubleDouble);
  4080. auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo);
  4081. *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
  4082. return Ret;
  4083. }
  4084. if (usesLayout<DoubleAPFloat>(getSemantics()) &&
  4085. usesLayout<IEEEFloat>(ToSemantics)) {
  4086. auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
  4087. *this = APFloat(std::move(getIEEE()), ToSemantics);
  4088. return Ret;
  4089. }
  4090. llvm_unreachable("Unexpected semantics");
  4091. }
  4092. APFloat APFloat::getAllOnesValue(const fltSemantics &Semantics) {
  4093. return APFloat(Semantics, APInt::getAllOnes(Semantics.sizeInBits));
  4094. }
  4095. void APFloat::print(raw_ostream &OS) const {
  4096. SmallVector<char, 16> Buffer;
  4097. toString(Buffer);
  4098. OS << Buffer << "\n";
  4099. }
  4100. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  4101. LLVM_DUMP_METHOD void APFloat::dump() const { print(dbgs()); }
  4102. #endif
  4103. void APFloat::Profile(FoldingSetNodeID &NID) const {
  4104. NID.Add(bitcastToAPInt());
  4105. }
  4106. /* Same as convertToInteger(integerPart*, ...), except the result is returned in
  4107. an APSInt, whose initial bit-width and signed-ness are used to determine the
  4108. precision of the conversion.
  4109. */
  4110. APFloat::opStatus APFloat::convertToInteger(APSInt &result,
  4111. roundingMode rounding_mode,
  4112. bool *isExact) const {
  4113. unsigned bitWidth = result.getBitWidth();
  4114. SmallVector<uint64_t, 4> parts(result.getNumWords());
  4115. opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
  4116. rounding_mode, isExact);
  4117. // Keeps the original signed-ness.
  4118. result = APInt(bitWidth, parts);
  4119. return status;
  4120. }
  4121. double APFloat::convertToDouble() const {
  4122. if (&getSemantics() == (const llvm::fltSemantics *)&semIEEEdouble)
  4123. return getIEEE().convertToDouble();
  4124. assert(getSemantics().isRepresentableBy(semIEEEdouble) &&
  4125. "Float semantics is not representable by IEEEdouble");
  4126. APFloat Temp = *this;
  4127. bool LosesInfo;
  4128. opStatus St = Temp.convert(semIEEEdouble, rmNearestTiesToEven, &LosesInfo);
  4129. assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
  4130. (void)St;
  4131. return Temp.getIEEE().convertToDouble();
  4132. }
  4133. float APFloat::convertToFloat() const {
  4134. if (&getSemantics() == (const llvm::fltSemantics *)&semIEEEsingle)
  4135. return getIEEE().convertToFloat();
  4136. assert(getSemantics().isRepresentableBy(semIEEEsingle) &&
  4137. "Float semantics is not representable by IEEEsingle");
  4138. APFloat Temp = *this;
  4139. bool LosesInfo;
  4140. opStatus St = Temp.convert(semIEEEsingle, rmNearestTiesToEven, &LosesInfo);
  4141. assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
  4142. (void)St;
  4143. return Temp.getIEEE().convertToFloat();
  4144. }
  4145. } // namespace llvm
  4146. #undef APFLOAT_DISPATCH_ON_SEMANTICS